Decompiled source of VoiceBox v0.3.4

VoiceBoxModLib.Core.dll

Decompiled 2 weeks ago
using System;
using System.ClientModel;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.WebSockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CognitiveServices.Speech;
using Microsoft.CognitiveServices.Speech.Audio;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
using NAudio.CoreAudioApi;
using NAudio.MediaFoundation;
using NAudio.Wave;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OllamaSharp;
using OpenAI;
using TimShaw.VoiceBox.Components;
using TimShaw.VoiceBox.Core;
using TimShaw.VoiceBox.Data;
using TimShaw.VoiceBox.GUI;
using TimShaw.VoiceBox.Generics;
using TimShaw.VoiceBox.Modding;
using UnityEngine;
using UnityEngine.Networking;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("VoiceBoxModLib.Core")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.4.0")]
[assembly: AssemblyInformationalVersion("0.3.4+8df47c835b89e3c9278a4984060ef6efbdf76fe6")]
[assembly: AssemblyProduct("VoiceBoxModLib.Core")]
[assembly: AssemblyTitle("VoiceBoxModLib.Core")]
[assembly: AssemblyVersion("0.3.4.0")]
public class APITester : MonoBehaviour
{
	[CompilerGenerated]
	private sealed class <>c__DisplayClass15_0
	{
		public bool waitingForTTS;

		public float clipLength;

		public APITester <>4__this;

		internal void <TestTextToSpeech>b__0(string path)
		{
			Debug.Log((object)("[Test: Text To Speech 1] Generated audio file at " + path));
			waitingForTTS = false;
		}

		internal void <TestTextToSpeech>b__2(AudioClip audioClip)
		{
			Debug.Log((object)"[Test: Text To Speech 2] Generated audioclip and playing...");
			clipLength = audioClip.length;
			waitingForTTS = false;
			<>4__this.audioSource.PlayOneShot(audioClip);
		}

		internal void <TestTextToSpeech>b__3(string err)
		{
			Debug.LogError((object)err);
			waitingForTTS = false;
		}
	}

	[CompilerGenerated]
	private sealed class <>c__DisplayClass16_0
	{
		public bool waitingForResponse;

		public string combinedResponse;

		internal void <TestChat>b__0(ChatUtils.VoiceBoxChatMessage chatMessage)
		{
			//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)
			ChatRole role = ((ChatMessage)chatMessage).Role;
			Debug.Log((object)(((object)(ChatRole)(ref role)).ToString() + ": " + chatMessage.Text));
			waitingForResponse = false;
		}

		internal void <TestChat>b__1(string error)
		{
			Debug.LogError((object)error);
			waitingForResponse = false;
		}

		internal void <TestChat>b__2(ChatResponseUpdate chunk)
		{
			Debug.Log((object)(chunk.Role.ToString() + ": " + chunk.Text));
			combinedResponse += (object)chunk;
		}

		internal void <TestChat>b__3()
		{
			Debug.Log((object)("Combined response: " + combinedResponse));
			waitingForResponse = false;
		}

		internal void <TestChat>b__4(string error)
		{
			Debug.LogError((object)error);
			waitingForResponse = false;
		}

		internal void <TestChat>b__5(ChatUtils.VoiceBoxChatMessage chatMessage)
		{
			//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)
			ChatRole role = ((ChatMessage)chatMessage).Role;
			Debug.Log((object)(((object)(ChatRole)(ref role)).ToString() + ": " + chatMessage.Text));
			waitingForResponse = false;
		}

		internal void <TestChat>b__6(string error)
		{
			Debug.LogError((object)error);
			waitingForResponse = false;
		}

		internal void <TestChat>b__7(ChatUtils.VoiceBoxChatMessage chatMessage)
		{
			//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)
			ChatRole role = ((ChatMessage)chatMessage).Role;
			Debug.Log((object)(((object)(ChatRole)(ref role)).ToString() + ": " + chatMessage.Text));
			waitingForResponse = false;
		}

		internal void <TestChat>b__8(string error)
		{
			Debug.LogError((object)error);
			waitingForResponse = false;
		}
	}

	[CompilerGenerated]
	private sealed class <TestChat>d__16 : IEnumerator<object>, IEnumerator, IDisposable
	{
		private int <>1__state;

		private object <>2__current;

		public APITester <>4__this;

		private <>c__DisplayClass16_0 <>8__1;

		private List<ChatUtils.VoiceBoxChatMessage> <chats>5__2;

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

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

		[DebuggerHidden]
		public <TestChat>d__16(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<>8__1 = null;
			<chats>5__2 = null;
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Expected O, but got Unknown
			//IL_01ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Expected O, but got Unknown
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_029d: Expected O, but got Unknown
			int num = <>1__state;
			APITester aPITester = <>4__this;
			ChatUtils.VoiceBoxChatMessage item;
			ChatUtils.VoiceBoxChatMessage item2;
			ChatUtils.VoiceBoxChatTool item3;
			ChatUtils.VoiceBoxChatCompletionOptions options;
			ChatUtils.VoiceBoxChatTool item4;
			ChatUtils.VoiceBoxChatCompletionOptions voiceBoxChatCompletionOptions;
			ChatUtils.VoiceBoxChatMessage item5;
			switch (num)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				<>8__1 = new <>c__DisplayClass16_0();
				goto IL_0062;
			case 1:
				<>1__state = -1;
				goto IL_0062;
			case 2:
				<>1__state = -1;
				goto IL_0123;
			case 3:
				<>1__state = -1;
				goto IL_01c6;
			case 4:
				<>1__state = -1;
				goto IL_02ad;
			case 5:
				{
					<>1__state = -1;
					return false;
				}
				IL_0062:
				if (aPITester.testIsRunning)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 1;
					return true;
				}
				aPITester.testIsRunning = true;
				<>8__1.waitingForResponse = false;
				Debug.Log((object)"VoiceBox: Testing Chat");
				Debug.Log((object)"[Test: Chat 1] Simple chat request");
				<chats>5__2 = new List<ChatUtils.VoiceBoxChatMessage>();
				item = new ChatUtils.VoiceBoxChatMessage(ChatUtils.VoiceBoxChatRole.User, "Write a 1 paragraph essay about huskies. ");
				<chats>5__2.Add(item);
				<>8__1.waitingForResponse = true;
				AIManager.Instance.SendChatMessage(<chats>5__2, delegate(ChatUtils.VoiceBoxChatMessage chatMessage)
				{
					//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)
					ChatRole role3 = ((ChatMessage)chatMessage).Role;
					Debug.Log((object)(((object)(ChatRole)(ref role3)).ToString() + ": " + chatMessage.Text));
					<>8__1.waitingForResponse = false;
				}, delegate(string error)
				{
					Debug.LogError((object)error);
					<>8__1.waitingForResponse = false;
				});
				goto IL_0123;
				IL_0123:
				if (<>8__1.waitingForResponse)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 2;
					return true;
				}
				<>8__1.combinedResponse = "";
				Debug.Log((object)"[Test: Chat 2] Simple streaming chat request");
				<>8__1.waitingForResponse = true;
				AIManager.Instance.StreamChatMessage(<chats>5__2, delegate(ChatResponseUpdate chunk)
				{
					Debug.Log((object)(chunk.Role.ToString() + ": " + chunk.Text));
					<>8__1.combinedResponse += (object)chunk;
				}, delegate
				{
					Debug.Log((object)("Combined response: " + <>8__1.combinedResponse));
					<>8__1.waitingForResponse = false;
				}, delegate(string error)
				{
					Debug.LogError((object)error);
					<>8__1.waitingForResponse = false;
				});
				goto IL_01c6;
				IL_02ad:
				if (<>8__1.waitingForResponse)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 4;
					return true;
				}
				Debug.Log((object)"[Test: Chat 4] Simple chat request with complex tool");
				item2 = new ChatUtils.VoiceBoxChatMessage(ChatUtils.VoiceBoxChatRole.User, "Display a Vector2 (1.00, 2.00) and a Quaterion (4.00, 4.00, 4.00) to the console");
				<chats>5__2.Clear();
				<chats>5__2.Add(item2);
				item3 = new ChatUtils.VoiceBoxChatTool(aPITester, "SampleTool3", "Displays a provided vector2 and quaternion to the console.", new List<JsonConverter>
				{
					new ChatUtils.ColorJsonConverter()
				});
				options = new ChatUtils.VoiceBoxChatCompletionOptions
				{
					VoiceBoxTools = { item3 }
				};
				<>8__1.waitingForResponse = true;
				AIManager.Instance.SendChatMessage(<chats>5__2, delegate(ChatUtils.VoiceBoxChatMessage chatMessage)
				{
					//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)
					ChatRole role2 = ((ChatMessage)chatMessage).Role;
					Debug.Log((object)(((object)(ChatRole)(ref role2)).ToString() + ": " + chatMessage.Text));
					<>8__1.waitingForResponse = false;
				}, delegate(string error)
				{
					Debug.LogError((object)error);
					<>8__1.waitingForResponse = false;
				}, options);
				Debug.Log((object)"VoiceBox: Finished Testing Chat");
				<>2__current = null;
				<>1__state = 5;
				return true;
				IL_01c6:
				if (<>8__1.waitingForResponse)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 3;
					return true;
				}
				Debug.Log((object)"[Test: Chat 3] Simple chat request with tool");
				item4 = new ChatUtils.VoiceBoxChatTool(aPITester, "SampleTool1", "Displays provided text in the console");
				voiceBoxChatCompletionOptions = new ChatUtils.VoiceBoxChatCompletionOptions
				{
					VoiceBoxTools = { item4 }
				};
				Debug.Log((object)((ChatOptions)voiceBoxChatCompletionOptions).Tools.Count);
				item5 = new ChatUtils.VoiceBoxChatMessage(ChatUtils.VoiceBoxChatRole.User, "Write a 1 paragraph essay about huskies. Then, display the first sentence to the console. Only display one sentence to the console.");
				<chats>5__2.Clear();
				<chats>5__2.Add(item5);
				<>8__1.waitingForResponse = true;
				AIManager.Instance.SendChatMessage(<chats>5__2, delegate(ChatUtils.VoiceBoxChatMessage chatMessage)
				{
					//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)
					ChatRole role = ((ChatMessage)chatMessage).Role;
					Debug.Log((object)(((object)(ChatRole)(ref role)).ToString() + ": " + chatMessage.Text));
					<>8__1.waitingForResponse = false;
				}, delegate(string error)
				{
					Debug.LogError((object)error);
					<>8__1.waitingForResponse = false;
				}, voiceBoxChatCompletionOptions);
				goto IL_02ad;
			}
		}

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

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	[CompilerGenerated]
	private sealed class <TestModdingTools>d__13 : IEnumerator<object>, IEnumerator, IDisposable
	{
		private int <>1__state;

		private object <>2__current;

		public APITester <>4__this;

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

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

		[DebuggerHidden]
		public <TestModdingTools>d__13(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			int num = <>1__state;
			APITester aPITester = <>4__this;
			switch (num)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				goto IL_004b;
			case 1:
				<>1__state = -1;
				goto IL_004b;
			case 2:
				{
					<>1__state = -1;
					return false;
				}
				IL_004b:
				if (aPITester.testIsRunning)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 1;
					return true;
				}
				aPITester.testIsRunning = true;
				Debug.Log((object)"VoiceBox: Testing Modding Tools");
				Debug.Log((object)"[Test: ModdingTools] Create AIManager using ModdingTools");
				ModdingTools.CreateAIManagerObject<GeminiServiceConfig, AzureSTTServiceConfig, ElevenlabsTTSServiceConfig>();
				Debug.Log((object)"VoiceBox: Finished Testing Modding Tools");
				aPITester.testIsRunning = false;
				<>2__current = null;
				<>1__state = 2;
				return true;
			}
		}

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

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	[CompilerGenerated]
	private sealed class <TestSpeechToText>d__14 : IEnumerator<object>, IEnumerator, IDisposable
	{
		private int <>1__state;

		private object <>2__current;

		public APITester <>4__this;

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

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

		[DebuggerHidden]
		public <TestSpeechToText>d__14(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: Expected O, but got Unknown
			//IL_0121: Unknown result type (might be due to invalid IL or missing references)
			//IL_012b: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Expected O, but got Unknown
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			int num = <>1__state;
			APITester aPITester = <>4__this;
			switch (num)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				goto IL_0057;
			case 1:
				<>1__state = -1;
				goto IL_0057;
			case 2:
				<>1__state = -1;
				Debug.Log((object)"[Test: Speech To Text 1] Stop Speech Transcription after 10s...");
				AIManager.Instance.StopSpeechTranscription();
				Debug.Log((object)"[Test: Speech To Text 2] Wait 2s then Start Speech Transcription for 10s after previous stop...");
				<>2__current = (object)new WaitForSeconds(2f);
				<>1__state = 3;
				return true;
			case 3:
				<>1__state = -1;
				AIManager.Instance.StartSpeechTranscription();
				<>2__current = (object)new WaitForSeconds(10f);
				<>1__state = 4;
				return true;
			case 4:
				<>1__state = -1;
				Debug.Log((object)"[Test: Speech To Text 2] Stop Speech Transcription again after 10s...");
				AIManager.Instance.StopSpeechTranscription();
				Debug.Log((object)"VoiceBox: Finished Testing Speech To Text");
				aPITester.testIsRunning = false;
				<>2__current = null;
				<>1__state = 5;
				return true;
			case 5:
				{
					<>1__state = -1;
					return false;
				}
				IL_0057:
				if (aPITester.testIsRunning)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 1;
					return true;
				}
				aPITester.testIsRunning = true;
				Debug.Log((object)"VoiceBox: Testing Speech To Text");
				Debug.Log((object)"[Test: Speech To Text 1] Start Speech Transcription for 10s...");
				AIManager.Instance.SpeechToTextService.OnRecognized += aPITester.LogRecognizedSpeech;
				AIManager.Instance.StartSpeechTranscription(aPITester.internalCancellationTokenSource.Token);
				<>2__current = (object)new WaitForSeconds(10f);
				<>1__state = 2;
				return true;
			}
		}

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

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	[CompilerGenerated]
	private sealed class <TestTextToSpeech>d__15 : IEnumerator<object>, IEnumerator, IDisposable
	{
		private int <>1__state;

		private object <>2__current;

		public APITester <>4__this;

		private <>c__DisplayClass15_0 <>8__1;

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

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

		[DebuggerHidden]
		public <TestTextToSpeech>d__15(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
			<>8__1 = null;
			<>1__state = -2;
		}

		private bool MoveNext()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_00fc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Expected O, but got Unknown
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Expected O, but got Unknown
			//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bf: Expected O, but got Unknown
			int num = <>1__state;
			APITester aPITester = <>4__this;
			switch (num)
			{
			default:
				return false;
			case 0:
				<>1__state = -1;
				<>8__1 = new <>c__DisplayClass15_0();
				<>8__1.<>4__this = <>4__this;
				goto IL_0073;
			case 1:
				<>1__state = -1;
				goto IL_0073;
			case 2:
				<>1__state = -1;
				goto IL_0116;
			case 3:
				<>1__state = -1;
				goto IL_019c;
			case 4:
				<>1__state = -1;
				Debug.Log((object)"[Test: Text To Speech 3] Stream audio");
				AIManager.Instance.RequestAudioAndStream("This audio is streaming instead of waiting for the full response. This approach reduces first-word latency tremendously.", ((Component)aPITester.audioSource).GetComponent<AudioStreamer>());
				Debug.Log((object)"VoiceBox: Finished Testing Text To Speech");
				aPITester.testIsRunning = false;
				<>2__current = null;
				<>1__state = 5;
				return true;
			case 5:
				{
					<>1__state = -1;
					return false;
				}
				IL_0073:
				if (aPITester.testIsRunning)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 1;
					return true;
				}
				aPITester.testIsRunning = true;
				<>8__1.waitingForTTS = true;
				Debug.Log((object)"VoiceBox: Testing Text To Speech");
				Debug.Log((object)"[Test: Text To Speech 1] Generate audio file");
				AIManager.Instance.GenerateSpeechFileFromText("Hello World", "helloworld.wav", Application.dataPath, delegate(string path)
				{
					Debug.Log((object)("[Test: Text To Speech 1] Generated audio file at " + path));
					<>8__1.waitingForTTS = false;
				}, delegate(string err)
				{
					Debug.LogError((object)err);
				});
				goto IL_0116;
				IL_0116:
				if (<>8__1.waitingForTTS)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 2;
					return true;
				}
				Debug.Log((object)"[Test: Text To Speech 2] Generating audioclip");
				<>8__1.waitingForTTS = true;
				<>8__1.clipLength = 0f;
				AIManager.Instance.GenerateSpeechAudioClipFromText("Hello World 2!", delegate(AudioClip audioClip)
				{
					Debug.Log((object)"[Test: Text To Speech 2] Generated audioclip and playing...");
					<>8__1.clipLength = audioClip.length;
					<>8__1.waitingForTTS = false;
					<>8__1.<>4__this.audioSource.PlayOneShot(audioClip);
				}, delegate(string err)
				{
					Debug.LogError((object)err);
					<>8__1.waitingForTTS = false;
				});
				goto IL_019c;
				IL_019c:
				if (<>8__1.waitingForTTS)
				{
					<>2__current = (object)new WaitForSeconds(0.1f);
					<>1__state = 3;
					return true;
				}
				<>2__current = (object)new WaitForSeconds(<>8__1.clipLength);
				<>1__state = 4;
				return true;
			}
		}

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

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	[SerializeField]
	public bool testSpawnManager;

	[SerializeField]
	public bool testGUI;

	[SerializeField]
	public bool testSTT;

	[SerializeField]
	public bool testTTS;

	[SerializeField]
	public bool testChat;

	[SerializeField]
	public AudioSource audioSource;

	private CancellationTokenSource internalCancellationTokenSource = new CancellationTokenSource();

	private bool testIsRunning;

	private void LogRecognizedSpeech(object s, STTUtils.VoiceBoxSpeechRecognitionEventArgs e)
	{
		if (e.Result.Reason == STTUtils.VoiceBoxResultReason.RecognizedSpeech)
		{
			if (e.Result.Text.Length > 0)
			{
				Debug.Log((object)("API Tester: Recognized: " + e.Result.Text));
			}
		}
		else if (e.Result.Reason == STTUtils.VoiceBoxResultReason.RecognizedSpeechWithTimestamps && e.Result.Text.Length > 0)
		{
			Debug.Log((object)("API Tester: Recognized with timestamps: " + e.Result.Text));
		}
	}

	public void SampleTool1(string textToDisplay)
	{
		Debug.Log((object)("AI is displaying text! --> " + textToDisplay));
	}

	public void SampleTool2(Color color)
	{
		//IL_0005: 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)
		Color val = color;
		Debug.Log((object)("AI is displaying a color! --> " + ((object)(Color)(ref val)).ToString()));
	}

	public void SampleTool3(Vector2 dir, Quaternion rot)
	{
		//IL_0005: 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_0019: 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)
		Vector2 val = dir;
		string? text = ((object)(Vector2)(ref val)).ToString();
		Quaternion val2 = rot;
		Debug.Log((object)("AI is displaying a Vector2 and a Quaternion! --> " + text + " -- " + ((object)(Quaternion)(ref val2)).ToString()));
	}

	private void Start()
	{
		if (testSpawnManager)
		{
			((MonoBehaviour)this).StartCoroutine(TestModdingTools());
		}
		if (testGUI && (Object)(object)GUIManager.Instance != (Object)null)
		{
			GUIManager.Instance.visible = true;
			GUIManager instance = GUIManager.Instance;
			instance.onApiKeysLoaded = (EventHandler)Delegate.Combine(instance.onApiKeysLoaded, (EventHandler)delegate
			{
				Debug.Log((object)"Api keys loaded!");
			});
			GUIManager instance2 = GUIManager.Instance;
			instance2.onMicrophoneSelected = (EventHandler<string>)Delegate.Combine(instance2.onMicrophoneSelected, (EventHandler<string>)delegate(object obj, string mic)
			{
				Debug.Log((object)("Mic selected: " + mic));
			});
			GUIManager instance3 = GUIManager.Instance;
			instance3.onRecordingStopped = (EventHandler<AudioClip>)Delegate.Combine(instance3.onRecordingStopped, (EventHandler<AudioClip>)delegate
			{
				Debug.Log((object)"Clip recorded!");
			});
		}
		if (testSTT)
		{
			((MonoBehaviour)this).StartCoroutine(TestSpeechToText());
		}
		if (testTTS)
		{
			((MonoBehaviour)this).StartCoroutine(TestTextToSpeech());
		}
		if (testChat)
		{
			((MonoBehaviour)this).StartCoroutine(TestChat());
		}
	}

	[IteratorStateMachine(typeof(<TestModdingTools>d__13))]
	private IEnumerator TestModdingTools()
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <TestModdingTools>d__13(0)
		{
			<>4__this = this
		};
	}

	[IteratorStateMachine(typeof(<TestSpeechToText>d__14))]
	private IEnumerator TestSpeechToText()
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <TestSpeechToText>d__14(0)
		{
			<>4__this = this
		};
	}

	[IteratorStateMachine(typeof(<TestTextToSpeech>d__15))]
	private IEnumerator TestTextToSpeech()
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <TestTextToSpeech>d__15(0)
		{
			<>4__this = this
		};
	}

	[IteratorStateMachine(typeof(<TestChat>d__16))]
	private IEnumerator TestChat()
	{
		//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
		return new <TestChat>d__16(0)
		{
			<>4__this = this
		};
	}

	private void OnDestroy()
	{
		internalCancellationTokenSource.Cancel();
	}
}
namespace TimShaw.VoiceBox.Modding
{
	public static class ModdingTools
	{
		public static T CreateChatServiceConfig<T>() where T : GenericChatServiceConfig
		{
			return ScriptableObject.CreateInstance<T>();
		}

		public static T CreateSTTServiceConfig<T>() where T : GenericSTTServiceConfig
		{
			return ScriptableObject.CreateInstance<T>();
		}

		public static T CreateTTSServiceConfig<T>() where T : GenericTTSServiceConfig
		{
			return ScriptableObject.CreateInstance<T>();
		}

		public static GameObject CreateAIManagerObject<ChatConfigType, STTConfigType, TTSConfigType>(string keysFile = "", string chatKey = null, string sttKey = null, string ttsKey = null) where ChatConfigType : GenericChatServiceConfig where STTConfigType : GenericSTTServiceConfig where TTSConfigType : GenericTTSServiceConfig
		{
			return CreateAIManagerObject(CreateChatServiceConfig<ChatConfigType>(), CreateSTTServiceConfig<STTConfigType>(), CreateTTSServiceConfig<TTSConfigType>(), keysFile, chatKey, sttKey, ttsKey);
		}

		public static GameObject CreateAIManagerObject(GenericChatServiceConfig genericChatServiceConfig, GenericSTTServiceConfig genericSTTServiceConfig, GenericTTSServiceConfig genericTTSServiceConfig, string keysFile = "", string chatKey = null, string sttKey = null, string ttsKey = null)
		{
			//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_0076: Expected O, but got Unknown
			if ((Object)(object)AIManager.Instance == (Object)null)
			{
				GameObject val = new GameObject("_AIManager");
				AIManager aIManager = val.AddComponent<AIManager>();
				aIManager.chatServiceConfig = genericChatServiceConfig;
				aIManager.speechToTextConfig = genericSTTServiceConfig;
				aIManager.textToSpeechConfig = genericTTSServiceConfig;
				AIManager.Instance.LoadAPIKeys(keysFile, chatKey, sttKey, ttsKey);
				aIManager.ChatService = ServiceFactory.CreateChatService(aIManager.chatServiceConfig);
				aIManager.SpeechToTextService = ServiceFactory.CreateSttService(aIManager.speechToTextConfig);
				aIManager.TextToSpeechService = ServiceFactory.CreateTtsService(aIManager.textToSpeechConfig);
				return val;
			}
			Debug.LogWarning((object)"AI Manager already exists, no new object will be created.");
			return ((Component)AIManager.Instance).gameObject;
		}

		public static void InitChatManagerObject(ChatManager manager, GenericChatServiceConfig config, string apiKeysJsonPath = "", string chatKey = null)
		{
			manager.chatServiceConfig = config;
			if (apiKeysJsonPath.Length > 0)
			{
				manager.LoadAPIKey(apiKeysJsonPath);
			}
			else if (chatKey != null)
			{
				manager.LoadAPIKey(null, chatKey);
			}
			else
			{
				manager.LoadAPIKey();
			}
			manager.ChatService = ServiceFactory.CreateChatService(manager.chatServiceConfig);
		}

		public static void InitTTSManagerObject(TTSManager manager, GenericTTSServiceConfig config, string apiKeysJsonPath = "", string ttsKey = null)
		{
			manager.textToSpeechConfig = config;
			if (apiKeysJsonPath.Length > 0)
			{
				manager.LoadAPIKey(apiKeysJsonPath);
			}
			else if (ttsKey != null)
			{
				manager.LoadAPIKey(null, ttsKey);
			}
			else
			{
				manager.LoadAPIKey();
			}
			manager.TextToSpeechService = ServiceFactory.CreateTtsService(manager.textToSpeechConfig);
		}
	}
}
namespace TimShaw.VoiceBox.GUI
{
	public class GUIManager : MonoBehaviour
	{
		[Header("GUI Settings")]
		[Tooltip("The global scale for all GUI elements.")]
		public float guiScale = 1.5f;

		[Tooltip("Pixel padding from the screen edges (before scaling).")]
		public float padding = 10f;

		[Tooltip("The color for our background.")]
		public Color backgroundColor = new Color(0.2f, 0.2f, 0.2f, 0.75f);

		[Header("API Keys")]
		private string chatApiKey = "";

		private string sttApiKey = "";

		private string ttsApiKey = "";

		[Header("Microphone")]
		[Tooltip("How sensitive the audio indicator is. Increase this if the bar is too low.")]
		public float audioSensitivity = 8.5f;

		[Tooltip("The height of the audio level bar in scaled pixels.")]
		public float audioBarHeight = 20f;

		[Tooltip("The max height of the microphone selection box in scaled pixels.")]
		public float micListMaxHeight = 100f;

		private float sliderValue = 60f;

		private DateTime recordingStartTime = DateTime.Now;

		private static string[] micDevices;

		private static int selectedMicIndex;

		private static bool isRecording;

		private static AudioClip recordingClip;

		private float currentAudioLevel;

		private float[] audioSampleData;

		private int sampleWindow = 256;

		public bool enableKeyboardShortcut = true;

		public bool visible;

		private Vector2 windowScrollPosition;

		private Vector2 micScrollPosition;

		private GUIStyle indicatorBoxStyle;

		private GUIStyle titleStyle;

		private GUIStyle subtitleStyle;

		private GenericChatServiceConfig chatServiceConfig;

		private GenericSTTServiceConfig sttServiceConfig;

		private GenericTTSServiceConfig ttsServiceConfig;

		private ChatManager[] chatManagers;

		private TTSManager[] tTSManagers;

		private HashSet<KeyCode> currentlyPressedKeys = new HashSet<KeyCode>();

		public EventHandler<AudioClip> onRecordingStopped;

		public EventHandler onApiKeysLoaded;

		public EventHandler<string> onMicrophoneSelected;

		public static GUIManager Instance { get; private set; }

		public static GameObject CreateGUIManagerObject()
		{
			//IL_001d: 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_002a: Expected O, but got Unknown
			if ((Object)(object)Instance != (Object)null)
			{
				return ((Component)Instance).gameObject;
			}
			GameObject val = new GameObject("_VoiceBoxGUIManager");
			val.AddComponent<GUIManager>();
			return val;
		}

		private void Awake()
		{
			if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
			}
			else
			{
				Instance = this;
			}
		}

		private void OnDestroy()
		{
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void Start()
		{
			micDevices = Microphone.devices;
			audioSampleData = new float[sampleWindow];
			if (micDevices.Length == 0)
			{
				Debug.LogWarning((object)"No microphone devices found!");
				micDevices = new string[1] { "No microphones available" };
			}
			Debug.Log((object)"[GUIManager] GUI Manager created!");
		}

		private void Update()
		{
			if (isRecording && (Object)(object)recordingClip != (Object)null)
			{
				currentAudioLevel = GetAudioLevel();
			}
			else
			{
				currentAudioLevel = 0f;
			}
		}

		private void OnGUI()
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: 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_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Expected O, but got Unknown
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: Expected O, but got Unknown
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Invalid comparison between Unknown and I4
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ca: Expected O, but got Unknown
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_0263: Unknown result type (might be due to invalid IL or missing references)
			//IL_0268: Unknown result type (might be due to invalid IL or missing references)
			//IL_069c: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_06ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_09af: Unknown result type (might be due to invalid IL or missing references)
			//IL_08b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_08b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_08ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_08bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_08e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0913: Unknown result type (might be due to invalid IL or missing references)
			//IL_0918: Unknown result type (might be due to invalid IL or missing references)
			//IL_091d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0924: Unknown result type (might be due to invalid IL or missing references)
			if (enableKeyboardShortcut)
			{
				if (Event.current.isKey && (int)Event.current.keyCode != 0)
				{
					if ((int)Event.current.type == 4)
					{
						currentlyPressedKeys.Add(Event.current.keyCode);
					}
					else if ((int)Event.current.type == 5)
					{
						currentlyPressedKeys.Remove(Event.current.keyCode);
					}
				}
				if (Event.current.shift && currentlyPressedKeys.Contains((KeyCode)118) && currentlyPressedKeys.Contains((KeyCode)98))
				{
					visible = true;
				}
			}
			if (!visible)
			{
				return;
			}
			Matrix4x4 matrix = GUI.matrix;
			GUI.matrix = Matrix4x4.Scale(new Vector3(guiScale, guiScale, 1f));
			float num = padding / guiScale;
			float num2 = (float)Screen.width / guiScale;
			float num3 = (float)Screen.height / guiScale;
			Rect val = new Rect(num, num, num2 - num * 2f, num3 - num * 2f);
			Color val2 = GUI.backgroundColor;
			GUI.backgroundColor = backgroundColor;
			GUI.Box(val, GUIContent.none);
			GUI.backgroundColor = val2;
			if (indicatorBoxStyle == null)
			{
				indicatorBoxStyle = new GUIStyle(GUI.skin.box);
				indicatorBoxStyle.alignment = (TextAnchor)3;
			}
			if (titleStyle == null)
			{
				titleStyle = new GUIStyle(GUI.skin.label);
				titleStyle.fontStyle = (FontStyle)1;
				int num4 = GUI.skin.label.fontSize;
				if (num4 <= 0)
				{
					num4 = 12;
				}
				titleStyle.fontSize = num4 * 2;
			}
			if (subtitleStyle == null)
			{
				subtitleStyle = new GUIStyle(GUI.skin.label);
				subtitleStyle.fontStyle = (FontStyle)1;
				int num5 = GUI.skin.label.fontSize;
				if (num5 <= 0)
				{
					num5 = 12;
				}
				subtitleStyle.fontSize = Mathf.FloorToInt((float)num5 * 1.2f);
			}
			GUILayout.BeginArea(val);
			GUILayout.BeginHorizontal(Array.Empty<GUILayoutOption>());
			GUILayout.FlexibleSpace();
			if (GUILayout.Button("Hide", (GUILayoutOption[])(object)new GUILayoutOption[2]
			{
				GUILayout.Width(60f),
				GUILayout.Height(25f)
			}))
			{
				visible = false;
			}
			GUILayout.EndHorizontal();
			windowScrollPosition = GUILayout.BeginScrollView(windowScrollPosition, false, true, Array.Empty<GUILayoutOption>());
			GUILayout.Label("VoiceBox Utilities GUI", titleStyle, Array.Empty<GUILayoutOption>());
			GUILayout.Label("", Array.Empty<GUILayoutOption>());
			GUILayout.Label("API Keys", subtitleStyle, Array.Empty<GUILayoutOption>());
			if (GUILayout.Button("Load API Keys", Array.Empty<GUILayoutOption>()))
			{
				if ((Object)(object)Object.FindFirstObjectByType<ChatManager>() != (Object)null)
				{
					chatManagers = Object.FindObjectsByType<ChatManager>((FindObjectsSortMode)0);
					chatServiceConfig = chatManagers[0].chatServiceConfig;
					chatApiKey = chatManagers[0].chatServiceConfig?.apiKey;
				}
				if ((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.ChatService != null)
				{
					chatServiceConfig = AIManager.Instance.chatServiceConfig;
					chatApiKey = AIManager.Instance.chatServiceConfig.apiKey;
				}
				if ((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.SpeechToTextService != null)
				{
					sttServiceConfig = AIManager.Instance.speechToTextConfig;
					sttApiKey = AIManager.Instance.speechToTextConfig.apiKey;
				}
				if ((Object)(object)Object.FindFirstObjectByType<TTSManager>() != (Object)null)
				{
					tTSManagers = Object.FindObjectsByType<TTSManager>((FindObjectsSortMode)0);
					ttsServiceConfig = tTSManagers[0].textToSpeechConfig;
					ttsApiKey = tTSManagers[0].textToSpeechConfig?.apiKey;
				}
				if ((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.TextToSpeechService != null)
				{
					ttsServiceConfig = AIManager.Instance.textToSpeechConfig;
					ttsApiKey = AIManager.Instance.textToSpeechConfig.apiKey;
				}
				onApiKeysLoaded?.Invoke(this, null);
			}
			if ((Object)(object)chatServiceConfig != (Object)null)
			{
				GUILayout.Label("Chat (Type: " + chatServiceConfig.serviceManagerType?.ToString() + ") (Manager Count: " + chatManagers?.Length + ") (" + (((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.ChatService != null) ? "AIManager)" : ")"), Array.Empty<GUILayoutOption>());
			}
			else
			{
				GUILayout.Label("Chat (Not Initialized)", Array.Empty<GUILayoutOption>());
			}
			chatApiKey = GUILayout.PasswordField((chatApiKey == null) ? "" : chatApiKey, '*', Array.Empty<GUILayoutOption>());
			if ((Object)(object)sttServiceConfig != (Object)null)
			{
				GUILayout.Label("Speech to Text (Type: " + sttServiceConfig.serviceManagerType?.ToString() + ") (AIManager)", Array.Empty<GUILayoutOption>());
			}
			else
			{
				GUILayout.Label("Speech to Text (Not Initialized)", Array.Empty<GUILayoutOption>());
			}
			sttApiKey = GUILayout.PasswordField((sttApiKey == null) ? "" : sttApiKey, '*', Array.Empty<GUILayoutOption>());
			if ((Object)(object)ttsServiceConfig != (Object)null)
			{
				GUILayout.Label("Text to Speech (Type: " + ttsServiceConfig.serviceManagerType?.ToString() + ") (Manager Count: " + tTSManagers?.Length + ") (" + (((Object)(object)AIManager.Instance != (Object)null && AIManager.Instance.TextToSpeechService != null) ? "AIManager)" : ")"), Array.Empty<GUILayoutOption>());
			}
			else
			{
				GUILayout.Label("Text to Speech (Not Initialized)", Array.Empty<GUILayoutOption>());
			}
			ttsApiKey = GUILayout.PasswordField((ttsApiKey == null) ? "" : ttsApiKey, '*', Array.Empty<GUILayoutOption>());
			GUILayout.Space(20f);
			GUILayout.Label("Microphone Utilities", subtitleStyle, Array.Empty<GUILayoutOption>());
			if (micDevices.Length != 0)
			{
				GUILayout.Label("Select a microphone (does not affect services):", Array.Empty<GUILayoutOption>());
				micScrollPosition = GUILayout.BeginScrollView(micScrollPosition, (GUILayoutOption[])(object)new GUILayoutOption[1] { GUILayout.Height(micListMaxHeight) });
				int num6 = selectedMicIndex;
				selectedMicIndex = GUILayout.SelectionGrid(selectedMicIndex, micDevices, 1, Array.Empty<GUILayoutOption>());
				if (num6 != selectedMicIndex)
				{
					onMicrophoneSelected?.Invoke(this, micDevices[selectedMicIndex]);
				}
				GUILayout.EndScrollView();
				GUILayout.Space(10f);
				GUILayout.Label("Record an AudioClip", subtitleStyle, Array.Empty<GUILayoutOption>());
				GUILayout.Label("Clip length: " + sliderValue + " seconds", Array.Empty<GUILayoutOption>());
				sliderValue = (int)Math.Round(GUILayout.HorizontalSlider(sliderValue, 1f, 600f, Array.Empty<GUILayoutOption>()), 0);
				if (GUILayout.Button(isRecording ? "Stop Recording" : "Start Recording", Array.Empty<GUILayoutOption>()))
				{
					if (isRecording)
					{
						AudioClip e = StopRecording();
						onRecordingStopped?.Invoke(this, e);
					}
					else
					{
						recordingStartTime = DateTime.Now;
						StartRecording();
					}
				}
				GUILayout.Space(5f);
				if (isRecording && (float)(DateTime.Now - recordingStartTime).Seconds >= sliderValue)
				{
					AudioClip e2 = StopRecording();
					onRecordingStopped?.Invoke(this, e2);
					Debug.Log((object)$"[GUIManager] Clip size maximum of {sliderValue} reached. Stopped recording.");
				}
				if (isRecording)
				{
					float num7 = Mathf.Clamp01(currentAudioLevel * audioSensitivity);
					if (num7 < 0.02f)
					{
						num7 = 0f;
					}
					GUILayout.Label("Listening... Level: " + (num7 * 100f).ToString("F0") + "%", Array.Empty<GUILayoutOption>());
					Rect rect = GUILayoutUtility.GetRect(GUIContent.none, indicatorBoxStyle, (GUILayoutOption[])(object)new GUILayoutOption[2]
					{
						GUILayout.Height(audioBarHeight),
						GUILayout.ExpandWidth(true)
					});
					Color val3 = GUI.backgroundColor;
					Color color = GUI.color;
					GUI.backgroundColor = new Color(0.1f, 0.1f, 0.1f, 0.8f);
					GUI.Box(rect, GUIContent.none, indicatorBoxStyle);
					Rect val4 = new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width * num7, ((Rect)(ref rect)).height);
					GUI.color = Color.Lerp(Color.green, Color.red, num7);
					GUI.DrawTexture(val4, (Texture)(object)Texture2D.whiteTexture);
					GUI.color = color;
					GUI.backgroundColor = val3;
					GUILayout.Label("Recording length: " + (DateTime.Now - recordingStartTime).Seconds + " seconds", Array.Empty<GUILayoutOption>());
				}
				else
				{
					GUILayout.Box("Not Recording", indicatorBoxStyle, Array.Empty<GUILayoutOption>());
				}
			}
			else
			{
				GUILayout.Label("No microphone devices found.", Array.Empty<GUILayoutOption>());
			}
			GUILayout.EndScrollView();
			GUILayout.EndArea();
			GUI.matrix = matrix;
		}

		public static void StartRecording()
		{
			if (micDevices.Length != 0)
			{
				string text = micDevices[selectedMicIndex];
				recordingClip = Microphone.Start(text, false, 60, 44100);
				isRecording = true;
				Debug.Log((object)("Started recording from: " + text));
			}
		}

		public static AudioClip StopRecording()
		{
			if (micDevices.Length == 0)
			{
				return null;
			}
			string text = micDevices[selectedMicIndex];
			Microphone.End(text);
			isRecording = false;
			AudioClip result = recordingClip;
			recordingClip = null;
			Debug.Log((object)("Stopped recording from: " + text));
			return result;
		}

		private float GetAudioLevel()
		{
			if ((Object)(object)recordingClip == (Object)null)
			{
				return 0f;
			}
			int num = Microphone.GetPosition(micDevices[selectedMicIndex]) - sampleWindow;
			if (num < 0)
			{
				num = 0;
			}
			recordingClip.GetData(audioSampleData, num);
			float num2 = 0f;
			for (int i = 0; i < sampleWindow; i++)
			{
				num2 += audioSampleData[i] * audioSampleData[i];
			}
			return Mathf.Sqrt(num2 / (float)sampleWindow);
		}

		private void OnDisable()
		{
			if (isRecording)
			{
				StopRecording();
			}
		}
	}
}
namespace TimShaw.VoiceBox.Generics
{
	public class GenericChatServiceConfig : ScriptableObject
	{
		public Type serviceManagerType;

		public string apiKey;

		public string apiKeyJSONString;

		public string modelName;

		public bool useFunctionInvokation = true;
	}
	public class GenericSTTServiceConfig : ScriptableObject
	{
		public Type serviceManagerType;

		public string apiKey;

		public string apiKeyJSONString;
	}
	public class GenericTTSServiceConfig : ScriptableObject
	{
		public Type serviceManagerType;

		public string apiKey;

		public string apiKeyJSONString;
	}
}
namespace TimShaw.VoiceBox.Data
{
	[CreateAssetMenu(fileName = "AzureSTTServiceConfig", menuName = "VoiceBox/STT/AzureSTTService Configuration")]
	public class AzureSTTServiceConfig : GenericSTTServiceConfig
	{
		public string region = "canadacentral";

		public string language = "en-CA";

		public string audioInputDeviceName = "Default";

		public string[] audioInputEndpointNames = new string[1] { "Default" };

		public bool requestWordLevelTimestamps;

		public AzureSTTServiceConfig()
		{
			serviceManagerType = typeof(AzureSTTServiceManager);
			apiKeyJSONString = "AZURE_SPEECH_API_KEY";
		}

		public void OnValidate()
		{
			audioInputEndpointNames = STTUtils.GetAudioInputEndpoints().Keys.ToArray();
		}
	}
	[CreateAssetMenu(fileName = "ChatGPTServiceConfig", menuName = "VoiceBox/Chat/ChatGPTService Configuration")]
	public class ChatGPTServiceConfig : GenericChatServiceConfig
	{
		public string serviceEndpoint = "https://api.openai.com/v1";

		public ChatGPTServiceConfig()
		{
			serviceManagerType = typeof(ChatGPTServiceManager);
			apiKeyJSONString = "OPENAI_API_KEY";
			modelName = "gpt-5-nano";
		}
	}
	[CreateAssetMenu(fileName = "ClaudeServiceConfig", menuName = "VoiceBox/Chat/ClaudeService Configuration")]
	public class ClaudeServiceConfig : GenericChatServiceConfig
	{
		public string serviceEndpoint = "https://api.anthropic.com/v1";

		public ClaudeServiceConfig()
		{
			serviceManagerType = typeof(ClaudeServiceManager);
			apiKeyJSONString = "ANTHROPIC_API_KEY";
			modelName = "claude-haiku-4-5";
		}
	}
	[Serializable]
	public enum ElevenlabsSTTCommitStrategy
	{
		Manual,
		Vad
	}
	[CreateAssetMenu(fileName = "ElevenlabsSTTServiceConfig", menuName = "VoiceBox/STT/ElevenlabsSTTService Configuration")]
	public class ElevenlabsSTTServiceConfig : GenericSTTServiceConfig
	{
		public string language_code = "eng";

		public string audioInputDeviceName = "Default";

		public string[] audioInputEndpointNames = new string[1] { "Default" };

		public bool include_timestamps = true;

		public bool include_language_detection;

		public ElevenlabsSTTCommitStrategy commit_strategy = ElevenlabsSTTCommitStrategy.Vad;

		public double vad_silence_threshold_secs = 0.65;

		public double vad_threshold = 0.4;

		public int min_speech_duration_ms = 250;

		public int min_silence_duration_ms = 550;

		public ElevenlabsSTTServiceConfig()
		{
			serviceManagerType = typeof(ElevenlabsSTTServiceManager);
			apiKeyJSONString = "ELEVENLABS_API_KEY";
		}

		public void OnValidate()
		{
			audioInputEndpointNames = STTUtils.GetAudioInputEndpoints().Keys.ToArray();
		}
	}
	[Serializable]
	public class VoiceSettings
	{
		[Tooltip("A float between 0 and 1. Higher values result in more stable speech, but may sound monotonous. Lower values are more expressive, but may be unstable.")]
		[Range(0f, 1f)]
		public float stability = 0.5f;

		[Tooltip("A float between 0 and 1. Higher values boost the similarity to the original voice, but may introduce artifacts. Lower values are more generic, but cleaner.")]
		[Range(0f, 1f)]
		public float similarity_boost = 0.75f;

		[Tooltip("A float between 0 and 1. A higher value will exaggerate the style of the voice.")]
		[Range(0f, 1f)]
		public float style;

		[Tooltip("Whether to use the speaker boost feature, which can enhance voice clarity.")]
		public bool use_speaker_boost = true;

		[Tooltip("A float between 0.7 and 1.2. A higher value will exaggerate the speed of the voice.")]
		[Range(0.7f, 1.2f)]
		public float speed = 1f;
	}
	[Serializable]
	public class PronunciationDictionaryLocator
	{
		[Tooltip("The ID of the pronunciation dictionary.")]
		public string pronunciation_dictionary_id;

		[Tooltip("The version ID of the pronunciation dictionary.")]
		public string version_id;
	}
	[CreateAssetMenu(fileName = "ElevenlabsServiceConfig", menuName = "VoiceBox/TTS/ElevenlabsService Configuration")]
	public class ElevenlabsTTSServiceConfig : GenericTTSServiceConfig
	{
		[Tooltip("The API endpoint for the text-to-speech service.")]
		public string serviceEndpoint = "https://api.elevenlabs.io/v1/text-to-speech/";

		[Tooltip("The ID of the voice you want to use.")]
		public string voiceId = "JBFqnCBsd6RMkjVDRZzb";

		[Tooltip("The ID of the model to be used. Defaults to eleven_flash_v2_5.")]
		public string modelID = "eleven_flash_v2_5";

		[Tooltip("Voice settings that override the stored settings for the given voice.")]
		public VoiceSettings voiceSettings;

		[Tooltip("Output format for the generated audio. Currently only mp3 is supported. e.g., mp3_44100_128")]
		public string output_format = "mp3_44100_128";

		public ElevenlabsTTSServiceConfig()
		{
			serviceManagerType = typeof(ElevenLabsTTSServiceManager);
			apiKeyJSONString = "ELEVENLABS_API_KEY";
		}
	}
	[CreateAssetMenu(fileName = "GeminiServiceConfig", menuName = "VoiceBox/Chat/GeminiService Configuration")]
	public class GeminiServiceConfig : GenericChatServiceConfig
	{
		public string serviceEndpoint = "https://generativelanguage.googleapis.com/v1beta/openai/";

		public GeminiServiceConfig()
		{
			serviceManagerType = typeof(GeminiServiceManager);
			apiKeyJSONString = "GEMINI_API_KEY";
			modelName = "gemini-2.5-flash";
		}
	}
	[CreateAssetMenu(fileName = "OllamaServiceConfig", menuName = "VoiceBox/Chat/OllamaService Configuration")]
	public class OllamaChatServiceConfig : GenericChatServiceConfig
	{
		public string serviceEndpoint = "http://localhost:11434/";

		public OllamaChatServiceConfig()
		{
			serviceManagerType = typeof(OllamaChatServiceManager);
			apiKeyJSONString = "OLLAMA_API_KEY";
		}
	}
	[CreateAssetMenu(fileName = "WhisperLiveSTTServiceConfig", menuName = "VoiceBox/STT/WhisperLiveSTTService Configuration")]
	public class WhisperLiveServiceConfig : GenericSTTServiceConfig
	{
		public string audioInputDeviceName = "Default";

		public string[] audioInputEndpointNames = new string[1] { "Default" };

		public WhisperLiveServiceConfig()
		{
			serviceManagerType = typeof(WhisperLiveServiceManager);
			apiKeyJSONString = "";
		}

		public void OnValidate()
		{
			audioInputEndpointNames = STTUtils.GetAudioInputEndpoints().Keys.ToArray();
		}
	}
}
namespace TimShaw.VoiceBox.Core
{
	public class AIManager : MonoBehaviour
	{
		private CancellationTokenSource internalChatCancellationTokenSource = new CancellationTokenSource();

		private CancellationTokenSource internalSttCancellationTokenSource = new CancellationTokenSource();

		private CancellationTokenSource internalTtsCancellationTokenSource = new CancellationTokenSource();

		[Tooltip("Path to an api keys json file.")]
		[SerializeField]
		public string apiKeysJsonPath = "";

		[Header("Service Configurations")]
		[Tooltip("Configuration asset for the chat service (e.g., GeminiConfig, ChatGPTConfig).")]
		[SerializeField]
		public GenericChatServiceConfig chatServiceConfig;

		[Tooltip("Configuration asset for the STT service (e.g., AzureConfig).")]
		[SerializeField]
		public GenericSTTServiceConfig speechToTextConfig;

		[Tooltip("Configuration asset for the TTS service (e.g., ElevenlabsConfig).")]
		[SerializeField]
		public GenericTTSServiceConfig textToSpeechConfig;

		private IChatService _chatService;

		private ISpeechToTextService _sttService;

		private ITextToSpeechService _ttsService;

		public static AIManager Instance { get; private set; }

		public IChatService ChatService
		{
			get
			{
				return _chatService;
			}
			set
			{
				_chatService = value;
			}
		}

		public ISpeechToTextService SpeechToTextService
		{
			get
			{
				return _sttService;
			}
			set
			{
				_sttService = value;
			}
		}

		public ITextToSpeechService TextToSpeechService
		{
			get
			{
				return _ttsService;
			}
			set
			{
				_ttsService = value;
			}
		}

		private static void CreateAIManagerObj()
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)Object.FindFirstObjectByType<AIManager>()))
			{
				Debug.LogError((object)"Error creating AI Manager: only 1 AI manager can exist in a scene at a time.");
			}
			else
			{
				new GameObject("_AIManager").AddComponent<AIManager>();
			}
		}

		public void LoadAPIKeys(string keysFile = null, string chatKey = null, string sttKey = null, string ttsKey = null)
		{
			Dictionary<string, string> keysFromFile = null;
			if (!string.IsNullOrEmpty(keysFile))
			{
				keysFromFile = LoadKeysFromFile(keysFile);
			}
			if ((Object)(object)chatServiceConfig != (Object)null)
			{
				chatServiceConfig.apiKey = GetApiKey(chatKey, chatServiceConfig.apiKeyJSONString, chatServiceConfig.apiKeyJSONString, keysFromFile);
				if (string.IsNullOrEmpty(chatServiceConfig.apiKey))
				{
					Debug.LogWarning((object)"Chat service API key not found.");
				}
			}
			if ((Object)(object)speechToTextConfig != (Object)null)
			{
				speechToTextConfig.apiKey = GetApiKey(sttKey, speechToTextConfig.apiKeyJSONString, speechToTextConfig.apiKeyJSONString, keysFromFile);
				if (string.IsNullOrEmpty(speechToTextConfig.apiKey))
				{
					Debug.LogWarning((object)"STT service API key not found.");
				}
			}
			if ((Object)(object)textToSpeechConfig != (Object)null)
			{
				textToSpeechConfig.apiKey = GetApiKey(ttsKey, textToSpeechConfig.apiKeyJSONString, textToSpeechConfig.apiKeyJSONString, keysFromFile);
				if (string.IsNullOrEmpty(textToSpeechConfig.apiKey))
				{
					Debug.LogWarning((object)"TTS service API key not found.");
				}
			}
		}

		private string GetApiKey(string directKey, string envVar, string jsonKey, Dictionary<string, string> keysFromFile)
		{
			if (!string.IsNullOrEmpty(directKey))
			{
				return directKey;
			}
			if (!string.IsNullOrEmpty(envVar))
			{
				string environmentVariable = Environment.GetEnvironmentVariable(envVar, EnvironmentVariableTarget.User);
				if (!string.IsNullOrEmpty(environmentVariable))
				{
					return environmentVariable;
				}
			}
			if (keysFromFile != null && !string.IsNullOrEmpty(jsonKey) && keysFromFile.ContainsKey(jsonKey))
			{
				return keysFromFile[jsonKey];
			}
			return null;
		}

		private Dictionary<string, string> LoadKeysFromFile(string keysFile)
		{
			try
			{
				return JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(keysFile));
			}
			catch (FileNotFoundException)
			{
				Debug.LogWarning((object)("[AI Manager] API keys json file not found at: " + keysFile));
				return null;
			}
			catch (Exception ex2)
			{
				Debug.LogError((object)("[AI Manager] Error reading API keys file: " + ex2.Message));
				return null;
			}
		}

		private void UnloadAPIKeys()
		{
			if (Object.op_Implicit((Object)(object)chatServiceConfig))
			{
				chatServiceConfig.apiKey = "";
			}
			if (Object.op_Implicit((Object)(object)speechToTextConfig))
			{
				speechToTextConfig.apiKey = "";
			}
			if (Object.op_Implicit((Object)(object)textToSpeechConfig))
			{
				textToSpeechConfig.apiKey = "";
			}
		}

		private void Awake()
		{
			if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this)
			{
				Object.Destroy((Object)(object)((Component)this).gameObject);
				return;
			}
			Instance = this;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			if (apiKeysJsonPath.Length > 0)
			{
				LoadAPIKeys(apiKeysJsonPath);
			}
			else
			{
				LoadAPIKeys();
			}
			ChatService = ServiceFactory.CreateChatService(chatServiceConfig);
			SpeechToTextService = ServiceFactory.CreateSttService(speechToTextConfig);
			TextToSpeechService = ServiceFactory.CreateTtsService(textToSpeechConfig);
		}

		private void OnDestroy()
		{
			internalChatCancellationTokenSource.Cancel();
			internalSttCancellationTokenSource.Cancel();
			internalTtsCancellationTokenSource.Cancel();
			UnloadAPIKeys();
			Instance = null;
		}

		public void SendChatMessage(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatUtils.VoiceBoxChatMessage> onSuccess, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options = null, CancellationToken token = default(CancellationToken))
		{
			if (internalChatCancellationTokenSource.IsCancellationRequested)
			{
				internalChatCancellationTokenSource = new CancellationTokenSource();
			}
			if (ChatService == null)
			{
				onError?.Invoke("Chat service is not initialized. Check AIManager configuration.");
				return;
			}
			token = CancellationTokenSource.CreateLinkedTokenSource(token, internalChatCancellationTokenSource.Token).Token;
			Task.Run(() => ChatService.SendMessage(messageHistory, onSuccess, onError, options, token));
		}

		public async void StreamChatMessage(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatResponseUpdate> onChunkReceived, Action onComplete, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options = null, CancellationToken token = default(CancellationToken))
		{
			if (internalChatCancellationTokenSource.IsCancellationRequested)
			{
				internalChatCancellationTokenSource = new CancellationTokenSource();
			}
			if (ChatService == null)
			{
				onError?.Invoke("Chat service is not initialized. Check AIManager configuration.");
				return;
			}
			token = CancellationTokenSource.CreateLinkedTokenSource(token, internalChatCancellationTokenSource.Token).Token;
			try
			{
				await Task.Run(() => ChatService.SendMessageStream(messageHistory, onChunkReceived, onComplete, onError, options, token));
			}
			catch (Exception ex)
			{
				Debug.LogException(ex);
			}
		}

		public void StartSpeechTranscription(CancellationToken token = default(CancellationToken))
		{
			if (internalSttCancellationTokenSource.IsCancellationRequested)
			{
				internalSttCancellationTokenSource = new CancellationTokenSource();
			}
			if (SpeechToTextService == null)
			{
				Debug.Log((object)"STT Service not initialized. Check AIManager configuration.");
				return;
			}
			token = CancellationTokenSource.CreateLinkedTokenSource(token, internalSttCancellationTokenSource.Token).Token;
			Debug.Log((object)"[AI Manager] Starting speech recognition.");
			Task.Run(() => SpeechToTextService.TranscribeAudioFromMic(token));
		}

		public void StopSpeechTranscription()
		{
			internalSttCancellationTokenSource.Cancel();
		}

		public void GenerateSpeechFileFromText(string prompt, string fileName, string dir, Action<string> onSuccess, Action<string> onError, CancellationToken token = default(CancellationToken))
		{
			Task.Run(() => TextToSpeechService.RequestAudioFile(prompt, fileName, dir, onSuccess, onError, token));
		}

		public async void GenerateSpeechAudioClipFromText(string prompt, Action<AudioClip> onSuccess, Action<string> onError)
		{
			try
			{
				AudioClip obj = await TextToSpeechService.RequestAudioClip(prompt);
				onSuccess?.Invoke(obj);
			}
			catch (Exception ex)
			{
				onError?.Invoke("Failed to generate speech: " + ex.Message);
			}
		}

		public void RequestAudioAndStream(string prompt, AudioStreamer audioStreamer, CancellationToken token = default(CancellationToken))
		{
			if (Object.op_Implicit((Object)(object)audioStreamer))
			{
				audioStreamer.InitStreaming(TextToSpeechService);
				if (internalTtsCancellationTokenSource.IsCancellationRequested)
				{
					internalTtsCancellationTokenSource = new CancellationTokenSource();
				}
				audioStreamer.ConnectAndStream(prompt, TextToSpeechService, isFinalSegment: true, internalTtsCancellationTokenSource.Token);
			}
			else
			{
				Debug.LogError((object)"[AI Manager] Audio Streamer is null.");
			}
		}

		public void RequestAudioAndStream(string promptChunk, bool isFinalSegment, AudioStreamer audioStreamer, CancellationToken token = default(CancellationToken))
		{
			if (Object.op_Implicit((Object)(object)audioStreamer))
			{
				audioStreamer.InitStreaming(TextToSpeechService);
				if (internalTtsCancellationTokenSource.IsCancellationRequested)
				{
					internalTtsCancellationTokenSource = new CancellationTokenSource();
				}
				audioStreamer.ConnectAndStream(promptChunk, TextToSpeechService, isFinalSegment, internalTtsCancellationTokenSource.Token);
			}
			else
			{
				Debug.LogError((object)"[AI Manager] Audio Streamer is null.");
			}
		}

		public async Task<string> CloneVoiceAndGetVoiceIDAsync(AudioFileSource filePaths, string voiceName, string description = "", bool removeBackgroundNoise = false)
		{
			return await TextToSpeechService.CloneVoiceAndGetVoiceIDAsync(filePaths.Paths, voiceName, description, removeBackgroundNoise);
		}

		public async Task<string> CloneVoiceAndGetVoiceIDAsync(AudioDataSource audioDataList, string voiceName, string description = "", bool removeBackgroundNoise = false, string mediaType = "mpeg")
		{
			return await TextToSpeechService.CloneVoiceAndGetVoiceIDAsync(audioDataList.Data, voiceName, description, removeBackgroundNoise, mediaType);
		}
	}
	public static class ChatUtils
	{
		public readonly struct VoiceBoxChatRole
		{
			public static VoiceBoxChatRole System { get; } = new VoiceBoxChatRole("system");


			public static VoiceBoxChatRole Assistant { get; } = new VoiceBoxChatRole("assistant");


			public static VoiceBoxChatRole User { get; } = new VoiceBoxChatRole("user");


			public static VoiceBoxChatRole Tool { get; } = new VoiceBoxChatRole("tool");


			public string Value { get; }

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

		public class VoiceBoxChatMessage : ChatMessage
		{
			public string Text => ConcatText(((ChatMessage)this).Contents);

			public VoiceBoxChatMessage(VoiceBoxChatRole role, string content)
			{
				//IL_000e: 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_002d: Expected O, but got Unknown
				((ChatMessage)this).Role = new ChatRole(role.Value);
				((ChatMessage)this).Contents = ((content == null) ? new List<AIContent>() : new List<AIContent> { (AIContent)new TextContent(content) });
			}

			public VoiceBoxChatMessage(ChatMessage chatMessage)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				((ChatMessage)this).Role = chatMessage.Role;
				((ChatMessage)this).Contents = chatMessage.Contents;
				((ChatMessage)this).AdditionalProperties = chatMessage.AdditionalProperties;
				((ChatMessage)this).CreatedAt = chatMessage.CreatedAt;
				((ChatMessage)this).RawRepresentation = chatMessage.RawRepresentation;
				((ChatMessage)this).MessageId = chatMessage.MessageId;
				((ChatMessage)this).AuthorName = chatMessage.AuthorName;
			}

			private static string ConcatText(IEnumerable<AIContent> contents)
			{
				if (contents is IList<AIContent> list)
				{
					int count = list.Count;
					switch (count)
					{
					case 0:
						return string.Empty;
					case 1:
					{
						AIContent obj2 = list[0];
						AIContent obj3 = ((obj2 is TextContent) ? obj2 : null);
						return ((obj3 != null) ? ((TextContent)obj3).Text : null) ?? string.Empty;
					}
					default:
					{
						StringBuilder stringBuilder = new StringBuilder();
						for (int i = 0; i < count; i++)
						{
							AIContent obj = list[i];
							TextContent val = (TextContent)(object)((obj is TextContent) ? obj : null);
							if (val != null)
							{
								stringBuilder.Append(val.Text);
							}
						}
						return stringBuilder.ToString();
					}
					}
				}
				return string.Concat(contents.OfType<TextContent>());
			}
		}

		public class VoiceBoxList<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable
		{
			public Action<T> AddCallback;

			private readonly List<T> _internalList = new List<T>();

			public T this[int index]
			{
				get
				{
					return _internalList[index];
				}
				set
				{
					_internalList[index] = value;
				}
			}

			public int Count => _internalList.Count;

			public bool IsReadOnly => false;

			public VoiceBoxList()
			{
			}

			public VoiceBoxList(Action<T> addCallback)
			{
				AddCallback = addCallback;
			}

			public void Add(T item)
			{
				_internalList.Add(item);
				AddCallback?.Invoke(item);
			}

			public void Clear()
			{
				_internalList.Clear();
			}

			public bool Contains(T item)
			{
				return _internalList.Contains(item);
			}

			public void CopyTo(T[] array, int arrayIndex)
			{
				_internalList.CopyTo(array, arrayIndex);
			}

			public IEnumerator<T> GetEnumerator()
			{
				return _internalList.GetEnumerator();
			}

			public int IndexOf(T item)
			{
				return _internalList.IndexOf(item);
			}

			public void Insert(int index, T item)
			{
				_internalList.Insert(index, item);
			}

			public bool Remove(T item)
			{
				return _internalList.Remove(item);
			}

			public void RemoveAt(int index)
			{
				_internalList.RemoveAt(index);
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		public class VoiceBoxChatCompletionOptions : ChatOptions
		{
			public VoiceBoxList<VoiceBoxChatTool> VoiceBoxTools = new VoiceBoxList<VoiceBoxChatTool>();

			public VoiceBoxChatCompletionOptions()
			{
				if (((ChatOptions)this).Tools == null)
				{
					((ChatOptions)this).Tools = new List<AITool>();
				}
				VoiceBoxTools.AddCallback = delegate(VoiceBoxChatTool tool)
				{
					((ChatOptions)this).Tools.Add((AITool)(object)tool.InternalChatTool);
				};
			}
		}

		public class VoiceBoxChatTool
		{
			public AIFunction InternalChatTool;

			public object Caller;

			public MethodInfo Method;

			public VoiceBoxChatTool(object caller, string functionName, string functionDescription, IList<JsonConverter> customConverters = null)
			{
				//IL_0065: Unknown result type (might be due to invalid IL or missing references)
				//IL_006f: Expected O, but got Unknown
				Caller = caller;
				Method = caller.GetType().GetMethod(functionName);
				JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions
				{
					Converters = 
					{
						(JsonConverter)new Vector2JsonConverter(),
						(JsonConverter)new Vector3JsonConverter(),
						(JsonConverter)new Vector4JsonConverter(),
						(JsonConverter)new QuaternionJsonConverter()
					},
					TypeInfoResolver = (IJsonTypeInfoResolver)new DefaultJsonTypeInfoResolver()
				};
				if (customConverters != null)
				{
					foreach (JsonConverter customConverter in customConverters)
					{
						jsonSerializerOptions.Converters.Add(customConverter);
					}
				}
				InternalChatTool = AIFunctionFactory.Create(Method, Caller, functionName, functionDescription, jsonSerializerOptions);
			}

			private BinaryData GetBinaryDataFromParameters(ParameterInfo[] parameters)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Expected O, but got Unknown
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Expected O, but got Unknown
				//IL_0056: Unknown result type (might be due to invalid IL or missing references)
				//IL_005b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0070: Unknown result type (might be due to invalid IL or missing references)
				//IL_007c: Unknown result type (might be due to invalid IL or missing references)
				//IL_008d: Expected O, but got Unknown
				JObject val = new JObject();
				JArray val2 = new JArray();
				foreach (ParameterInfo parameterInfo in parameters)
				{
					val.Add(parameterInfo.Name, (JToken)(object)GetJsonSchemaForType(parameterInfo.ParameterType));
					if (!parameterInfo.IsOptional)
					{
						val2.Add(JToken.op_Implicit(parameterInfo.Name));
					}
				}
				return BinaryData.FromString(((object)new JObject
				{
					["type"] = JToken.op_Implicit("object"),
					["properties"] = (JToken)(object)val,
					["required"] = (JToken)(object)val2
				}).ToString());
			}

			private JObject GetJsonSchemaForType(Type type)
			{
				//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_002d: Expected O, but got Unknown
				//IL_0063: Unknown result type (might be due to invalid IL or missing references)
				//IL_0068: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Expected O, but got Unknown
				//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_00cf: Expected O, but got Unknown
				//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
				//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fc: Expected O, but got Unknown
				//IL_010e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0113: Unknown result type (might be due to invalid IL or missing references)
				//IL_0128: Unknown result type (might be due to invalid IL or missing references)
				//IL_013e: Expected O, but got Unknown
				//IL_0241: Unknown result type (might be due to invalid IL or missing references)
				//IL_0246: Unknown result type (might be due to invalid IL or missing references)
				//IL_025c: Expected O, but got Unknown
				//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bb: Expected O, but got Unknown
				//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c1: Expected O, but got Unknown
				//IL_017d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0182: Unknown result type (might be due to invalid IL or missing references)
				//IL_0197: Unknown result type (might be due to invalid IL or missing references)
				//IL_01aa: Expected O, but got Unknown
				//IL_020e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0213: Unknown result type (might be due to invalid IL or missing references)
				//IL_0228: Unknown result type (might be due to invalid IL or missing references)
				//IL_0234: Unknown result type (might be due to invalid IL or missing references)
				//IL_0241: Expected O, but got Unknown
				if (!(type == typeof(string)))
				{
					if (!(type == typeof(int)) && !(type == typeof(long)) && !(type == typeof(short)))
					{
						if (!(type == typeof(double)) && !(type == typeof(float)) && !(type == typeof(decimal)))
						{
							if (!(type == typeof(bool)))
							{
								if (!(type == typeof(Guid)))
								{
									if (type.IsGenericType && (type.GetGenericTypeDefinition() == typeof(List<>) || type.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
									{
										Type type2 = type.GetGenericArguments()[0];
										return new JObject
										{
											["type"] = JToken.op_Implicit("array"),
											["items"] = (JToken)(object)GetJsonSchemaForType(type2)
										};
									}
									if (type.IsClass)
									{
										JObject val = new JObject();
										JArray val2 = new JArray();
										PropertyInfo[] properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
										foreach (PropertyInfo propertyInfo in properties)
										{
											val.Add(propertyInfo.Name, (JToken)(object)GetJsonSchemaForType(propertyInfo.PropertyType));
											val2.Add(JToken.op_Implicit(propertyInfo.Name));
										}
										return new JObject
										{
											["type"] = JToken.op_Implicit("object"),
											["properties"] = (JToken)(object)val,
											["required"] = (JToken)(object)val2
										};
									}
									return new JObject { ["type"] = JToken.op_Implicit("string") };
								}
								return new JObject
								{
									["type"] = JToken.op_Implicit("string"),
									["format"] = JToken.op_Implicit("uuid")
								};
							}
							return new JObject { ["type"] = JToken.op_Implicit("boolean") };
						}
						return new JObject { ["type"] = JToken.op_Implicit("number") };
					}
					return new JObject { ["type"] = JToken.op_Implicit("integer") };
				}
				return new JObject { ["type"] = JToken.op_Implicit("string") };
			}
		}

		public class Vector2JsonConverter : JsonConverter<Vector2>
		{
			public override bool CanConvert(Type typeToConvert)
			{
				return typeToConvert == typeof(Vector2);
			}

			public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				//IL_0057: Unknown result type (might be due to invalid IL or missing references)
				//IL_0081: Unknown result type (might be due to invalid IL or missing references)
				if (reader.TokenType == JsonTokenType.String)
				{
					string[] array = reader.GetString().Trim('(', ')', ' ').Split(',');
					if (array.Length == 2 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2))
					{
						return new Vector2(result, result2);
					}
				}
				else if (reader.TokenType == JsonTokenType.StartObject)
				{
					float num = 0f;
					float num2 = 0f;
					while (reader.Read())
					{
						if (reader.TokenType == JsonTokenType.EndObject)
						{
							return new Vector2(num, num2);
						}
						if (reader.TokenType != JsonTokenType.PropertyName)
						{
							continue;
						}
						string? @string = reader.GetString();
						reader.Read();
						string text = @string.ToLower();
						if (!(text == "x"))
						{
							if (text == "y")
							{
								num2 = reader.GetSingle();
							}
						}
						else
						{
							num = reader.GetSingle();
						}
					}
				}
				throw new JsonException("Unexpected token or format when parsing Vector2. Value: " + reader.GetString());
			}

			public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				writer.WriteStartObject();
				writer.WriteNumber("x", value.x);
				writer.WriteNumber("y", value.y);
				writer.WriteEndObject();
			}
		}

		public class Vector3JsonConverter : JsonConverter<Vector3>
		{
			public override bool CanConvert(Type typeToConvert)
			{
				return typeToConvert == typeof(Vector3);
			}

			public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				//IL_009f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Unknown result type (might be due to invalid IL or missing references)
				if (reader.TokenType == JsonTokenType.String)
				{
					string[] array = reader.GetString().Trim('(', ')', ' ').Split(',');
					if (array.Length == 3 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3))
					{
						return new Vector3(result, result2, result3);
					}
				}
				else if (reader.TokenType == JsonTokenType.StartObject)
				{
					float num = 0f;
					float num2 = 0f;
					float num3 = 0f;
					while (reader.Read())
					{
						if (reader.TokenType == JsonTokenType.EndObject)
						{
							return new Vector3(num, num2, num3);
						}
						if (reader.TokenType == JsonTokenType.PropertyName)
						{
							string? @string = reader.GetString();
							reader.Read();
							switch (@string.ToLower())
							{
							case "x":
								num = reader.GetSingle();
								break;
							case "y":
								num2 = reader.GetSingle();
								break;
							case "z":
								num3 = reader.GetSingle();
								break;
							}
						}
					}
				}
				throw new JsonException("Unexpected token or format when parsing Vector3. Value: " + reader.GetString());
			}

			public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				writer.WriteStartObject();
				writer.WriteNumber("x", value.x);
				writer.WriteNumber("y", value.y);
				writer.WriteNumber("z", value.z);
				writer.WriteEndObject();
			}
		}

		public class Vector4JsonConverter : JsonConverter<Vector4>
		{
			public override bool CanConvert(Type typeToConvert)
			{
				return typeToConvert == typeof(Vector4);
			}

			public override Vector4 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				if (reader.TokenType == JsonTokenType.String)
				{
					string[] array = reader.GetString().Trim('(', ')', ' ').Split(',');
					if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4))
					{
						return new Vector4(result, result2, result3, result4);
					}
				}
				else if (reader.TokenType == JsonTokenType.StartObject)
				{
					float num = 0f;
					float num2 = 0f;
					float num3 = 0f;
					float num4 = 0f;
					while (reader.Read())
					{
						if (reader.TokenType == JsonTokenType.EndObject)
						{
							return new Vector4(num, num2, num3, num4);
						}
						if (reader.TokenType == JsonTokenType.PropertyName)
						{
							string? @string = reader.GetString();
							reader.Read();
							switch (@string.ToLower())
							{
							case "x":
								num = reader.GetSingle();
								break;
							case "y":
								num2 = reader.GetSingle();
								break;
							case "z":
								num3 = reader.GetSingle();
								break;
							case "w":
								num4 = reader.GetSingle();
								break;
							}
						}
					}
				}
				throw new JsonException("Unexpected token or format when parsing Vector4. Value: " + reader.GetString());
			}

			public override void Write(Utf8JsonWriter writer, Vector4 value, JsonSerializerOptions options)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: 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)
				writer.WriteStartObject();
				writer.WriteNumber("x", value.x);
				writer.WriteNumber("y", value.y);
				writer.WriteNumber("z", value.z);
				writer.WriteNumber("w", value.w);
				writer.WriteEndObject();
			}
		}

		public class QuaternionJsonConverter : JsonConverter<Quaternion>
		{
			public override bool CanConvert(Type typeToConvert)
			{
				return typeToConvert == typeof(Quaternion);
			}

			public override Quaternion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				if (reader.TokenType == JsonTokenType.String)
				{
					string[] array = reader.GetString().Trim('(', ')', ' ').Split(',');
					if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4))
					{
						return new Quaternion(result, result2, result3, result4);
					}
				}
				else if (reader.TokenType == JsonTokenType.StartObject)
				{
					float num = 0f;
					float num2 = 0f;
					float num3 = 0f;
					float num4 = 0f;
					while (reader.Read())
					{
						if (reader.TokenType == JsonTokenType.EndObject)
						{
							return new Quaternion(num, num2, num3, num4);
						}
						if (reader.TokenType == JsonTokenType.PropertyName)
						{
							string? @string = reader.GetString();
							reader.Read();
							switch (@string.ToLower())
							{
							case "x":
								num = reader.GetSingle();
								break;
							case "y":
								num2 = reader.GetSingle();
								break;
							case "z":
								num3 = reader.GetSingle();
								break;
							case "w":
								num4 = reader.GetSingle();
								break;
							}
						}
					}
				}
				throw new JsonException("Unexpected token or format when parsing Quaternion. Value: " + reader.GetString());
			}

			public override void Write(Utf8JsonWriter writer, Quaternion value, JsonSerializerOptions options)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: 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)
				writer.WriteStartObject();
				writer.WriteNumber("x", value.x);
				writer.WriteNumber("y", value.y);
				writer.WriteNumber("z", value.z);
				writer.WriteNumber("w", value.w);
				writer.WriteEndObject();
			}
		}

		public class ColorJsonConverter : JsonConverter<Color>
		{
			public override bool CanConvert(Type typeToConvert)
			{
				return typeToConvert == typeof(Color);
			}

			public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				//IL_001d: 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_00d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_0093: Unknown result type (might be due to invalid IL or missing references)
				if (reader.TokenType == JsonTokenType.String)
				{
					string @string = reader.GetString();
					if (string.IsNullOrEmpty(@string))
					{
						return default(Color);
					}
					@string = @string.Trim('(', ')', ' ');
					string[] array = @string.Split(',');
					if (array.Length == 4 && float.TryParse(array[0], out var result) && float.TryParse(array[1], out var result2) && float.TryParse(array[2], out var result3) && float.TryParse(array[3], out var result4))
					{
						return new Color(result, result2, result3, result4);
					}
				}
				else if (reader.TokenType == JsonTokenType.StartObject)
				{
					float num = 0f;
					float num2 = 0f;
					float num3 = 0f;
					float num4 = 1f;
					while (reader.Read())
					{
						if (reader.TokenType == JsonTokenType.EndObject)
						{
							return new Color(num, num2, num3, num4);
						}
						if (reader.TokenType == JsonTokenType.PropertyName)
						{
							string? string2 = reader.GetString();
							reader.Read();
							switch (string2.ToLower())
							{
							case "r":
								num = reader.GetSingle();
								break;
							case "g":
								num2 = reader.GetSingle();
								break;
							case "b":
								num3 = reader.GetSingle();
								break;
							case "a":
								num4 = reader.GetSingle();
								break;
							}
						}
					}
				}
				throw new JsonException($"Unexpected token or format when parsing Color. Token: {reader.TokenType}");
			}

			public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
			{
				//IL_000c: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: 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)
				writer.WriteStartObject();
				writer.WriteNumber("r", value.r);
				writer.WriteNumber("g", value.g);
				writer.WriteNumber("b", value.b);
				writer.WriteNumber("a", value.a);
				writer.WriteEndObject();
			}
		}
	}
	public interface IChatService
	{
		void Initialize(GenericChatServiceConfig config);

		Task SendMessage(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatUtils.VoiceBoxChatMessage> onSuccess, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options, CancellationToken token);

		Task SendMessageStream(List<ChatUtils.VoiceBoxChatMessage> messageHistory, Action<ChatResponseUpdate> onChunkReceived, Action onComplete, Action<string> onError, ChatUtils.VoiceBoxChatCompletionOptions options, CancellationToken token);
	}
	public interface ISpeechToTextService
	{
		event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognizing;

		event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognized;

		event EventHandler<STTUtils.VoiceBoxSpeechRecognitionCanceledEventArgs> OnCanceled;

		event EventHandler<SessionEventArgs> OnSessionStarted;

		event EventHandler<SessionEventArgs> OnSessionStopped;

		event EventHandler<RecognitionEventArgs> OnSpeechStartDetected;

		event EventHandler<RecognitionEventArgs> OnSpeechEndDetected;

		void Initialize(GenericSTTServiceConfig config);

		Task TranscribeAudioFromMic(CancellationToken token);
	}
	public interface ITextToSpeechService
	{
		event EventHandler<byte[]> OnAudioDataReceived;

		void Initialize(GenericTTSServiceConfig config);

		Task RequestAudioFile(string prompt, string fileName, string dir, Action<string> onSuccess, Action<string> onError, CancellationToken token);

		Task<AudioClip> RequestAudioClip(string prompt);

		void InitWebsocket(ClientWebSocket webSocket, StreamingAudioDecoder audioDecoder, CancellationToken token);

		Task ConnectAndStream(string text, ClientWebSocket _webSocket, bool isFinalSegment, CancellationToken token);

		void StopStreamingAndDisconnect(ClientWebSocket websocket, CancellationToken token = default(CancellationToken));

		Task<string> CloneVoiceAndGetVoiceIDAsync(IEnumerable<byte[]> audioDataList, string voiceName, string description = "", bool removeBackgroundNoise = false, string mediaType = "mpeg");

		Task<string> CloneVoiceAndGetVoiceIDAsync(IEnumerable<string> filePaths, string voiceName, string description = "", bool removeBackgroundNoise = false);
	}
	public static class ServiceFactory
	{
		public static IChatService CreateChatService(GenericChatServiceConfig config)
		{
			try
			{
				IChatService obj = Activator.CreateInstance(config.serviceManagerType) as IChatService;
				obj.Initialize(config);
				return obj;
			}
			catch (Exception ex)
			{
				if ((Object)(object)config != (Object)null)
				{
					string modelName = config.modelName;
					if (modelName != null && modelName.Length == 0)
					{
						Debug.LogError((object)"[ServiceFactory] No model name specified for chat model.");
					}
					if (config.serviceManagerType != null && ex.GetType() == typeof(NullReferenceException))
					{
						Debug.LogError((object)("[ServiceFactory] Unknown chat config type: " + ((object)config).GetType().Name + ". Does it implement IChatService?"));
					}
				}
				else
				{
					Debug.LogWarning((object)"[ServiceFactory] Chat service config is null. No chat service will be created.");
				}
				return null;
			}
		}

		public static ISpeechToTextService CreateSttService(GenericSTTServiceConfig config)
		{
			try
			{
				ISpeechToTextService obj = Activator.CreateInstance(config.serviceManagerType) as ISpeechToTextService;
				obj.Initialize(config);
				return obj;
			}
			catch
			{
				if ((Object)(object)config != (Object)null)
				{
					if (config.serviceManagerType != null)
					{
						Debug.LogError((object)("[ServiceFactory] Unknown STT config type: " + ((object)config).GetType().Name));
					}
				}
				else
				{
					Debug.LogWarning((object)"[ServiceFactory] STT service config is null. No STT service will be created.");
				}
				return null;
			}
		}

		public static ITextToSpeechService CreateTtsService(GenericTTSServiceConfig config)
		{
			try
			{
				ITextToSpeechService obj = Activator.CreateInstance(config.serviceManagerType) as ITextToSpeechService;
				obj.Initialize(config);
				return obj;
			}
			catch
			{
				if ((Object)(object)config != (Object)null)
				{
					if (config.serviceManagerType != null)
					{
						Debug.LogError((object)("[ServiceFactory] Unknown TTS config type: " + ((object)config).GetType().Name));
					}
				}
				else
				{
					Debug.LogWarning((object)"[ServiceFactory] TTS service config is null. No TTS service will be created.");
				}
				return null;
			}
		}
	}
	public class STTUtils
	{
		public enum VoiceBoxResultReason
		{
			NoMatch,
			Canceled,
			RecognizingSpeech,
			RecognizedSpeech,
			RecognizingIntent,
			RecognizedIntent,
			TranslatingSpeech,
			TranslatedSpeech,
			SynthesizingAudio,
			SynthesizingAudioCompleted,
			RecognizingKeyword,
			RecognizedKeyword,
			SynthesizingAudioStarted,
			TranslatingParticipantSpeech,
			TranslatedParticipantSpeech,
			TranslatedInstantMessage,
			TranslatedParticipantInstantMessage,
			EnrollingVoiceProfile,
			EnrolledVoiceProfile,
			RecognizedSpeakers,
			RecognizedSpeaker,
			ResetVoiceProfile,
			DeletedVoiceProfile,
			VoicesListRetrieved,
			RecognizedSpeechWithTimestamps
		}

		public class RecognitionResult
		{
			public VoiceBoxResultReason Reason { get; set; }

			public string Text { get; set; }

			public TimeSpan Duration { get; set; }

			public long OffsetInTicks { get; set; }
		}

		public class VoiceBoxSpeechRecognitionEventArgs
		{
			public RecognitionResult Result { get; set; }

			public string Text => Result.Text;

			public VoiceBoxSpeechRecognitionEventArgs()
			{
				Result = new RecognitionResult();
			}

			public VoiceBoxSpeechRecognitionEventArgs(VoiceBoxResultReason reason, string text, TimeSpan duration, long offsetInTicks)
			{
				Result = new RecognitionResult();
				Result.Reason = reason;
				Result.Text = text;
				Result.Duration = duration;
				Result.OffsetInTicks = offsetInTicks;
			}

			public static explicit operator VoiceBoxSpeechRecognitionEventArgs(SpeechRecognitionEventArgs args)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_0031: Expected I4, but got Unknown
				return new VoiceBoxSpeechRecognitionEventArgs((VoiceBoxResultReason)((RecognitionResult)args.Result).Reason, ((RecognitionResult)args.Result).Text, ((RecognitionResult)args.Result).Duration, ((RecognitionResult)args.Result).OffsetInTicks);
			}
		}

		public class VoiceBoxSpeechRecognitionCanceledEventArgs : EventArgs
		{
			public CancellationReason Reason { get; private set; }

			public string ErrorCode { get; private set; }

			public string ErrorDetails { get; private set; }

			public VoiceBoxSpeechRecognitionCanceledEventArgs(CancellationReason reason, string errorCode, string errorDetails)
			{
				Reason = reason;
				ErrorCode = errorCode;
				ErrorDetails = errorDetails;
			}

			public static explicit operator VoiceBoxSpeechRecognitionCanceledEventArgs(SpeechRecognitionCanceledEventArgs args)
			{
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Expected I4, but got Unknown
				//IL_002f: 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)
				if (args == null)
				{
					return null;
				}
				CancellationReason reason = CancellationReason.Error;
				CancellationReason reason2 = args.Reason;
				switch (reason2 - 1)
				{
				case 0:
					reason = CancellationReason.Error;
					break;
				case 1:
					reason = CancellationReason.EndOfStream;
					break;
				case 2:
					reason = CancellationReason.User;
					break;
				}
				CancellationErrorCode errorCode = args.ErrorCode;
				string errorCode2 = ((object)(CancellationErrorCode)(ref errorCode)).ToString();
				return new VoiceBoxSpeechRecognitionCanceledEventArgs(reason, errorCode2, args.ErrorDetails);
			}
		}

		public enum CancellationReason
		{
			Error,
			EndOfStream,
			User
		}

		public static Dictionary<string, string> GetAudioInputEndpoints()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			List<MMDevice> list = ((IEnumerable<MMDevice>)new MMDeviceEnumerator().EnumerateAudioEndPoints((DataFlow)1, (DeviceState)1)).ToList();
			dictionary.Add("Default", "");
			foreach (MMDevice item in list)
			{
				dictionary.Add(item.FriendlyName, item.ID);
			}
			return dictionary;
		}

		public static int GetAudioInputDeviceNum(string deviceName, Dictionary<string, string> audioInputEndpoints)
		{
			//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)
			if (deviceName == "Default")
			{
				return 0;
			}
			int deviceCount = WaveIn.DeviceCount;
			for (int i = 0; i < deviceCount; i++)
			{
				WaveInCapabilities capabilities = WaveIn.GetCapabilities(i);
				foreach (string key in audioInputEndpoints.Keys)
				{
					if (key.StartsWith(((WaveInCapabilities)(ref capabilities)).ProductName) && key == deviceName)
					{
						return i;
					}
				}
			}
			Debug.LogWarning((object)("Device " + deviceName + " not found."));
			return -1;
		}
	}
	public readonly struct AudioFileSource
	{
		public IEnumerable<string> Paths { get; }

		public AudioFileSource(string path)
		{
			Paths = new string[1] { path };
		}

		public AudioFileSource(IEnumerable<string> paths)
		{
			Paths = paths;
		}

		public static implicit operator AudioFileSource(string path)
		{
			return new AudioFileSource(path);
		}

		public static implicit operator AudioFileSource(List<string> paths)
		{
			return new AudioFileSource(paths);
		}

		public static implicit operator AudioFileSource(string[] paths)
		{
			return new AudioFileSource(paths);
		}
	}
	public readonly struct AudioDataSource
	{
		public IEnumerable<byte[]> Data { get; }

		public AudioDataSource(byte[] singleItem)
		{
			Data = new byte[1][] { singleItem };
		}

		public AudioDataSource(IEnumerable<byte[]> collection)
		{
			Data = collection;
		}

		public static implicit operator AudioDataSource(byte[] data)
		{
			return new AudioDataSource(data);
		}

		public static implicit operator AudioDataSource(List<byte[]> data)
		{
			return new AudioDataSource(data);
		}

		public static implicit operator AudioDataSource(byte[][] data)
		{
			return new AudioDataSource(data);
		}
	}
	public class AzureSTTServiceManager : ISpeechToTextService
	{
		public SpeechRecognizer speechRecognizer;

		private Dictionary<string, string> audioEndpoints;

		private AzureSTTServiceConfig _config;

		public event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognizing;

		public event EventHandler<STTUtils.VoiceBoxSpeechRecognitionEventArgs> OnRecognized;

		public event EventHandler<STTUtils.VoiceBoxSpeechRecognitionCanceledEventArgs> OnCanceled;

		public event EventHandler<SessionEventArgs> OnSessionStarted;

		public event EventHandler<SessionEventArgs> OnSessionStopped;

		public event EventHandler<RecognitionEventArgs> OnSpeechStartDetected;

		public event EventHandler<RecognitionEventArgs> OnSpeechEndDetected;

		public async Task TranscribeAudioFromMic(CancellationToken token)
		{
			_ = 2;
			try
			{
				TaskCompletionSource<int> stopRecognition = new TaskCompletionSource<int>();
				token.Register(delegate
				{
					stopRecognition.TrySetResult(0);
				});
				await speechRecognizer.StartContinuousRecognitionAsync();
				await stopRecognition.Task;
				await speechRecognizer.StopContinuousRecognitionAsync();
				Debug.Log((object)"Azure Service Manager: Transcription stopped.");
			}
			catch (Exception ex)
			{
				Debug.Log((object)"Azure Service Manager: Speech to Text error");
				Debug.Log((object)ex.ToString());
			}
		}

		public void Initialize(GenericSTTServiceConfig config)
		{
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e0: Expected O, but got Unknown
			_config = config as AzureSTTServiceConfig;
			if (_config.apiKey.Length == 0)
			{
				Debug.Log((object)"No API key. STT disabled.");
				return;
			}
			audioEndpoints = STTUtils.GetAudioInputEndpoints();
			AudioConfig val;
			try
			{
				val = ((_config.audioInputDeviceName == "Default") ? AudioConfig.FromDefaultMicrophoneInput() : AudioConfig.FromMicrophoneInput(audioEndpoints[_config.audioInputDeviceName]));
			}
			catch (Exception ex)
			{
				Debug.LogWarning((object)("Azure Service Manager: AudioConfig error: " + ex.Message + " -- Using default microphone."));
				val = AudioConfig.FromDefaultMicrophoneInput();
			}
			SpeechConfig val2 = SpeechConfig.FromSubscription(_config.apiKey, _config.region);
			val2.SpeechRecognitionLanguage = _config.language;
			if (_config.requestWordLevelTimestamps)
			{
				val2.RequestWordLevelTimestamps();
			}
			speechRecognizer = new SpeechRecognizer(val2, val);
			InitSpeechRecognizer();
		}

		private void InitSpeechRecognizer()
		{
			speechRecognizer.Recognizing += delegate(object s, SpeechRecognitionEventArgs e)
			{
				Debug.Log((object)("Azure Service Manager: Recognizing: " + ((RecognitionResult)e.Result).Text));
				this.OnRecognizing?.Invoke(this, (STTUtils.VoiceBoxSpeechRecognitionEventArgs)e);
			};
			speechRecognizer.Recognized += delegate(object s, SpeechRecognitionEventArgs e)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Invalid comparison between Unknown and I4
				//IL_0030: Unknown result type (might be due to invalid IL or missing references)
				if ((int)((RecognitionResult)e.Result).Reason == 3)
				{
					Debug.Log((object)("Azure Service Manager: Recognized: " + ((RecognitionResult)e.Result).Text));
				}
				else if ((int)((RecognitionResult)e.Result).Reason == 0)
				{
					Debug.Log((object)"Azure Service Manager: No match.");
				}
				STTUtils.VoiceBoxSpeechRecognitionEventArgs voiceBoxSpeechRecognitionEventArgs = (STTUtils.VoiceBoxSpeechRecognitionEventArgs)e;
				if (_config.requestWordLevelTimestamps && voiceBoxSpeechRecognitionEventArgs.Result.Reason == STTUtils.VoiceBoxResultReason.RecognizedSpeech)
				{
					voiceBoxSpeechRecognitionEventArgs.Result.Reason = STTUtils.VoiceBoxResultReason.RecognizedSpeechWithTimestamps;
				}
				this.OnRecognized?.Invoke(this, voiceBoxSpeechRecognitionEventArgs);
			};
			speechRecognizer.Canceled += delegate(object s, SpeechRecognitionCanceledEventArgs e)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				Debug.Log((object)$"Azure Service Manager: CANCELED: Reason={e.Reason} Details={e.ErrorDetails}");
				this.OnCanceled?.Invoke(this, (STTUtils.VoiceBoxSpeechRecognitionCanceledEventArgs)e);
			};
			((Recognizer)speechRecognizer).SessionStarted += delegate(object s, SessionEventArgs e)
			{
				Debug.Log((object)"Azure Service Manager: Session Started.");
				this.OnSessionStarted?.Invoke(this, e);
			};
			((Recognizer)speechRecognizer).SessionStopped += delegate(object s, SessionEventArgs e)
			{
				Debug.Log((object)"Azure Service Manager: Session Stopped.");
				this.OnSessionStopped?.Invoke(this, e);
			};
			((Recognizer)speechRecognizer).SpeechStartDetected += delegate(object s, RecognitionEventArgs e)
			{
				this.OnSpeechStartDetected?.Invoke(this, e);
			};
			((Recognizer)speechRecognizer).SpeechEndDetected += delegate(object s, RecognitionEventArgs e)
			{
				this.OnSpeechEndDetected?.Invoke(this, e);
			};
		}
	}
	internal class ChatGPTServiceManager : IChatService
	{
		private IChatClient _client;

		private ChatGPTServiceConfig _config;

		public void Initialize(GenericChatServiceConfig config)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid 

BepInEx/core/Accessibility.dll

Decompiled 2 weeks ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;

[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Accessibility.dll")]
[assembly: AssemblyDescription("Accessibility.dll")]
[assembly: AssemblyDefaultAlias("Accessibility.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: CLSCompliant(true)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(true)]
[assembly: Guid("1ea4dbf0-3c3b-11cf-810c-00aa00389b71")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyDelaySign(true)]
[assembly: ImportedFromTypeLib("Accessibility")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: TypeLibVersion(1, 1)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: AssemblyVersion("4.0.0.0")]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal interface IAccessibleHandler
{
}
namespace Accessibility;

public interface IAccessible
{
	int accChildCount { get; }

	object accFocus { get; }

	object accParent { get; }

	object accSelection { get; }

	void accDoDefaultAction(object childID);

	object accHitTest(int xLeft, int yTop);

	void accLocation(out int pxLeft, out int pyTop, out int pcxWidth, out int pcyHeight, object childID);

	object accNavigate(int navDir, object childID);

	void accSelect(int flagsSelect, object childID);

	object get_accChild(object childID);

	string get_accDefaultAction(object childID);

	string get_accDescription(object childID);

	string get_accHelp(object childID);

	int get_accHelpTopic(out string pszHelpFile, object childID);

	string get_accKeyboardShortcut(object childID);

	string get_accName(object childID);

	object get_accRole(object childID);

	object get_accState(object childID);

	string get_accValue(object childID);

	void set_accName(object childID, string newName);

	void set_accValue(object childID, string newValue);
}

BepInEx/core/Azure.Core.dll

Decompiled 2 weeks ago
#define TRACE
using System;
using System.Buffers;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Core.Buffers;
using Azure.Core.Diagnostics;
using Azure.Core.Json;
using Azure.Core.JsonPatch;
using Azure.Core.Pipeline;
using Azure.Core.Serialization;
using Azure.Core.Shared;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Azure.Core.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")]
[assembly: InternalsVisibleTo("Azure.Core.Perf, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("This is the implementation of the Azure Client Pipeline")]
[assembly: AssemblyFileVersion("1.5000.25.55604")]
[assembly: AssemblyInformationalVersion("1.50.0+724366b17b92e657d2136d470077c769e89818c7")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyTitle("Microsoft Azure Client Pipeline")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Azure/azure-sdk-for-net")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ModelReaderWriterContextType(typeof(AzureCoreContext))]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.50.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]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	internal sealed class ExperimentalAttribute : Attribute
	{
		public string DiagnosticId { get; }

		public string? UrlFormat { get; set; }

		public ExperimentalAttribute(string diagnosticId)
		{
			DiagnosticId = diagnosticId;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class DynamicDependencyAttribute : Attribute
	{
		public string? MemberSignature { get; }

		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public Type? Type { get; }

		public string? TypeName { get; }

		public string? AssemblyName { get; }

		public string? Condition { get; set; }

		public DynamicDependencyAttribute(string memberSignature)
		{
			MemberSignature = memberSignature;
		}

		public DynamicDependencyAttribute(string memberSignature, Type type)
		{
			MemberSignature = memberSignature;
			Type = type;
		}

		public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName)
		{
			MemberSignature = memberSignature;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type)
		{
			MemberTypes = memberTypes;
			Type = type;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName)
		{
			MemberTypes = memberTypes;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000,
		All = -1
	}
}
namespace Azure
{
	public abstract class AsyncPageable<T> : IAsyncEnumerable<T> where T : notnull
	{
		private class StaticPageable : AsyncPageable<T>
		{
			private readonly IEnumerable<Page<T>> _pages;

			public StaticPageable(IEnumerable<Page<T>> pages)
			{
				_pages = pages;
			}

			public override async IAsyncEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null)
			{
				bool shouldReturnPages = continuationToken == null;
				foreach (Page<T> page in _pages)
				{
					if (shouldReturnPages)
					{
						yield return page;
					}
					else if (continuationToken == page.ContinuationToken)
					{
						shouldReturnPages = true;
					}
				}
			}
		}

		protected virtual CancellationToken CancellationToken { get; }

		protected AsyncPageable()
		{
			CancellationToken = CancellationToken.None;
		}

		protected AsyncPageable(CancellationToken cancellationToken)
		{
			CancellationToken = cancellationToken;
		}

		public abstract IAsyncEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null);

		public virtual async IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
		{
			await foreach (Page<T> item in AsPages().ConfigureAwait(continueOnCapturedContext: false).WithCancellation(cancellationToken))
			{
				foreach (T value in item.Values)
				{
					yield return value;
				}
			}
		}

		public static AsyncPageable<T> FromPages(IEnumerable<Page<T>> pages)
		{
			return new StaticPageable(pages);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override string? ToString()
		{
			return base.ToString();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object? obj)
		{
			return base.Equals(obj);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}
	}
	public class AzureKeyCredential : ApiKeyCredential
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public string Key
		{
			get
			{
				string result = default(string);
				((ApiKeyCredential)this).Deconstruct(ref result);
				return result;
			}
			private set
			{
				((ApiKeyCredential)this).Update(value);
			}
		}

		public AzureKeyCredential(string key)
			: base(key)
		{
		}
	}
	public class AzureNamedKeyCredential
	{
		private Tuple<string, string> _namedKey;

		public string Name => Volatile.Read(ref _namedKey).Item1;

		public AzureNamedKeyCredential(string name, string key)
		{
			Update(name, key);
		}

		public void Update(string name, string key)
		{
			Argument.AssertNotNullOrEmpty(name, "name");
			Argument.AssertNotNullOrEmpty(key, "key");
			Volatile.Write(ref _namedKey, Tuple.Create(name, key));
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public void Deconstruct(out string name, out string key)
		{
			Tuple<string, string> tuple = Volatile.Read(ref _namedKey);
			name = tuple.Item1;
			key = tuple.Item2;
		}
	}
	public class AzureSasCredential
	{
		private string _signature;

		[EditorBrowsable(EditorBrowsableState.Never)]
		public string Signature
		{
			get
			{
				return Volatile.Read(ref _signature);
			}
			private set
			{
				Volatile.Write(ref _signature, value);
			}
		}

		public AzureSasCredential(string signature)
		{
			Argument.AssertNotNullOrWhiteSpace(signature, "signature");
			Signature = signature;
		}

		public void Update(string signature)
		{
			Argument.AssertNotNullOrWhiteSpace(signature, "signature");
			Signature = signature;
		}
	}
	[Flags]
	public enum ErrorOptions
	{
		Default = 0,
		NoThrow = 1
	}
	[JsonConverter(typeof(ETagConverter))]
	public readonly struct ETag : IEquatable<ETag>
	{
		private const char QuoteCharacter = '"';

		private const string QuoteString = "\"";

		private const string WeakETagPrefix = "W/\"";

		private const string DefaultFormat = "G";

		private const string HeaderFormat = "H";

		private readonly string? _value;

		public static readonly ETag All = new ETag("*");

		public ETag(string etag)
		{
			_value = etag;
		}

		public static bool operator ==(ETag left, ETag right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ETag left, ETag right)
		{
			return !left.Equals(right);
		}

		public bool Equals(ETag other)
		{
			return string.Equals(_value, other._value, StringComparison.Ordinal);
		}

		public bool Equals(string? other)
		{
			return string.Equals(_value, other, StringComparison.Ordinal);
		}

		public override bool Equals(object? obj)
		{
			if (obj is ETag other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return _value.GetHashCodeOrdinal();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override string ToString()
		{
			return ToString("G");
		}

		public string ToString(string format)
		{
			if (_value == null)
			{
				return string.Empty;
			}
			if (!(format == "H"))
			{
				if (format == "G")
				{
					return _value;
				}
				throw new ArgumentException("Invalid format string.");
			}
			return (!IsValidQuotedFormat(_value)) ? ("\"" + _value + "\"") : _value;
		}

		internal static ETag Parse(string value)
		{
			if (value == All._value)
			{
				return All;
			}
			if (!IsValidQuotedFormat(value))
			{
				throw new ArgumentException("The value should be equal to * , be wrapped in quotes, or be wrapped in quotes prefixed by W/", "value");
			}
			if (value.StartsWith("W/\"", StringComparison.Ordinal))
			{
				return new ETag(value);
			}
			return new ETag(value.Trim(new char[1] { '"' }));
		}

		private static bool IsValidQuotedFormat(string value)
		{
			if ((!value.StartsWith("\"", StringComparison.Ordinal) && !value.StartsWith("W/\"", StringComparison.Ordinal)) || !value.EndsWith("\"", StringComparison.Ordinal))
			{
				return value == All._value;
			}
			return true;
		}
	}
	internal class ETagConverter : JsonConverter<ETag>
	{
		public override ETag Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			string @string = reader.GetString();
			if (@string == null)
			{
				return default(ETag);
			}
			return new ETag(@string);
		}

		public override void Write(Utf8JsonWriter writer, ETag value, JsonSerializerOptions options)
		{
			if (value == default(ETag))
			{
				writer.WriteNullValue();
			}
			else
			{
				writer.WriteStringValue(value.ToString("H"));
			}
		}
	}
	public class HttpAuthorization
	{
		public string Scheme { get; }

		public string Parameter { get; }

		public HttpAuthorization(string scheme, string parameter)
		{
			Argument.AssertNotNullOrWhiteSpace(scheme, "scheme");
			Argument.AssertNotNullOrWhiteSpace(parameter, "parameter");
			Scheme = scheme;
			Parameter = parameter;
		}

		public override string ToString()
		{
			return Scheme + " " + Parameter;
		}
	}
	public readonly struct HttpRange : IEquatable<HttpRange>
	{
		private const string Unit = "bytes";

		public long Offset { get; }

		public long? Length { get; }

		public HttpRange(long offset = 0L, long? length = null)
		{
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset");
			}
			if (length.HasValue && length <= 0)
			{
				throw new ArgumentOutOfRangeException("length");
			}
			Offset = offset;
			Length = length;
		}

		public override string ToString()
		{
			if (Length.HasValue && Length != 0)
			{
				long num = Offset + Length.Value - 1;
				return FormattableString.Invariant(FormattableStringFactory.Create("{0}={1}-{2}", "bytes", Offset, num));
			}
			return FormattableString.Invariant(FormattableStringFactory.Create("{0}={1}-", "bytes", Offset));
		}

		public static bool operator ==(HttpRange left, HttpRange right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(HttpRange left, HttpRange right)
		{
			return !(left == right);
		}

		public bool Equals(HttpRange other)
		{
			if (Offset == other.Offset)
			{
				return Length == other.Length;
			}
			return false;
		}

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

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return HashCodeBuilder.Combine(Offset, Length);
		}
	}
	internal class ResponseDebugView<T>
	{
		private readonly Response<T> _response;

		public Response GetRawResponse => _response.GetRawResponse();

		public T Value => _response.Value;

		public ResponseDebugView(Response<T> response)
		{
			_response = response;
		}
	}
	internal class ValueResponse<T> : Response<T>
	{
		private readonly Response _response;

		public override T Value { get; }

		public ValueResponse(Response response, T value)
		{
			_response = response;
			Value = value;
		}

		public override Response GetRawResponse()
		{
			return _response;
		}
	}
	public class JsonPatchDocument
	{
		private readonly ReadOnlyMemory<byte> _rawDocument;

		private readonly ObjectSerializer _serializer;

		private readonly Collection<JsonPatchOperation> _operations;

		[RequiresUnreferencedCode("JsonObjectSerializer uses reflection-based JSON serialization and deserialization that is not compatible with trimming.")]
		[RequiresDynamicCode("JsonObjectSerializer uses reflection-based JSON serialization and deserialization that is not compatible with trimming.")]
		public JsonPatchDocument()
			: this(default(ReadOnlyMemory<byte>))
		{
		}

		public JsonPatchDocument(ObjectSerializer serializer)
			: this(default(ReadOnlyMemory<byte>), serializer)
		{
		}

		[RequiresUnreferencedCode("JsonObjectSerializer uses reflection-based JSON serialization and deserialization that is not compatible with trimming.")]
		[RequiresDynamicCode("JsonObjectSerializer uses reflection-based JSON serialization and deserialization that is not compatible with trimming.")]
		public JsonPatchDocument(ReadOnlyMemory<byte> rawDocument)
			: this(rawDocument, new JsonObjectSerializer())
		{
		}

		public JsonPatchDocument(ReadOnlyMemory<byte> rawDocument, ObjectSerializer serializer)
		{
			_operations = new Collection<JsonPatchOperation>();
			_rawDocument = rawDocument;
			_serializer = serializer ?? throw new ArgumentNullException("serializer");
		}

		public void AppendAddRaw(string path, string rawJsonValue)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Add, path, null, rawJsonValue));
		}

		public void AppendAdd<T>(string path, T value)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Add, path, null, Serialize(value)));
		}

		public void AppendReplaceRaw(string path, string rawJsonValue)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Replace, path, null, rawJsonValue));
		}

		public void AppendReplace<T>(string path, T value)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Replace, path, null, Serialize(value)));
		}

		public void AppendCopy(string from, string path)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Copy, path, from, null));
		}

		public void AppendMove(string from, string path)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Move, path, from, null));
		}

		public void AppendRemove(string path)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Remove, path, null, null));
		}

		public void AppendTestRaw(string path, string rawJsonValue)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Test, path, null, rawJsonValue));
		}

		public void AppendTest<T>(string path, T value)
		{
			_operations.Add(new JsonPatchOperation(JsonPatchOperationKind.Test, path, null, Serialize(value)));
		}

		public ReadOnlyMemory<byte> ToBytes()
		{
			if (!_rawDocument.IsEmpty && _operations.Count == 0)
			{
				return _rawDocument;
			}
			using MemoryStream memoryStream = new MemoryStream();
			using (Utf8JsonWriter writer = new Utf8JsonWriter(memoryStream))
			{
				WriteTo(writer);
			}
			return memoryStream.GetBuffer().AsMemory(0, (int)memoryStream.Length);
		}

		public override string ToString()
		{
			return Encoding.UTF8.GetString(ToBytes().ToArray());
		}

		private void WriteTo(Utf8JsonWriter writer)
		{
			writer.WriteStartArray();
			if (!_rawDocument.IsEmpty)
			{
				using JsonDocument jsonDocument = JsonDocument.Parse(_rawDocument);
				foreach (JsonElement item in jsonDocument.RootElement.EnumerateArray())
				{
					item.WriteTo(writer);
				}
			}
			foreach (JsonPatchOperation operation in _operations)
			{
				writer.WriteStartObject();
				writer.WriteString("op", operation.Kind.ToString());
				if (operation.From != null)
				{
					writer.WriteString("from", operation.From);
				}
				writer.WriteString("path", operation.Path);
				if (operation.RawJsonValue != null)
				{
					using JsonDocument jsonDocument2 = JsonDocument.Parse(operation.RawJsonValue);
					writer.WritePropertyName("value");
					jsonDocument2.WriteTo(writer);
				}
				writer.WriteEndObject();
			}
			writer.WriteEndArray();
		}

		private string Serialize<T>(T value)
		{
			using MemoryStream memoryStream = new MemoryStream();
			_serializer.Serialize(memoryStream, value, typeof(T), default(CancellationToken));
			return Encoding.UTF8.GetString(memoryStream.ToArray());
		}
	}
	public class MatchConditions
	{
		public ETag? IfMatch { get; set; }

		public ETag? IfNoneMatch { get; set; }
	}
	public abstract class NullableResponse<T>
	{
		private const string NoValue = "<null>";

		public abstract bool HasValue { get; }

		public abstract T? Value { get; }

		public abstract Response GetRawResponse();

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object? obj)
		{
			return base.Equals(obj);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public override string ToString()
		{
			return string.Format("Status: {0}, Value: {1}", GetRawResponse()?.Status, HasValue ? ((object)Value) : "<null>");
		}
	}
	public abstract class Operation
	{
		public abstract string Id { get; }

		public abstract bool HasCompleted { get; }

		[RequiresDynamicCode("This method uses reflection.")]
		[RequiresUnreferencedCode("This method uses reflection.")]
		public static Operation<T> Rehydrate<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(HttpPipeline pipeline, RehydrationToken rehydrationToken, ClientOptions? options = null) where T : IPersistableModel<T>
		{
			Argument.AssertNotNull(pipeline, "pipeline");
			Argument.AssertNotNull(rehydrationToken, "rehydrationToken");
			GenericOperationSource<T> operationSource = new GenericOperationSource<T>();
			NextLinkOperationImplementation nextLinkOperationImplementation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(pipeline, rehydrationToken);
			IOperation<T> operation = NextLinkOperationImplementation.Create(operationSource, nextLinkOperationImplementation);
			OperationState<T> operationState = operation.UpdateStateAsync(async: false, default(CancellationToken)).EnsureCompleted();
			return new RehydrationOperation<T>(nextLinkOperationImplementation, operationState, operation, options);
		}

		public static Operation Rehydrate(HttpPipeline pipeline, RehydrationToken rehydrationToken, ClientOptions? options = null)
		{
			Argument.AssertNotNull(pipeline, "pipeline");
			Argument.AssertNotNull(rehydrationToken, "rehydrationToken");
			NextLinkOperationImplementation obj = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(pipeline, rehydrationToken);
			OperationState operationState = obj.UpdateStateAsync(async: false, default(CancellationToken)).EnsureCompleted();
			return new RehydrationOperation(obj, operationState);
		}

		[RequiresDynamicCode("This method uses reflection.")]
		[RequiresUnreferencedCode("This method uses reflection.")]
		public static async Task<Operation<T>> RehydrateAsync<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] T>(HttpPipeline pipeline, RehydrationToken rehydrationToken, ClientOptions? options = null) where T : IPersistableModel<T>
		{
			Argument.AssertNotNull(pipeline, "pipeline");
			Argument.AssertNotNull(rehydrationToken, "rehydrationToken");
			IOperationSource<T> operationSource = new GenericOperationSource<T>();
			NextLinkOperationImplementation nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(pipeline, rehydrationToken);
			IOperation<T> operation = NextLinkOperationImplementation.Create(operationSource, nextLinkOperation);
			return new RehydrationOperation<T>(nextLinkOperation, await operation.UpdateStateAsync(async: true, default(CancellationToken)).ConfigureAwait(continueOnCapturedContext: false), operation, options);
		}

		public static async Task<Operation> RehydrateAsync(HttpPipeline pipeline, RehydrationToken rehydrationToken, ClientOptions? options = null)
		{
			Argument.AssertNotNull(pipeline, "pipeline");
			Argument.AssertNotNull(rehydrationToken, "rehydrationToken");
			NextLinkOperationImplementation nextLinkOperation = (NextLinkOperationImplementation)NextLinkOperationImplementation.Create(pipeline, rehydrationToken);
			return new RehydrationOperation(nextLinkOperation, await nextLinkOperation.UpdateStateAsync(async: true, default(CancellationToken)).ConfigureAwait(continueOnCapturedContext: false));
		}

		public virtual RehydrationToken? GetRehydrationToken()
		{
			return null;
		}

		public abstract Response GetRawResponse();

		public abstract ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default(CancellationToken));

		public abstract Response UpdateStatus(CancellationToken cancellationToken = default(CancellationToken));

		public virtual async ValueTask<Response> WaitForCompletionResponseAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return await new OperationPoller().WaitForCompletionResponseAsync(this, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public virtual async ValueTask<Response> WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default(CancellationToken))
		{
			return await new OperationPoller().WaitForCompletionResponseAsync(this, pollingInterval, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public virtual async ValueTask<Response> WaitForCompletionResponseAsync(DelayStrategy delayStrategy, CancellationToken cancellationToken = default(CancellationToken))
		{
			return await new OperationPoller(delayStrategy).WaitForCompletionResponseAsync(this, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public virtual Response WaitForCompletionResponse(CancellationToken cancellationToken = default(CancellationToken))
		{
			return new OperationPoller().WaitForCompletionResponse(this, null, cancellationToken);
		}

		public virtual Response WaitForCompletionResponse(TimeSpan pollingInterval, CancellationToken cancellationToken = default(CancellationToken))
		{
			return new OperationPoller().WaitForCompletionResponse(this, pollingInterval, cancellationToken);
		}

		public virtual Response WaitForCompletionResponse(DelayStrategy delayStrategy, CancellationToken cancellationToken = default(CancellationToken))
		{
			return new OperationPoller(delayStrategy).WaitForCompletionResponse(this, null, cancellationToken);
		}

		internal static T GetValue<T>(ref T? value) where T : class
		{
			if (value == null)
			{
				throw new InvalidOperationException("The operation has not completed yet.");
			}
			return value;
		}

		internal static T GetValue<T>(ref T? value) where T : struct
		{
			if (!value.HasValue)
			{
				throw new InvalidOperationException("The operation has not completed yet.");
			}
			return value.Value;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object? obj)
		{
			return base.Equals(obj);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override string? ToString()
		{
			return base.ToString();
		}
	}
	public abstract class Operation<T> : Operation where T : notnull
	{
		public abstract T Value { get; }

		public abstract bool HasValue { get; }

		public virtual Response<T> WaitForCompletion(CancellationToken cancellationToken = default(CancellationToken))
		{
			return new OperationPoller().WaitForCompletion(this, null, cancellationToken);
		}

		public virtual Response<T> WaitForCompletion(TimeSpan pollingInterval, CancellationToken cancellationToken)
		{
			return new OperationPoller().WaitForCompletion(this, pollingInterval, cancellationToken);
		}

		public virtual async ValueTask<Response<T>> WaitForCompletionAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return await new OperationPoller().WaitForCompletionAsync(this, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public virtual async ValueTask<Response<T>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken)
		{
			return await new OperationPoller().WaitForCompletionAsync(this, pollingInterval, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public virtual Response<T> WaitForCompletion(DelayStrategy delayStrategy, CancellationToken cancellationToken)
		{
			return new OperationPoller(delayStrategy).WaitForCompletion(this, null, cancellationToken);
		}

		public virtual async ValueTask<Response<T>> WaitForCompletionAsync(DelayStrategy delayStrategy, CancellationToken cancellationToken)
		{
			return await new OperationPoller(delayStrategy).WaitForCompletionAsync(this, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override async ValueTask<Response> WaitForCompletionResponseAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await WaitForCompletionAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetRawResponse();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override async ValueTask<Response> WaitForCompletionResponseAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await WaitForCompletionAsync(pollingInterval, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetRawResponse();
		}
	}
	public abstract class Page<T>
	{
		private class PageCore : Page<T>
		{
			private readonly Response _response;

			public override IReadOnlyList<T> Values { get; }

			public override string? ContinuationToken { get; }

			public PageCore(IReadOnlyList<T> values, string? continuationToken, Response response)
			{
				_response = response;
				Values = values;
				ContinuationToken = continuationToken;
			}

			public override Response GetRawResponse()
			{
				return _response;
			}
		}

		public abstract IReadOnlyList<T> Values { get; }

		public abstract string? ContinuationToken { get; }

		public abstract Response GetRawResponse();

		public static Page<T> FromValues(IReadOnlyList<T> values, string? continuationToken, Response response)
		{
			return new PageCore(values, continuationToken, response);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override string? ToString()
		{
			return base.ToString();
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object? obj)
		{
			return base.Equals(obj);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}
	}
	public abstract class Pageable<T> : IEnumerable<T>, IEnumerable where T : notnull
	{
		private class StaticPageable : Pageable<T>
		{
			[CompilerGenerated]
			private sealed class <AsPages>d__2 : IEnumerable<Page<T>>, IEnumerable, IEnumerator<Page<T>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private Page<T> <>2__current;

				private int <>l__initialThreadId;

				private string continuationToken;

				public string <>3__continuationToken;

				public Pageable<T>.StaticPageable <>4__this;

				private bool <shouldReturnPages>5__2;

				private IEnumerator<Page<T>> <>7__wrap2;

				Page<T> IEnumerator<Page<T>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

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

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					int num = <>1__state;
					if (num == -3 || num == 1)
					{
						try
						{
						}
						finally
						{
							<>m__Finally1();
						}
					}
					<>7__wrap2 = null;
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					try
					{
						int num = <>1__state;
						Pageable<T>.StaticPageable staticPageable = <>4__this;
						switch (num)
						{
						default:
							return false;
						case 0:
							<>1__state = -1;
							<shouldReturnPages>5__2 = continuationToken == null;
							<>7__wrap2 = staticPageable._pages.GetEnumerator();
							<>1__state = -3;
							break;
						case 1:
							<>1__state = -3;
							break;
						}
						while (<>7__wrap2.MoveNext())
						{
							Page<T> current = <>7__wrap2.Current;
							if (<shouldReturnPages>5__2)
							{
								<>2__current = current;
								<>1__state = 1;
								return true;
							}
							if (continuationToken == current.ContinuationToken)
							{
								<shouldReturnPages>5__2 = true;
							}
						}
						<>m__Finally1();
						<>7__wrap2 = null;
						return false;
					}
					catch
					{
						//try-fault
						((IDisposable)this).Dispose();
						throw;
					}
				}

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

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}

				[DebuggerHidden]
				IEnumerator<Page<T>> IEnumerable<Page<T>>.GetEnumerator()
				{
					<AsPages>d__2 <AsPages>d__;
					if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
					{
						<>1__state = 0;
						<AsPages>d__ = this;
					}
					else
					{
						<AsPages>d__ = new <AsPages>d__2(0)
						{
							<>4__this = <>4__this
						};
					}
					<AsPages>d__.continuationToken = <>3__continuationToken;
					return <AsPages>d__;
				}

				[DebuggerHidden]
				IEnumerator IEnumerable.GetEnumerator()
				{
					return ((IEnumerable<Page<T>>)this).GetEnumerator();
				}
			}

			private readonly IEnumerable<Page<T>> _pages;

			public StaticPageable(IEnumerable<Page<T>> pages)
			{
				_pages = pages;
			}

			[IteratorStateMachine(typeof(Pageable<>.StaticPageable.<AsPages>d__2))]
			public override IEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null)
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <AsPages>d__2(-2)
				{
					<>4__this = this,
					<>3__continuationToken = continuationToken
				};
			}
		}

		[CompilerGenerated]
		private sealed class <GetEnumerator>d__8 : IEnumerator<T>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private T <>2__current;

			public Pageable<T> <>4__this;

			private IEnumerator<Page<T>> <>7__wrap1;

			private IEnumerator<T> <>7__wrap2;

			T IEnumerator<T>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

			[DebuggerHidden]
			public <GetEnumerator>d__8(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if ((uint)(num - -4) <= 1u || num == 1)
				{
					try
					{
						if (num == -4 || num == 1)
						{
							try
							{
							}
							finally
							{
								<>m__Finally2();
							}
						}
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<>7__wrap1 = null;
				<>7__wrap2 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				try
				{
					int num = <>1__state;
					Pageable<T> pageable = <>4__this;
					if (num != 0)
					{
						if (num != 1)
						{
							return false;
						}
						<>1__state = -4;
						goto IL_0099;
					}
					<>1__state = -1;
					<>7__wrap1 = pageable.AsPages().GetEnumerator();
					<>1__state = -3;
					goto IL_00b3;
					IL_0099:
					if (<>7__wrap2.MoveNext())
					{
						T current = <>7__wrap2.Current;
						<>2__current = current;
						<>1__state = 1;
						return true;
					}
					<>m__Finally2();
					<>7__wrap2 = null;
					goto IL_00b3;
					IL_00b3:
					if (<>7__wrap1.MoveNext())
					{
						Page<T> current2 = <>7__wrap1.Current;
						<>7__wrap2 = current2.Values.GetEnumerator();
						<>1__state = -4;
						goto IL_0099;
					}
					<>m__Finally1();
					<>7__wrap1 = null;
					return false;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

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

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

			private void <>m__Finally2()
			{
				<>1__state = -3;
				if (<>7__wrap2 != null)
				{
					<>7__wrap2.Dispose();
				}
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		protected virtual CancellationToken CancellationToken { get; }

		protected Pageable()
		{
			CancellationToken = CancellationToken.None;
		}

		protected Pageable(CancellationToken cancellationToken)
		{
			CancellationToken = cancellationToken;
		}

		public abstract IEnumerable<Page<T>> AsPages(string? continuationToken = null, int? pageSizeHint = null);

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override string? ToString()
		{
			return base.ToString();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		[IteratorStateMachine(typeof(Pageable<>.<GetEnumerator>d__8))]
		public virtual IEnumerator<T> GetEnumerator()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetEnumerator>d__8(0)
			{
				<>4__this = this
			};
		}

		public static Pageable<T> FromPages(IEnumerable<Page<T>> pages)
		{
			return new StaticPageable(pages);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object? obj)
		{
			return base.Equals(obj);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}
	}
	public abstract class PageableOperation<T> : Operation<AsyncPageable<T>> where T : notnull
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override AsyncPageable<T> Value => GetValuesAsync();

		public abstract AsyncPageable<T> GetValuesAsync(CancellationToken cancellationToken = default(CancellationToken));

		public abstract Pageable<T> GetValues(CancellationToken cancellationToken = default(CancellationToken));
	}
	public class RequestConditions : MatchConditions
	{
		public DateTimeOffset? IfModifiedSince { get; set; }

		public DateTimeOffset? IfUnmodifiedSince { get; set; }
	}
	public class RequestContext
	{
		private bool _frozen;

		private (int Status, bool IsError)[]? _statusCodes;

		private ResponseClassificationHandler[]? _handlers;

		internal (int Status, bool IsError)[]? StatusCodes => _statusCodes;

		internal ResponseClassificationHandler[]? Handlers => _handlers;

		internal List<(HttpPipelinePosition Position, HttpPipelinePolicy Policy)>? Policies { get; private set; }

		public ErrorOptions ErrorOptions { get; set; }

		public CancellationToken CancellationToken { get; set; } = CancellationToken.None;


		public static implicit operator RequestContext(ErrorOptions options)
		{
			return new RequestContext
			{
				ErrorOptions = options
			};
		}

		public void AddPolicy(HttpPipelinePolicy policy, HttpPipelinePosition position)
		{
			if (Policies == null)
			{
				List<(HttpPipelinePosition, HttpPipelinePolicy)> list2 = (Policies = new List<(HttpPipelinePosition, HttpPipelinePolicy)>());
			}
			Policies.Add((position, policy));
		}

		public void AddClassifier(int statusCode, bool isError)
		{
			Argument.AssertInRange(statusCode, 100, 599, "statusCode");
			if (_frozen)
			{
				throw new InvalidOperationException("Cannot modify classifiers after this type has been used in a method call.");
			}
			int num = ((_statusCodes != null) ? _statusCodes.Length : 0);
			Array.Resize(ref _statusCodes, num + 1);
			Array.Copy(_statusCodes, 0, _statusCodes, 1, num);
			_statusCodes[0] = (statusCode, isError);
		}

		public void AddClassifier(ResponseClassificationHandler classifier)
		{
			if (_frozen)
			{
				throw new InvalidOperationException("Cannot modify classifiers after this type has been used in a method call.");
			}
			int num = ((_handlers != null) ? _handlers.Length : 0);
			Array.Resize(ref _handlers, num + 1);
			Array.Copy(_handlers, 0, _handlers, 1, num);
			_handlers[0] = classifier;
		}

		internal void Freeze()
		{
			_frozen = true;
		}

		internal ResponseClassifier Apply(ResponseClassifier classifier)
		{
			if (_statusCodes == null && _handlers == null)
			{
				return classifier;
			}
			if (classifier is StatusCodeClassifier statusCodeClassifier)
			{
				StatusCodeClassifier statusCodeClassifier2 = statusCodeClassifier.Clone();
				statusCodeClassifier2.Handlers = _handlers;
				if (_statusCodes != null)
				{
					(int, bool)[] statusCodes = _statusCodes;
					for (int i = 0; i < statusCodes.Length; i++)
					{
						(int, bool) tuple = statusCodes[i];
						statusCodeClassifier2.AddClassifier(tuple.Item1, tuple.Item2);
					}
				}
				return statusCodeClassifier2;
			}
			return new ChainingClassifier(_statusCodes, _handlers, classifier);
		}
	}
	[Serializable]
	public class RequestFailedException : Exception, ISerializable
	{
		internal class ErrorResponse
		{
			[JsonPropertyName("error")]
			public ResponseError? Error { get; set; }
		}

		private readonly struct ErrorDetails
		{
			public string Message { get; }

			public string? ErrorCode { get; }

			public IDictionary<string, string>? Data { get; }

			public ErrorDetails(string message, string? errorCode, IDictionary<string, string>? data)
			{
				Message = message;
				ErrorCode = errorCode;
				Data = data;
			}
		}

		private const string DefaultMessage = "Service request failed.";

		internal const string NoContentOnSuccessMessage = "Service request succeeded. Response content and headers are not included to avoid logging sensitive data.";

		private readonly Response? _response;

		public int Status { get; }

		public string? ErrorCode { get; }

		public RequestFailedException(string message)
			: this(0, message)
		{
		}

		public RequestFailedException(string message, Exception? innerException)
			: this(0, message, innerException)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public RequestFailedException(int status, string message)
			: this(status, message, null)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public RequestFailedException(int status, string message, Exception? innerException)
			: this(status, message, null, innerException)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public RequestFailedException(int status, string message, string? errorCode, Exception? innerException)
			: base(message, innerException)
		{
			Status = status;
			ErrorCode = errorCode;
		}

		private RequestFailedException(int status, (string Message, ResponseError? Error) details)
			: this(status, details.Message, details.Error?.Code, null)
		{
		}

		private RequestFailedException(int status, ErrorDetails details, Exception? innerException)
			: this(status, details.Message, details.ErrorCode, innerException)
		{
			if (details.Data == null)
			{
				return;
			}
			foreach (KeyValuePair<string, string> datum in details.Data)
			{
				Data.Add(datum.Key, datum.Value);
			}
		}

		public RequestFailedException(Response response)
			: this(response, null)
		{
		}

		public RequestFailedException(Response response, Exception? innerException)
			: this(response, innerException, null)
		{
		}

		public RequestFailedException(Response response, Exception? innerException, RequestFailedDetailsParser? detailsParser)
			: this(response.Status, CreateExceptionDetails(response, detailsParser), innerException)
		{
			_response = response;
		}

		protected RequestFailedException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			Status = info.GetInt32("Status");
			ErrorCode = info.GetString("ErrorCode");
		}

		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			Argument.AssertNotNull(info, "info");
			info.AddValue("Status", Status);
			info.AddValue("ErrorCode", ErrorCode);
			base.GetObjectData(info, context);
		}

		public Response? GetRawResponse()
		{
			return _response;
		}

		private static ErrorDetails CreateExceptionDetails(Response response, RequestFailedDetailsParser? parser)
		{
			BufferResponseIfNeeded(response);
			if (parser == null)
			{
				parser = response.RequestFailedDetailsParser;
			}
			if (!(parser?.TryParse(response, out ResponseError error, out IDictionary<string, string> data) ?? DefaultRequestFailedDetailsParser.TryParseDetails(response, out error, out data)))
			{
				error = null;
				data = null;
			}
			StringBuilder stringBuilder = new StringBuilder();
			AppendStatusAndReason(response, error, stringBuilder);
			AppendErrorCodeAndAdditionalInfo(error, data, stringBuilder);
			if (response.IsError)
			{
				AppendContentAndHeaders(response, stringBuilder);
			}
			else
			{
				stringBuilder.AppendLine().AppendLine("Service request succeeded. Response content and headers are not included to avoid logging sensitive data.");
			}
			return new ErrorDetails(stringBuilder.ToString(), error?.Code, data);
		}

		private static void AppendContentAndHeaders(Response response, StringBuilder messageBuilder)
		{
			if (response.ContentStream is MemoryStream && ContentTypeUtilities.TryGetTextEncoding(response.Headers.ContentType, out var _))
			{
				messageBuilder.AppendLine().AppendLine("Content:").AppendLine(((object)response.Content).ToString());
			}
			messageBuilder.AppendLine().AppendLine("Headers:");
			foreach (HttpHeader header in response.Headers)
			{
				string text = response.Sanitizer.SanitizeHeader(header.Name, header.Value);
				string value = header.Name + ": " + text;
				messageBuilder.AppendLine(value);
			}
		}

		private static void AppendErrorCodeAndAdditionalInfo(ResponseError? error, IDictionary<string, string>? additionalInfo, StringBuilder messageBuilder)
		{
			if (!string.IsNullOrWhiteSpace(error?.Code))
			{
				messageBuilder.Append("ErrorCode: ").Append(error?.Code).AppendLine();
			}
			if (additionalInfo == null || additionalInfo.Count <= 0)
			{
				return;
			}
			messageBuilder.AppendLine().AppendLine("Additional Information:");
			foreach (KeyValuePair<string, string> item in additionalInfo)
			{
				messageBuilder.Append(item.Key).Append(": ").AppendLine(item.Value);
			}
		}

		private static void AppendStatusAndReason(Response response, ResponseError? error, StringBuilder messageBuilder)
		{
			messageBuilder.AppendLine(error?.Message ?? "Service request failed.").Append("Status: ").Append(response.Status.ToString(CultureInfo.InvariantCulture));
			if (!string.IsNullOrEmpty(response.ReasonPhrase))
			{
				messageBuilder.Append(" (").Append(response.ReasonPhrase).AppendLine(")");
			}
			else
			{
				messageBuilder.AppendLine();
			}
		}

		private static void BufferResponseIfNeeded(Response response)
		{
			Stream contentStream = response.ContentStream;
			if ((contentStream != null && !(contentStream is MemoryStream)) || 1 == 0)
			{
				MemoryStream memoryStream = new MemoryStream();
				response.ContentStream.CopyTo(memoryStream);
				response.ContentStream.Dispose();
				memoryStream.Position = 0L;
				response.ContentStream = memoryStream;
			}
		}
	}
	public abstract class Response : IDisposable
	{
		public abstract int Status { get; }

		public abstract string ReasonPhrase { get; }

		public abstract Stream? ContentStream { get; set; }

		public abstract string ClientRequestId { get; set; }

		public virtual ResponseHeaders Headers => new ResponseHeaders(this);

		public virtual BinaryData Content
		{
			get
			{
				//IL_0049: Unknown result type (might be due to invalid IL or missing references)
				//IL_004f: Expected O, but got Unknown
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Expected O, but got Unknown
				if (ContentStream == null)
				{
					return BinaryData.Empty;
				}
				if (!(ContentStream is MemoryStream memoryStream))
				{
					throw new InvalidOperationException("The response is not fully buffered.");
				}
				if (!memoryStream.TryGetBuffer(out var buffer))
				{
					return new BinaryData(memoryStream.ToArray());
				}
				return new BinaryData((ReadOnlyMemory<byte>)buffer.AsMemory());
			}
		}

		public virtual bool IsError { get; internal set; }

		internal HttpMessageSanitizer Sanitizer { get; set; } = HttpMessageSanitizer.Default;


		internal RequestFailedDetailsParser? RequestFailedDetailsParser { get; set; }

		public abstract void Dispose();

		protected internal abstract bool TryGetHeader(string name, [NotNullWhen(true)] out string? value);

		protected internal abstract bool TryGetHeaderValues(string name, [NotNullWhen(true)] out IEnumerable<string>? values);

		protected internal abstract bool ContainsHeader(string name);

		protected internal abstract IEnumerable<HttpHeader> EnumerateHeaders();

		public static Response<T> FromValue<T>(T value, Response response)
		{
			return new ValueResponse<T>(response, value);
		}

		public override string ToString()
		{
			return $"Status: {Status}, ReasonPhrase: {ReasonPhrase}";
		}

		internal static void DisposeStreamIfNotBuffered(ref Stream? stream)
		{
			if (!(stream is MemoryStream))
			{
				stream?.Dispose();
				stream = null;
			}
		}
	}
	[JsonConverter(typeof(Converter))]
	[TypeReferenceType(true, new string[] { "Target", "Details" })]
	public sealed class ResponseError : IJsonModel<ResponseError>, IPersistableModel<ResponseError>
	{
		internal class Converter : JsonConverter<ResponseError?>
		{
			public override ResponseError? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
				return ReadFromJson(jsonDocument.RootElement);
			}

			public override void Write(Utf8JsonWriter writer, ResponseError? value, JsonSerializerOptions options)
			{
				throw new NotImplementedException();
			}
		}

		private readonly JsonElement _element;

		public string? Code { get; }

		public string? Message { get; }

		internal ResponseInnerError? InnerError { get; }

		internal string? Target { get; }

		internal IReadOnlyList<ResponseError> Details { get; }

		public ResponseError()
			: this(null, null)
		{
		}

		[InitializationConstructor]
		public ResponseError(string? code, string? message)
			: this(code, message, null, default(JsonElement))
		{
		}

		[SerializationConstructor]
		internal ResponseError(string? code, string? message, string? target, JsonElement element, ResponseInnerError? innerError = null, IReadOnlyList<ResponseError>? details = null)
		{
			_element = element;
			Code = code;
			Message = message;
			InnerError = innerError;
			Target = target;
			Details = details ?? Array.Empty<ResponseError>();
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder, includeRaw: true);
			return stringBuilder.ToString();
		}

		internal void Append(StringBuilder builder, bool includeRaw)
		{
			builder.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}{2}", Code, Message, Environment.NewLine);
			if (Target != null)
			{
				builder.AppendFormat(CultureInfo.InvariantCulture, "Target: {0}{1}", Target, Environment.NewLine);
			}
			ResponseInnerError innerError = InnerError;
			if (innerError != null)
			{
				builder.AppendLine();
				builder.AppendLine("Inner Errors:");
				while (innerError != null)
				{
					builder.AppendLine(innerError.Code);
					innerError = innerError.InnerError;
				}
			}
			if (Details.Count > 0)
			{
				builder.AppendLine();
				builder.AppendLine("Details:");
				foreach (ResponseError detail in Details)
				{
					detail.Append(builder, includeRaw: false);
				}
			}
			if (includeRaw && _element.ValueKind != 0)
			{
				builder.AppendLine();
				builder.AppendLine("Raw:");
				builder.Append(_element.GetRawText());
			}
		}

		private void Write(Utf8JsonWriter writer)
		{
			writer.WriteStartObject();
			if (Code != null)
			{
				writer.WritePropertyName("code");
				writer.WriteStringValue(Code);
			}
			if (Message != null)
			{
				writer.WritePropertyName("message");
				writer.WriteStringValue(Message);
			}
			if (Target != null)
			{
				writer.WritePropertyName("target");
				writer.WriteStringValue(Target);
			}
			if (InnerError != null)
			{
				writer.WritePropertyName("innererror");
				InnerError.Write(writer, ModelReaderWriterOptions.Json);
			}
			if (Details.Count > 0)
			{
				writer.WritePropertyName("details");
				writer.WriteStartArray();
				foreach (ResponseError detail in Details)
				{
					if (detail == null)
					{
						writer.WriteNullValue();
					}
					else
					{
						detail.Write(writer);
					}
				}
				writer.WriteEndArray();
			}
			writer.WriteEndObject();
		}

		private static ResponseError? ReadFromJson(JsonElement element)
		{
			if (element.ValueKind == JsonValueKind.Null)
			{
				return null;
			}
			string code = null;
			if (element.TryGetProperty("code", out var value))
			{
				code = value.GetString();
			}
			string message = null;
			if (element.TryGetProperty("message", out value))
			{
				message = value.GetString();
			}
			string target = null;
			if (element.TryGetProperty("target", out value))
			{
				target = value.GetString();
			}
			ResponseInnerError innerError = null;
			if (element.TryGetProperty("innererror", out value))
			{
				innerError = ResponseInnerError.ReadFromJson(value);
			}
			List<ResponseError> list = null;
			if (element.TryGetProperty("details", out value) && value.ValueKind == JsonValueKind.Array)
			{
				foreach (JsonElement item in value.EnumerateArray())
				{
					ResponseError responseError = ReadFromJson(item);
					if (responseError != null)
					{
						if (list == null)
						{
							list = new List<ResponseError>();
						}
						list.Add(responseError);
					}
				}
			}
			return new ResponseError(code, message, target, element.Clone(), innerError, list);
		}

		void IJsonModel<ResponseError>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? ((IPersistableModel<ResponseError>)(object)this).GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model ResponseError does not support '" + text + "' format.");
			}
			writer.WriteStartObject();
			if (Code != null)
			{
				writer.WritePropertyName("code");
				writer.WriteStringValue(Code);
			}
			if (Message != null)
			{
				writer.WritePropertyName("message");
				writer.WriteStringValue(Message);
			}
			if (Target != null)
			{
				writer.WritePropertyName("target");
				writer.WriteStringValue(Target);
			}
			if (InnerError != null)
			{
				writer.WritePropertyName("innererror");
				InnerError.Write(writer, ModelReaderWriterOptions.Json);
			}
			if (Details.Count > 0)
			{
				writer.WritePropertyName("details");
				writer.WriteStartArray();
				foreach (ResponseError detail in Details)
				{
					if (detail == null)
					{
						writer.WriteNullValue();
					}
					else
					{
						detail.Write(writer);
					}
				}
				writer.WriteEndArray();
			}
			writer.WriteEndObject();
		}

		ResponseError IJsonModel<ResponseError>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? ((IPersistableModel<ResponseError>)(object)this).GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model ResponseError does not support '" + text + "' format.");
			}
			using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
			return ReadFromJson(jsonDocument.RootElement) ?? new ResponseError();
		}

		BinaryData IPersistableModel<ResponseError>.Write(ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? ((IPersistableModel<ResponseError>)(object)this).GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model ResponseError does not support '" + text + "' format.");
			}
			return ModelReaderWriter.Write<ResponseError>(this, options, (ModelReaderWriterContext)(object)AzureCoreContext.Default);
		}

		ResponseError IPersistableModel<ResponseError>.Create(BinaryData data, ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? ((IPersistableModel<ResponseError>)(object)this).GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model ResponseError does not support '" + text + "' format.");
			}
			using JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(data));
			return ReadFromJson(jsonDocument.RootElement) ?? new ResponseError();
		}

		string IPersistableModel<ResponseError>.GetFormatFromOptions(ModelReaderWriterOptions options)
		{
			return "J";
		}
	}
	[JsonConverter(typeof(ResponseInnerErrorConverter))]
	internal sealed class ResponseInnerError : IJsonModel<ResponseInnerError>, IPersistableModel<ResponseInnerError>
	{
		internal class ResponseInnerErrorConverter : JsonConverter<ResponseInnerError?>
		{
			public override ResponseInnerError? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
				return ReadFromJson(jsonDocument.RootElement);
			}

			public override void Write(Utf8JsonWriter writer, ResponseInnerError? value, JsonSerializerOptions options)
			{
				throw new NotImplementedException();
			}
		}

		private readonly JsonElement _innerErrorElement;

		public string? Code { get; }

		public ResponseInnerError? InnerError { get; }

		internal ResponseInnerError()
		{
		}

		internal ResponseInnerError(string? code, ResponseInnerError? innerError, JsonElement innerErrorElement)
		{
			_innerErrorElement = innerErrorElement;
			Code = code;
			InnerError = innerError;
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			Append(stringBuilder);
			return stringBuilder.ToString();
		}

		internal void Append(StringBuilder builder)
		{
			builder.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}", Code, Environment.NewLine);
			if (InnerError != null)
			{
				builder.AppendLine("Inner Error:");
				builder.Append(InnerError);
			}
		}

		private static void WriteInnerError(Utf8JsonWriter writer, ResponseInnerError innerError)
		{
			writer.WriteStartObject();
			if (innerError.Code != null)
			{
				writer.WritePropertyName("code");
				writer.WriteStringValue(innerError.Code);
			}
			if (innerError.InnerError != null)
			{
				writer.WritePropertyName("innererror");
				WriteInnerError(writer, innerError.InnerError);
			}
			writer.WriteEndObject();
		}

		public void Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model ResponseInnerError does not support '" + text + "' format.");
			}
			WriteInnerError(writer, this);
		}

		public ResponseInnerError Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model ResponseInnerError does not support '" + text + "' format.");
			}
			using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
			return ReadFromJson(jsonDocument.RootElement) ?? new ResponseInnerError(null, null, default(JsonElement));
		}

		public BinaryData Write(ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model ResponseInnerError does not support '" + text + "' format.");
			}
			return ModelReaderWriter.Write<ResponseInnerError>(this, options, (ModelReaderWriterContext)(object)AzureCoreContext.Default);
		}

		public ResponseInnerError Create(BinaryData data, ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model ResponseInnerError does not support '" + text + "' format.");
			}
			using JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(data));
			return ReadFromJson(jsonDocument.RootElement) ?? new ResponseInnerError(null, null, default(JsonElement));
		}

		string IPersistableModel<ResponseInnerError>.GetFormatFromOptions(ModelReaderWriterOptions options)
		{
			return "J";
		}

		private string GetFormatFromOptions(ModelReaderWriterOptions options)
		{
			return "J";
		}

		internal static ResponseInnerError? ReadFromJson(JsonElement element)
		{
			if (element.ValueKind == JsonValueKind.Null)
			{
				return null;
			}
			string code = null;
			if (element.TryGetProperty("code", out var value))
			{
				code = value.GetString();
			}
			ResponseInnerError innerError = null;
			if (element.TryGetProperty("innererror", out value))
			{
				innerError = ReadFromJson(value);
			}
			return new ResponseInnerError(code, innerError, element.Clone());
		}
	}
	[DebuggerTypeProxy(typeof(ResponseDebugView<>))]
	public abstract class Response<T> : NullableResponse<T>
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool HasValue => true;

		public override T Value => Value;

		public static implicit operator T(Response<T> response)
		{
			if (response == null)
			{
				throw new ArgumentNullException("response", $"The implicit cast from Response<{typeof(T)}> to {typeof(T)} failed because the Response<{typeof(T)}> was null.");
			}
			return response.Value;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals(object? obj)
		{
			return base.Equals(obj);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}
	}
	public static class AzureCoreExtensions
	{
		public static T? ToObject<T>(this BinaryData data, ObjectSerializer serializer, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (T)serializer.Deserialize(data.ToStream(), typeof(T), cancellationToken);
		}

		public static async ValueTask<T?> ToObjectAsync<T>(this BinaryData data, ObjectSerializer serializer, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (T)(await serializer.DeserializeAsync(data.ToStream(), typeof(T), cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
		}

		[RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
		[RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
		public static object? ToObjectFromJson(this BinaryData data)
		{
			JsonElement element = data.ToObjectFromJson<JsonElement>((JsonSerializerOptions)null);
			return element.GetObject();
		}

		[RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
		[RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
		public static dynamic ToDynamicFromJson(this BinaryData utf8Json)
		{
			DynamicDataOptions options = new DynamicDataOptions();
			return utf8Json.ToDynamicFromJson(options);
		}

		[RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
		[RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
		public static dynamic ToDynamicFromJson(this BinaryData utf8Json, JsonPropertyNames propertyNameFormat, string dateTimeFormat = "o")
		{
			DynamicDataOptions options = new DynamicDataOptions
			{
				PropertyNameFormat = propertyNameFormat,
				DateTimeFormat = dateTimeFormat
			};
			return utf8Json.ToDynamicFromJson(options);
		}

		[RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
		[RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
		internal static dynamic ToDynamicFromJson(this BinaryData utf8Json, DynamicDataOptions options)
		{
			return new DynamicData(MutableJsonDocument.Parse(utf8Json, DynamicDataOptions.ToSerializerOptions(options)).RootElement, options);
		}

		private static object? GetObject(this in JsonElement element)
		{
			switch (element.ValueKind)
			{
			case JsonValueKind.String:
				return element.GetString();
			case JsonValueKind.Number:
			{
				if (element.TryGetInt32(out var value))
				{
					return value;
				}
				if (element.TryGetInt64(out var value2))
				{
					return value2;
				}
				return element.GetDouble();
			}
			case JsonValueKind.True:
				return true;
			case JsonValueKind.False:
				return false;
			case JsonValueKind.Undefined:
			case JsonValueKind.Null:
				return null;
			case JsonValueKind.Object:
			{
				Dictionary<string, object> dictionary = new Dictionary<string, object>();
				{
					foreach (JsonProperty item in element.EnumerateObject())
					{
						string name = item.Name;
						JsonElement element3 = item.Value;
						dictionary.Add(name, element3.GetObject());
					}
					return dictionary;
				}
			}
			case JsonValueKind.Array:
			{
				List<object> list = new List<object>();
				foreach (JsonElement item2 in element.EnumerateArray())
				{
					JsonElement element2 = item2;
					list.Add(element2.GetObject());
				}
				return list.ToArray();
			}
			default:
				throw new NotSupportedException("Not supported value kind " + element.ValueKind);
			}
		}
	}
	public class SyncAsyncEventArgs : EventArgs
	{
		public bool IsRunningSynchronously { get; }

		public CancellationToken CancellationToken { get; }

		public SyncAsyncEventArgs(bool isRunningSynchronously, CancellationToken cancellationToken = default(CancellationToken))
		{
			IsRunningSynchronously = isRunningSynchronously;
			CancellationToken = cancellationToken;
		}
	}
	public enum WaitUntil
	{
		Completed,
		Started
	}
	internal class ResponseError_Builder : ModelReaderWriterTypeBuilder
	{
		protected override Type BuilderType => typeof(ResponseError);

		protected override object CreateInstance()
		{
			return new ResponseError();
		}
	}
	internal class ResponseInnerError_Builder : ModelReaderWriterTypeBuilder
	{
		protected override Type BuilderType => typeof(ResponseInnerError);

		protected override object CreateInstance()
		{
			return new ResponseInnerError();
		}
	}
}
namespace Azure.Messaging
{
	[JsonConverter(typeof(CloudEventConverter))]
	[RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
	[RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
	public class CloudEvent
	{
		private string? _id;

		private string? _source;

		private string? _type;

		public BinaryData? Data { get; set; }

		public string Id
		{
			get
			{
				return _id;
			}
			set
			{
				Argument.AssertNotNull(value, "value");
				_id = value;
			}
		}

		internal CloudEventDataFormat DataFormat { get; set; }

		public string Source
		{
			get
			{
				return _source;
			}
			set
			{
				Argument.AssertNotNull(value, "value");
				_source = value;
			}
		}

		public string Type
		{
			get
			{
				return _type;
			}
			set
			{
				Argument.AssertNotNull(value, "value");
				_type = value;
			}
		}

		internal string? SpecVersion { get; set; }

		public DateTimeOffset? Time { get; set; } = DateTimeOffset.UtcNow;


		public string? DataSchema { get; set; }

		public string? DataContentType { get; set; }

		internal Type? DataSerializationType { get; }

		public string? Subject { get; set; }

		public IDictionary<string, object> ExtensionAttributes { get; } = new CloudEventExtensionAttributes<string, object>();


		public CloudEvent(string source, string type, object? jsonSerializableData, Type? dataSerializationType = null)
		{
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			if (jsonSerializableData is BinaryData)
			{
				throw new InvalidOperationException("This constructor does not support BinaryData. Use the constructor that takes a BinaryData instance.");
			}
			Source = source;
			Type = type;
			Id = Guid.NewGuid().ToString();
			DataFormat = CloudEventDataFormat.Json;
			Data = new BinaryData(jsonSerializableData, (JsonSerializerOptions)null, dataSerializationType ?? jsonSerializableData?.GetType());
			SpecVersion = "1.0";
		}

		public CloudEvent(string source, string type, BinaryData? data, string? dataContentType, CloudEventDataFormat dataFormat = CloudEventDataFormat.Binary)
		{
			Source = source;
			Type = type;
			DataContentType = dataContentType;
			Id = Guid.NewGuid().ToString();
			DataFormat = dataFormat;
			Data = data;
			SpecVersion = "1.0";
		}

		internal CloudEvent()
		{
		}

		public static CloudEvent[] ParseMany(BinaryData json, bool skipValidation = false)
		{
			Argument.AssertNotNull<BinaryData>(json, "json");
			CloudEvent[] array = null;
			JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(json));
			if (jsonDocument.RootElement.ValueKind == JsonValueKind.Object)
			{
				array = new CloudEvent[1] { CloudEventConverter.DeserializeCloudEvent(jsonDocument.RootElement, skipValidation) };
			}
			else if (jsonDocument.RootElement.ValueKind == JsonValueKind.Array)
			{
				array = new CloudEvent[jsonDocument.RootElement.GetArrayLength()];
				int num = 0;
				foreach (JsonElement item in jsonDocument.RootElement.EnumerateArray())
				{
					array[num++] = CloudEventConverter.DeserializeCloudEvent(item, skipValidation);
				}
			}
			return array ?? Array.Empty<CloudEvent>();
		}

		public static CloudEvent? Parse(BinaryData json, bool skipValidation = false)
		{
			Argument.AssertNotNull<BinaryData>(json, "json");
			using JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(json));
			CloudEvent result = null;
			if (jsonDocument.RootElement.ValueKind == JsonValueKind.Object)
			{
				result = CloudEventConverter.DeserializeCloudEvent(jsonDocument.RootElement, skipValidation);
			}
			else if (jsonDocument.RootElement.ValueKind == JsonValueKind.Array)
			{
				if (jsonDocument.RootElement.GetArrayLength() > 1)
				{
					throw new ArgumentException("The BinaryData instance contains JSON from multiple cloud events. This method should only be used with BinaryData containing a single cloud event. " + Environment.NewLine + "To parse multiple events, use the ParseMany overload.");
				}
				using JsonElement.ArrayEnumerator arrayEnumerator = jsonDocument.RootElement.EnumerateArray().GetEnumerator();
				if (arrayEnumerator.MoveNext())
				{
					result = CloudEventConverter.DeserializeCloudEvent(arrayEnumerator.Current, skipValidation);
				}
			}
			return result;
		}
	}
	internal class CloudEventConstants
	{
		public const string SpecVersion = "specversion";

		public const string Id = "id";

		public const string Source = "source";

		public const string Type = "type";

		public const string DataContentType = "datacontenttype";

		public const string DataSchema = "dataschema";

		public const string Subject = "subject";

		public const string Time = "time";

		public const string Data = "data";

		public const string DataBase64 = "data_base64";

		public const string ErrorSkipValidationSuggestion = "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation.";
	}
	[RequiresUnreferencedCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
	[RequiresDynamicCode("This utilizes reflection-based JSON serialization and deserialization which is not compatible with trimming.")]
	internal class CloudEventConverter : JsonConverter<CloudEvent>
	{
		public override CloudEvent Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
			return DeserializeCloudEvent(jsonDocument.RootElement, skipValidation: false);
		}

		internal static CloudEvent DeserializeCloudEvent(JsonElement element, bool skipValidation)
		{
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Expected O, but got Unknown
			CloudEvent cloudEvent = new CloudEvent();
			foreach (JsonProperty item in element.EnumerateObject())
			{
				if (item.NameEquals("id"))
				{
					if (item.Value.ValueKind != JsonValueKind.Null)
					{
						cloudEvent.Id = item.Value.GetString();
					}
				}
				else if (item.NameEquals("source"))
				{
					if (item.Value.ValueKind != JsonValueKind.Null)
					{
						cloudEvent.Source = item.Value.GetString();
					}
				}
				else if (item.NameEquals("data"))
				{
					cloudEvent.Data = new BinaryData((object)item.Value, (JsonSerializerOptions)null, (Type)null);
					cloudEvent.DataFormat = CloudEventDataFormat.Json;
				}
				else if (item.NameEquals("data_base64"))
				{
					if (item.Value.ValueKind != JsonValueKind.Null)
					{
						cloudEvent.Data = BinaryData.FromBytes(item.Value.GetBytesFromBase64());
						cloudEvent.DataFormat = CloudEventDataFormat.Binary;
					}
				}
				else if (item.NameEquals("type"))
				{
					if (item.Value.ValueKind != JsonValueKind.Null)
					{
						cloudEvent.Type = item.Value.GetString();
					}
				}
				else if (item.NameEquals("time"))
				{
					if (item.Value.ValueKind != JsonValueKind.Null)
					{
						cloudEvent.Time = item.Value.GetDateTimeOffset();
					}
				}
				else if (item.NameEquals("specversion"))
				{
					cloudEvent.SpecVersion = item.Value.GetString();
				}
				else if (item.NameEquals("dataschema"))
				{
					cloudEvent.DataSchema = item.Value.GetString();
				}
				else if (item.NameEquals("datacontenttype"))
				{
					cloudEvent.DataContentType = item.Value.GetString();
				}
				else if (item.NameEquals("subject"))
				{
					cloudEvent.Subject = item.Value.GetString();
				}
				else if (!skipValidation)
				{
					IDictionary<string, object> extensionAttributes = cloudEvent.ExtensionAttributes;
					string name = item.Name;
					JsonElement element2 = item.Value;
					extensionAttributes.Add(name, GetObject(in element2));
				}
				else
				{
					CloudEventExtensionAttributes<string, object> obj = (CloudEventExtensionAttributes<string, object>)cloudEvent.ExtensionAttributes;
					string name2 = item.Name;
					JsonElement element2 = item.Value;
					obj.AddWithoutValidation(name2, GetObject(in element2));
				}
			}
			if (!skipValidation)
			{
				if (cloudEvent.Source == null)
				{
					throw new ArgumentException("The source property must be specified in each CloudEvent. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation.");
				}
				if (cloudEvent.Type == null)
				{
					throw new ArgumentException("The type property must be specified in each CloudEvent. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation.");
				}
				if (cloudEvent.Id == null)
				{
					throw new ArgumentException("The Id property must be specified in each CloudEvent. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation.");
				}
				if (cloudEvent.SpecVersion != "1.0")
				{
					if (cloudEvent.SpecVersion == null)
					{
						throw new ArgumentException("The specverion was not set in at least one of the events in the payload. This type only supports specversion '1.0', which must be set for each event. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation." + Environment.NewLine + element, "element");
					}
					throw new ArgumentException("The specverion value of '" + cloudEvent.SpecVersion + "' is not supported by CloudEvent. This type only supports specversion '1.0'. " + Environment.NewLine + "The `skipValidation` parameter can be set to 'true' in the CloudEvent.Parse or CloudEvent.ParseEvents method to skip this validation." + Environment.NewLine + element, "element");
				}
			}
			return cloudEvent;
		}

		public override void Write(Utf8JsonWriter writer, CloudEvent value, JsonSerializerOptions options)
		{
			writer.WriteStartObject();
			writer.WritePropertyName("id");
			writer.WriteStringValue(value.Id);
			writer.WritePropertyName("source");
			writer.WriteStringValue(value.Source);
			writer.WritePropertyName("type");
			writer.WriteStringValue(value.Type);
			if (value.Data != null)
			{
				switch (value.DataFormat)
				{
				case CloudEventDataFormat.Binary:
					writer.WritePropertyName("data_base64");
					writer.WriteBase64StringValue(value.Data.ToArray());
					break;
				case CloudEventDataFormat.Json:
				{
					using (JsonDocument jsonDocument = JsonDocument.Parse(value.Data.ToMemory()))
					{
						writer.WritePropertyName("data");
						jsonDocument.RootElement.WriteTo(writer);
					}
					break;
				}
				}
			}
			if (value.Time.HasValue)
			{
				writer.WritePropertyName("time");
				writer.WriteStringValue(value.Time.Value);
			}
			writer.WritePropertyName("specversion");
			writer.WriteStringValue(value.SpecVersion);
			if (value.DataSchema != null)
			{
				writer.WritePropertyName("dataschema");
				writer.WriteStringValue(value.DataSchema);
			}
			if (value.DataContentType != null)
			{
				writer.WritePropertyName("datacontenttype");
				writer.WriteStringValue(value.DataContentType);
			}
			if (value.Subject != null)
			{
				writer.WritePropertyName("subject");
				writer.WriteStringValue(value.Subject);
			}
			foreach (KeyValuePair<string, object> extensionAttribute in value.ExtensionAttributes)
			{
				writer.WritePropertyName(extensionAttribute.Key);
				WriteObjectValue(writer, extensionAttribute.Value);
			}
			writer.WriteEndObject();
		}

		private static void WriteObjectValue(Utf8JsonWriter writer, object? value)
		{
			if (value != null)
			{
				if (!(value is byte[] inArray))
				{
					if (!(value is ReadOnlyMemory<byte> readOnlyMemory))
					{
						if (!(value is int value2))
						{
							if (!(value is string value3))
							{
								if (!(value is bool value4))
								{
									if (!(value is Guid value5))
									{
										if (!(value is Uri uri))
										{
											if (!(value is DateTimeOffset value6))
											{
												if (!(value is DateTime value7))
												{
													if (!(value is IEnumerable<KeyValuePair<string, object>> enumerable))
													{
														if (value is IEnumerable<object> enumerable2)
														{
															writer.WriteStartArray();
															foreach (object item in enumerable2)
															{
																WriteObjectValue(writer, item);
															}
															writer.WriteEndArray();
															return;
														}
														throw new NotSupportedException("Not supported type " + value.GetType());
													}
													writer.WriteStartObject();
													foreach (KeyValuePair<string, object> item2 in enumerable)
													{
														writer.WritePropertyName(item2.Key);
														WriteObjectValue(writer, item2.Value);
													}
													writer.WriteEndObject();
												}
												else
												{
													writer.WriteStringValue(value7);
												}
											}
											else
											{
												writer.WriteStringValue(value6);
											}
										}
										else
										{
											writer.WriteStringValue(uri.ToString());
										}
									}
									else
									{
										writer.WriteStringValue(value5);
									}
								}
								else
								{
									writer.WriteBooleanValue(value4);
								}
							}
							else
							{
								writer.WriteStringValue(value3);
							}
						}
						else
						{
							writer.WriteNumberValue(value2);
						}
					}
					else
					{
						writer.WriteStringValue(Convert.ToBase64String(readOnlyMemory.ToArray()));
					}
				}
				else
				{
					writer.WriteStringValue(Convert.ToBase64String(inArray));
				}
			}
			else
			{
				writer.WriteNullValue();
			}
		}

		private static object? GetObject(in JsonElement element)
		{
			switch (element.ValueKind)
			{
			case JsonValueKind.String:
				return element.GetString();
			case JsonValueKind.Number:
			{
				if (element.TryGetInt32(out var value))
				{
					return value;
				}
				if (element.TryGetInt64(out var value2))
				{
					return value2;
				}
				return element.GetDouble();
			}
			case JsonValueKind.True:
				return true;
			case JsonValueKind.False:
				return false;
			case JsonValueKind.Undefined:
			case JsonValueKind.Null:
				return null;
			case JsonValueKind.Object:
			{
				Dictionary<string, object> dictionary = new Dictionary<string, object>();
				{
					foreach (JsonProperty item in element.EnumerateObject())
					{
						string name = item.Name;
						JsonElement element3 = item.Value;
						dictionary.Add(name, GetObject(in element3));
					}
					return dictionary;
				}
			}
			case JsonValueKind.Array:
			{
				List<object> list = new List<object>();
				foreach (JsonElement item2 in element.EnumerateArray())
				{
					JsonElement element2 = item2;
					list.Add(GetObject(in element2));
				}
				return list.ToArray();
			}
			default:
				throw new NotSupportedException("Not supported value kind " + element.ValueKind);
			}
		}
	}
	public enum CloudEventDataFormat
	{
		Binary,
		Json
	}
	internal class CloudEventExtensionAttributes<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable where TKey : class
	{
		private readonly Dictionary<TKey, TValue> _backingDictionary;

		private static readonly HashSet<string> s_reservedAttributes = new HashSet<string> { "specversion", "id", "source", "type", "datacontenttype", "dataschema", "subject", "time", "data", "data_base64" };

		public TValue this[TKey key]
		{
			get
			{
				return _backingDictionary[key];
			}
			set
			{
				ValidateAttribute(key as string, value);
				_backingDictionary[key] = value;
			}
		}

		public ICollection<TKey> Keys => _backingDictionary.Keys;

		public ICollection<TValue> Values => _backingDictionary.Values;

		public int Count => _backingDictionary.Count;

		public bool IsReadOnly => ((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).IsReadOnly;

		public CloudEventExtensionAttributes()
		{
			_backingDictionary = new Dictionary<TKey, TValue>();
		}

		public void Add(TKey key, TValue value)
		{
			ValidateAttribute(key as string, value);
			_backingDictionary.Add(key, value);
		}

		public void AddWithoutValidation(TKey key, TValue value)
		{
			_backingDictionary.Add(key, value);
		}

		public void Add(KeyValuePair<TKey, TValue> item)
		{
			ValidateAttribute(item.Key as string, item.Value);
			((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).Add(item);
		}

		public void Clear()
		{
			_backingDictionary.Clear();
		}

		public bool Contains(KeyValuePair<TKey, TValue> item)
		{
			return ((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).Contains(item);
		}

		public bool ContainsKey(TKey key)
		{
			return _backingDictionary.ContainsKey(key);
		}

		public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
		{
			((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).CopyTo(array, arrayIndex);
		}

		public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator()
		{
			return _backingDictionary.GetEnumerator();
		}

		public bool Remove(TKey key)
		{
			return _backingDictionary.Remove(key);
		}

		public bool Remove(KeyValuePair<TKey, TValue> item)
		{
			return ((ICollection<KeyValuePair<TKey, TValue>>)_backingDictionary).Remove(item);
		}

		public bool TryGetValue(TKey key, out TValue value)
		{
			return _backingDictionary.TryGetValue(key, out value);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _backingDictionary.GetEnumerator();
		}

		private static void ValidateAttribute(string? name, object? value)
		{
			Argument.AssertNotNullOrEmpty(name, "name");
			Argument.AssertNotNull(value, "value");
			if (s_reservedAttributes.Contains(name))
			{
				throw new ArgumentException("Attribute name cannot use the reserved attribute: '" + name + "'", "name");
			}
			foreach (char c in name)
			{
				if ((c < '0' || c > '9') && (c < 'a' || c > 'z'))
				{
					throw new ArgumentException($"Invalid character in extension attribute name: '{c}'. " + "CloudEvent attribute names must consist of lower-case letters ('a' to 'z') or digits ('0' to '9') from the ASCII character set.", "name");
				}
			}
			if (value is string || value is byte[] || value is ReadOnlyMemory<byte> || value is int || value is bool || value is Uri || value is DateTime || value is DateTimeOffset)
			{
				return;
			}
			throw new ArgumentException($"Values of type {value.GetType()} are not supported. " + "Attribute values must be of type string, bool, byte, int, Uri, DateTime, or DateTimeOffset.");
		}
	}
	public class MessageContent
	{
		public virtual BinaryData? Data { get; set; }

		public virtual ContentType? ContentType
		{
			get
			{
				return ContentTypeCore;
			}
			set
			{
				ContentTypeCore = value;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		protected virtual ContentType? ContentTypeCore { get; set; }

		public virtual bool IsReadOnly { get; }
	}
}
namespace Azure.Core
{
	public struct AccessToken
	{
		public string Token { get; }

		public DateTimeOffset ExpiresOn { get; }

		public DateTimeOffset? RefreshOn { get; }

		public string TokenType { get; }

		public AccessToken(string accessToken, DateTimeOffset expiresOn)
		{
			RefreshOn = null;
			Token = accessToken;
			ExpiresOn = expiresOn;
			TokenType = "Bearer";
		}

		public AccessToken(string accessToken, DateTimeOffset expiresOn, DateTimeOffset? refreshOn)
		{
			Token = accessToken;
			ExpiresOn = expiresOn;
			RefreshOn = refreshOn;
			TokenType = "Bearer";
		}

		public AccessToken(string accessToken, DateTimeOffset expiresOn, DateTimeOffset? refreshOn, string tokenType)
		{
			Token = accessToken;
			ExpiresOn = expiresOn;
			RefreshOn = refreshOn;
			TokenType = tokenType;
		}

		public override bool Equals(object? obj)
		{
			if (obj is AccessToken accessToken)
			{
				if (accessToken.ExpiresOn == ExpiresOn && accessToken.Token == Token)
				{
					return accessToken.TokenType == TokenType;
				}
				return false;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return HashCodeBuilder.Combine(Token, ExpiresOn, TokenType);
		}

		internal AuthenticationToken ToAuthenticationToken()
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Expected O, but got Unknown
			return new AuthenticationToken(Token, TokenType, ExpiresOn, RefreshOn);
		}
	}
	[ModelReaderWriterBuildable(typeof(ResponseError))]
	[ModelReaderWriterBuildable(typeof(RehydrationToken))]
	[ModelReaderWriterBuildable(typeof(ResponseInnerError))]
	public class AzureCoreContext : ModelReaderWriterContext
	{
		private readonly Dictionary<Type, Func<ModelReaderWriterTypeBuilder>> _typeBuilderFactories = new Dictionary<Type, Func<ModelReaderWriterTypeBuilder>>();

		private readonly ConcurrentDictionary<Type, ModelReaderWriterTypeBuilder> _typeBuilders = new ConcurrentDictionary<Type, ModelReaderWriterTypeBuilder>();

		private static AzureCoreContext _azureCoreContext;

		public static AzureCoreContext Default => _azureCoreContext ?? (_azureCoreContext = new AzureCoreContext());

		private AzureCoreContext()
		{
			_typeBuilderFactories.Add(typeof(ResponseError), () => (ModelReaderWriterTypeBuilder)(object)new ResponseError_Builder());
			_typeBuilderFactories.Add(typeof(RehydrationToken), () => (ModelReaderWriterTypeBuilder)(object)new RehydrationToken_Builder());
			_typeBuilderFactories.Add(typeof(ResponseInnerError), () => (ModelReaderWriterTypeBuilder)(object)new ResponseInnerError_Builder());
		}

		protected override bool TryGetTypeBuilderCore(Type type, out ModelReaderWriterTypeBuilder builder)
		{
			if (_typeBuilders.TryGetValue(type, out builder))
			{
				return true;
			}
			if (_typeBuilderFactories.TryGetValue(type, out var value))
			{
				builder = value();
				_typeBuilders.TryAdd(type, builder);
				return true;
			}
			builder = null;
			return false;
		}
	}
	public readonly struct AzureLocation : IEquatable<AzureLocation>
	{
		private const char Space = ' ';

		private static Dictionary<string, AzureLocation> PublicCloudLocations { get; } = new Dictionary<string, AzureLocation>();


		public static AzureLocation EastAsia { get; } = CreateStaticReference("eastasia", "East Asia");


		public static AzureLocation SoutheastAsia { get; } = CreateStaticReference("southeastasia", "Southeast Asia");


		public static AzureLocation CentralUS { get; } = CreateStaticReference("centralus", "Central US");


		public static AzureLocation EastUS { get; } = CreateStaticReference("eastus", "East US");


		public static AzureLocation EastUS2 { get; } = CreateStaticReference("eastus2", "East US 2");


		public static AzureLocation WestUS { get; } = CreateStaticReference("westus", "West US");


		public static AzureLocation WestUS2 { get; } = CreateStaticReference("westus2", "West US 2");


		public static AzureLocation WestUS3 { get; } = CreateStaticReference("westus3", "West US 3");


		public static AzureLocation NorthCentralUS { get; } = CreateStaticReference("northcentralus", "North Central US");


		public static AzureLocation SouthCentralUS { get; } = CreateStaticReference("southcentralus", "South Central US");


		public static AzureLocation NorthEurope { get; } = CreateStaticReference("northeurope", "North Europe");


		public static AzureLocation WestEurope { get; } = CreateStaticReference("westeurope", "West Europe");


		public static AzureLocation JapanWest { get; } = CreateStaticReference("japanwest", "Japan West");


		public static AzureLocation JapanEast { get; } = CreateStaticReference("japaneast", "Japan East");


		public static AzureLocation BrazilSouth { get; } = CreateStaticReference("brazilsouth", "Brazil South");


		public static AzureLocation AustraliaEast { get; } = CreateStaticReference("australiaeast", "Australia East");


		public static AzureLocation AustraliaSoutheast { get; } = CreateStaticReference("australiasoutheast", "Australia Southeast");


		public static AzureLocation SouthIndia { get; } = CreateStaticReference("southindia", "South India");


		public static AzureLocation CentralIndia { get; } = CreateStaticReference("centralindia", "Central India");


		public static AzureLocation WestIndia { get; } = CreateStaticReference("westindia", "West India");


		public static AzureLocation CanadaCentral { get; } = CreateStaticReference("canadacentral", "Canada Central");


		public static AzureLocation CanadaEast { get; } = CreateStaticReference("canadaeast", "Canada East");


		public static AzureLocation UKSouth { get; } = CreateStaticReference("uksouth", "UK South");


		public static AzureLocation UKWest { get; } = CreateStaticReference("ukwest", "UK West");


		public static AzureLocation WestCentralUS { get; } = CreateStaticReference("westcentralus", "West Central US");


		public static AzureLocation KoreaCentral { get; } = CreateStaticReference("koreacentral", "Korea Central");


		public static AzureLocation KoreaSouth { get; } = CreateStaticReference("koreasouth", "Korea South");


		public static AzureLocation FranceCentral { get; } = CreateStaticReference("francecentral", "France Central");


		public static AzureLocation FranceSouth { get; } = CreateStaticReference("francesouth", "France South");


		public static AzureLocation AustraliaCentral { get; } = CreateStaticReference("australiacentral", "Australia Central");


		public static AzureLocation AustraliaCentral2 { get; } = CreateStaticReference("australiacentral2", "Australia Central 2");


		public static AzureLocation UAECentral { get; } = CreateStaticReference("uaecentral", "UAE Central");


		public static AzureLocation UAENorth { get; } = CreateStaticReference("uaenorth", "UAE North");


		public static AzureLocation SouthAfricaNorth { get; } = CreateStaticReference("southafricanorth", "South Africa North");


		public static AzureLocation SouthAfricaWest { get; } = CreateStaticReference("southafricawest", "South Africa West");


		public static AzureLocation SwedenCentral { get; } = CreateStaticReference("swedencentral", "Sweden Central");


		public static AzureLocation SwedenSouth { get; } = CreateStaticReference("swedensouth", "Sweden South");


		public static AzureLocation SwitzerlandNorth { get; } = CreateStaticReference("switzerlandnorth", "Switzerland North");


		public static AzureLocation SwitzerlandWest { get; } = CreateStaticReference("switzerlandwest", "Switzerland West");


		public static AzureLocation GermanyNorth { get; } = CreateStaticReference("germanynorth", "Germany North");


		public static AzureLocation GermanyWestCentral { get; } = CreateStaticReference("germanywestcentral", "Germany West Central");


		public static AzureLocation GermanyCentral { get; } = CreateStaticReference("germanycentral", "Germany Central");


		public static AzureLocation GermanyNorthEast { get; } = CreateStaticReference("germanynortheast", "Germany Northeast");


		public static AzureLocation NorwayWest { get; } = CreateStaticReference("norwaywest", "Norway West");


		public static AzureLocation NorwayEast { get; } = CreateStaticReference("norwayeast", "Norway East");


		public static AzureLocation BrazilSoutheast { get; } = CreateStaticReference("brazilsoutheast", "Brazil Southeast");


		public static AzureLocation ChinaNorth { get; } = CreateStaticReference("chinanorth", "China North");


		public static AzureLocation ChinaEast { get; } = CreateStaticReference("chinaeast", "China East");


		public static AzureLocation ChinaNorth2 { get; } = CreateStaticReference("chinanorth2", "China North 2");


		public static AzureLocation ChinaNorth3 { get; } = CreateStaticReference("chinanorth3", "China North 3");


		public static AzureLocation ChinaEast2 { get; } = CreateStaticReference("chinaeast2", "China East 2");


		public static AzureLocation ChinaEast3 { get; } = CreateStaticReference("chinaeast3", "China East 3");


		public static AzureLocation QatarCentral { get; } = CreateStaticReference("qatarcentral", "Qatar Central");


		public static AzureLocation USDoDCentral { get; } = CreateStaticReference("usdodcentral", "US DoD Central");


		public static AzureLocation USDoDEast { get; } = CreateStaticReference("usdodeast", "US DoD East");


		public static AzureLocation USGovArizona { get; } = CreateStaticReference("usgovarizona", "US Gov Arizona");


		public static AzureLocation USGovTexas { get; } = CreateStaticReference("usgovtexas", "US Gov Texas");


		public static AzureLocation USGovVirginia { get; } = CreateStaticReference("usgovvirginia", "US Gov Virginia");


		public static AzureLocation USGovIowa { get; } = CreateStaticReference("usgoviowa", "US Gov Iowa");


		public static AzureLocation IsraelCentral { get; } = CreateStaticReference("israelcentral", "Israel Central");


		public static AzureLocation ItalyNorth { get; } = CreateStaticReference("italynorth", "Italy North");


		public static AzureLocation PolandCentral { get; } = CreateStaticReference("polandcentral", "Poland Central");


		public static AzureLocation MexicoCentral { get; } = CreateStaticReference("mexicocentral", "Mexico Central");


		public static AzureLocation SpainCentral { get; } = CreateStaticReference("spaincentral", "Spain Central");


		public string Name { get; }

		public string? DisplayName { get; }

		public AzureLocation(string location)
		{
			if (location == null)
			{
				throw new ArgumentNullException("location");
			}
			Name = GetNameFromDisplayName(location, out var foundSpace);
			string key = (foundSpace ? Name : location.ToLowerInvariant());
			if (PublicCloudLocations.TryGetValue(key, out var value))
			{
				Name = value.Name;
				DisplayName = value.DisplayName;
			}
			else
			{
				DisplayName = (foundSpace ? location : null);
			}
		}

		public AzureLocation(string name,

BepInEx/core/Microsoft.Bcl.AsyncInterfaces.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Bcl.AsyncInterfaces")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides the IAsyncEnumerable<T> and IAsyncDisposable interfaces and helper types for .NET Standard 2.0. This package is not required starting with .NET Standard 2.1 and .NET Core 3.0.")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: AssemblyVersion("10.0.0.1")]
[assembly: TypeForwardedTo(typeof(IAsyncEnumerable<>))]
[assembly: TypeForwardedTo(typeof(IAsyncEnumerator<>))]
[assembly: TypeForwardedTo(typeof(IAsyncDisposable))]
[assembly: TypeForwardedTo(typeof(AsyncIteratorMethodBuilder))]
[assembly: TypeForwardedTo(typeof(AsyncIteratorStateMachineAttribute))]
[assembly: TypeForwardedTo(typeof(ConfiguredAsyncDisposable))]
[assembly: TypeForwardedTo(typeof(ConfiguredCancelableAsyncEnumerable<>))]
[assembly: TypeForwardedTo(typeof(EnumeratorCancellationAttribute))]
[assembly: TypeForwardedTo(typeof(ManualResetValueTaskSourceCore<>))]
[assembly: TypeForwardedTo(typeof(TaskAsyncEnumerableExtensions))]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace System
{
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}

BepInEx/core/Microsoft.Bcl.Numerics.dll

Decompiled 2 weeks ago
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Bcl.Numerics")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides the System.MathF for .NET Standard 2.0")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Bcl.Numerics")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("10.0.0.1")]
[assembly: TypeForwardedTo(typeof(MathF))]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace System
{
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}

BepInEx/core/Microsoft.CognitiveServices.Speech.csharp.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Azure.AI.Common.Internal;
using Azure.Core;
using Microsoft.CognitiveServices.Speech.Audio;
using Microsoft.CognitiveServices.Speech.Diagnostics.Logging;
using Microsoft.CognitiveServices.Speech.Dialog;
using Microsoft.CognitiveServices.Speech.Dialog.Internal;
using Microsoft.CognitiveServices.Speech.Intent;
using Microsoft.CognitiveServices.Speech.Internal;
using Microsoft.CognitiveServices.Speech.Transcription;
using Microsoft.CognitiveServices.Speech.Translation;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("ReleaseUnity")]
[assembly: AssemblyCopyright("\ufffd Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Microsoft Cognitive Services Speech SDK")]
[assembly: AssemblyFileVersion("1.44.0.28")]
[assembly: AssemblyInformationalVersion("1.44.0+eaf8ce5f789cd9b50e1b7c3afd8ab6c9c521d29e")]
[assembly: AssemblyProduct("Microsoft Cognitive Services Speech SDK")]
[assembly: AssemblyTitle("Microsoft Cognitive Services Speech SDK")]
[assembly: AssemblyVersion("1.44.0.28")]
namespace Azure.AI.Common.Internal
{
	public enum ValueKind
	{
		Error = -1,
		End = 0,
		Object = 123,
		Array = 91,
		String = 34,
		Number = 49,
		Boolean = 98,
		Null = 110,
		Unspecified = 63
	}
	public class JsonValue : DisposableBase
	{
		[CompilerGenerated]
		private sealed class <get_Items>d__16 : IEnumerable<JsonValue>, IEnumerable, IEnumerator<JsonValue>, IDisposable, IEnumerator
		{
			private int <>1__state;

			private JsonValue <>2__current;

			private int <>l__initialThreadId;

			public JsonValue <>4__this;

			private int <i>5__1;

			JsonValue IEnumerator<JsonValue>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<i>5__1 = 0;
					break;
				case 1:
					<>1__state = -1;
					<i>5__1++;
					break;
				}
				if (<i>5__1 < <>4__this.Count)
				{
					<>2__current = <>4__this[<i>5__1];
					<>1__state = 1;
					return true;
				}
				return false;
			}

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

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<JsonValue> IEnumerable<JsonValue>.GetEnumerator()
			{
				<get_Items>d__16 result;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					result = this;
				}
				else
				{
					result = new <get_Items>d__16(0)
					{
						<>4__this = <>4__this
					};
				}
				return result;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<JsonValue>)this).GetEnumerator();
			}
		}

		private Func<InteropSafeHandle> _getHandle;

		private InteropSafeHandle _parser;

		private int _item;

		public int Count { get; }

		public ValueKind Kind { get; }

		public string Name { get; }

		public IEnumerable<JsonValue> Items
		{
			[IteratorStateMachine(typeof(<get_Items>d__16))]
			get
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				<get_Items>d__16 <get_Items>d__ = new <get_Items>d__16(-2);
				<get_Items>d__.<>4__this = this;
				return <get_Items>d__;
			}
		}

		public JsonValue this[int index]
		{
			get
			{
				int num = ai_core_json.ai_core_json_item_at(Handle, _item, index, null);
				IfFalseThrowHr(num < 0, SpxError.NotFound);
				return new JsonValue(_getHandle ?? ((Func<InteropSafeHandle>)(() => _parser)), num);
			}
		}

		public JsonValue this[string key]
		{
			get
			{
				int num = ai_core_json.ai_core_json_item_at(Handle, _item, 0, key);
				IfFalseThrowHr(num < 0, SpxError.NotFound);
				return new JsonValue(_getHandle ?? ((Func<InteropSafeHandle>)(() => _parser)), num);
			}
		}

		internal InteropSafeHandle Handle
		{
			get
			{
				CheckDisposed();
				return _getHandle?.Invoke() ?? _parser;
			}
		}

		public static JsonValue Parse(string json)
		{
			InteropSafeHandle parser;
			int num = ai_core_json.ai_core_json_parser_create(out parser, json);
			IfFalseThrowHr(num < 0, SpxError.InvalidArgument, "Unable to parse json: " + ((json == null || json.Length <= 31) ? (json + "...") : json?.Substring(0, 32)));
			return new JsonValue(parser, null, num);
		}

		private JsonValue(InteropSafeHandle parser, Func<InteropSafeHandle> getHandle, int item)
		{
			_parser = parser;
			_getHandle = getHandle;
			_item = item;
			Count = ai_core_json.native.ai_core_json_item_count(Handle, _item);
			Kind = (ValueKind)ai_core_json.native.ai_core_json_value_kind(Handle, _item);
			Name = ai_core_json.ai_core_json_value_as_string_ptr(Handle, ai_core_json.native.ai_core_json_item_name(Handle, _item), null);
		}

		private JsonValue(Func<InteropSafeHandle> getHandle, int item)
			: this(null, getHandle ?? throw new ArgumentNullException("getHandle"), item)
		{
		}

		public bool HasValue(int index)
		{
			return ai_core_json.ai_core_json_item_at(Handle, _item, index, null) > 0;
		}

		public bool HasValue(string key)
		{
			return ai_core_json.ai_core_json_item_at(Handle, _item, 0, key) > 0;
		}

		public string AsString()
		{
			string text = ai_core_json.ai_core_json_value_as_string_ptr(Handle, _item, null);
			IfFalseThrowHr(text == null, SpxError.InvalidArgument, "Unable to get string value for json pair with name {Name}.");
			return text;
		}

		public string AsStringCopy()
		{
			string text = ai_core_json.ai_core_json_value_as_string_copy(Handle, _item, null);
			IfFalseThrowHr(text == null, SpxError.InvalidArgument, "Unable to get string value for json pair with name {Name}.");
			return text;
		}

		public long AsLong()
		{
			IfFalseThrowHr(Kind != ValueKind.Number, SpxError.InvalidArgument);
			return ai_core_json.native.ai_core_json_value_as_int(Handle, _item, 0L);
		}

		public ulong AsULong()
		{
			IfFalseThrowHr(Kind != ValueKind.Number, SpxError.InvalidArgument);
			return ai_core_json.native.ai_core_json_value_as_uint(Handle, _item, 0uL);
		}

		public double AsDouble()
		{
			IfFalseThrowHr(Kind != ValueKind.Number, SpxError.InvalidArgument);
			return ai_core_json.native.ai_core_json_value_as_double(Handle, _item, 0.0);
		}

		public float AsFloat()
		{
			return (float)AsDouble();
		}

		public bool AsBool()
		{
			IfFalseThrowHr(Kind != ValueKind.Boolean, SpxError.InvalidArgument);
			return ai_core_json.native.ai_core_json_value_as_bool(Handle, _item, defaultValue: false);
		}

		public string AsJson()
		{
			return ai_core_json.ai_core_json_value_as_json_copy(Handle, _item);
		}

		public JsonValue[] AsArray()
		{
			IfFalseThrowHr(Kind != ValueKind.Array, SpxError.InvalidArgument);
			if (Count == 0)
			{
				return Array.Empty<JsonValue>();
			}
			JsonValue[] array = new JsonValue[Count];
			for (int i = 0; i < Count; i++)
			{
				array[i] = this[i];
			}
			return array;
		}

		protected override void Dispose(bool disposeManaged)
		{
			if (disposeManaged)
			{
				_parser?.Dispose();
				_parser = null;
				_getHandle = null;
			}
		}

		private static void IfFalseThrowHr(bool cond, IntPtr error, string errorMessage)
		{
			if (cond)
			{
				string message = string.Format(CultureInfo.CurrentCulture, "Exception with an error code: 0x{0:x} \n{errorMessage}", error);
				throw new ApplicationException(message);
			}
		}

		private static void IfFalseThrowHr(bool cond, IntPtr error)
		{
			IfFalseThrowHr(cond, error, string.Empty);
		}
	}
	public class JsonBuilder : DisposableBase
	{
		private Func<InteropSafeHandle> _getHandle;

		private InteropSafeHandle _builder;

		public int root { get; }

		internal InteropSafeHandle Handle
		{
			get
			{
				CheckDisposed();
				return _getHandle?.Invoke() ?? _builder;
			}
		}

		public JsonBuilder()
		{
			root = ai_core_json.ai_core_json_builder_create(out _builder);
		}

		public int AddItem(int item, int index, string find)
		{
			return ai_core_json.ai_core_json_builder_add(_builder, item, index, find);
		}

		public void SetString(int item, string value)
		{
			using Utf8StringHandle str = new Utf8StringHandle(value);
			using Utf8StringHandle json = new Utf8StringHandle(null);
			int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, json, (UIntPtr)0uL, 34, str, (UIntPtr)(ulong)value.Length, boolean: false, 0, 0.0);
			IfTrueThrowHr(num != 0, (IntPtr)num);
		}

		public void SetJson(int item, string value)
		{
			using Utf8StringHandle json = new Utf8StringHandle(value);
			using Utf8StringHandle str = new Utf8StringHandle(null);
			int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, json, (UIntPtr)(ulong)value.Length, 123, str, (UIntPtr)0uL, boolean: false, 0, 0.0);
			IfTrueThrowHr(num != 0, (IntPtr)num);
		}

		public void SetBoolean(int item, bool value)
		{
			using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(null);
			int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, utf8StringHandle, (UIntPtr)0uL, 98, utf8StringHandle, (UIntPtr)0uL, value, 0, 0.0);
			IfTrueThrowHr(num != 0, (IntPtr)num);
		}

		public void SetInteger(int item, int value)
		{
			using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(null);
			int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, utf8StringHandle, (UIntPtr)0uL, 49, utf8StringHandle, (UIntPtr)0uL, boolean: false, value, 0.0);
			IfTrueThrowHr(num != 0, (IntPtr)num);
		}

		public void SetDouble(int item, double value)
		{
			using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(null);
			int num = ai_core_json.native.ai_core_json_builder_item_set(Handle, item, utf8StringHandle, (UIntPtr)0uL, 49, utf8StringHandle, (UIntPtr)0uL, boolean: false, 0, value);
			IfTrueThrowHr(num != 0, (IntPtr)num);
		}

		public override string ToString()
		{
			return ai_core_json.ai_core_json_value_as_json_copy(Handle, root);
		}

		protected override void Dispose(bool disposeManaged)
		{
			if (disposeManaged)
			{
				_builder?.Dispose();
				_builder = null;
				_getHandle = null;
			}
		}

		private static void IfTrueThrowHr(bool cond, IntPtr error, string errorMessage)
		{
			if (cond)
			{
				string message = string.Format(CultureInfo.CurrentCulture, "Exception with an error code: 0x{0:x} \n{errorMessage}", error);
				throw new ApplicationException(message);
			}
		}

		private static void IfTrueThrowHr(bool cond, IntPtr error)
		{
			IfTrueThrowHr(cond, error, string.Empty);
		}
	}
	internal static class ai_core_json
	{
		internal static class native
		{
			static native()
			{
				DotNetFrameworkAnyCpuSupport.Initialize();
			}

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern IntPtr ai_core_string_create(Utf8StringHandle str, UIntPtr size);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern void ai_core_string_free(IntPtr str);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_parser_create(out IntPtr parser, Utf8StringHandle json, UIntPtr jsize);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			[return: MarshalAs(UnmanagedType.U1)]
			internal static extern bool ai_core_json_parser_handle_is_valid(InteropSafeHandle parser);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern IntPtr ai_core_json_parser_handle_release(IntPtr parser);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_item_count(InteropSafeHandle parserOrBuildder, int item);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_item_at(InteropSafeHandle parserOrBuilder, int item, int index, Utf8StringHandle find);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_item_next(InteropSafeHandle parserOrBuilder, int item);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_item_name(InteropSafeHandle parserOrBuilder, int item);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_value_kind(InteropSafeHandle parserOrBuilder, int item);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			[return: MarshalAs(UnmanagedType.U1)]
			internal static extern bool ai_core_json_value_as_bool(InteropSafeHandle parserOrBuilder, int item, bool defaultValue);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern double ai_core_json_value_as_double(InteropSafeHandle parserOrBuilder, int item, double defaultValue);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern long ai_core_json_value_as_int(InteropSafeHandle parserOrBuilder, int item, long defaultValue);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern ulong ai_core_json_value_as_uint(InteropSafeHandle parserOrBuilder, int item, ulong defaultValue);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern IntPtr ai_core_json_value_as_string_ptr(InteropSafeHandle parserOrBuilder, int item, out IntPtr size);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern IntPtr ai_core_json_value_as_string_copy(InteropSafeHandle parserOrBuilder, int item, Utf8StringHandle defaultValue);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern IntPtr ai_core_json_value_as_json_copy(InteropSafeHandle parserOrBuilder, int item);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_builder_create(out IntPtr builder, Utf8StringHandle json, UIntPtr jsize);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_builder_item_add(InteropSafeHandle builder, int item, int index, Utf8StringHandle find);

			[DllImport("Microsoft.CognitiveServices.Speech.core.dll", CallingConvention = CallingConvention.StdCall)]
			internal static extern int ai_core_json_builder_item_set(InteropSafeHandle builder, int item, Utf8StringHandle json, UIntPtr jsize, int kind, Utf8StringHandle str, UIntPtr ssize, bool boolean, int integer, double number);
		}

		internal static int ai_core_json_parser_create(out InteropSafeHandle parser, string json)
		{
			using Utf8StringHandle utf8StringHandle = new Utf8StringHandle(json);
			IntPtr parser2;
			int result = native.ai_core_json_parser_create(out parser2, utf8StringHandle, (UIntPtr)utf8StringHandle.Length);
			parser = new InteropSafeHandle(parser2, (HandleRelease)native.ai_core_json_parser_handle_release);
			return result;
		}

		internal static int ai_core_json_builder_create(out InteropSafeHandle builder)
		{
			using Utf8StringHandle utf8StringHandle = new Utf8StringHandle("");
			IntPtr builder2;
			int result = native.ai_core_json_builder_create(out builder2, utf8StringHandle, (UIntPtr)utf8StringHandle.Length);
			builder = new InteropSafeHandle(builder2, (HandleRelease)native.ai_core_json_parser_handle_release);
			return result;
		}

		internal static int ai_core_json_builder_add(InteropSafeHandle builder, int item, int index, string find)
		{
			using Utf8StringHandle find2 = new Utf8StringHandle(find);
			return native.ai_core_json_builder_item_add(builder, item, index, find2);
		}

		internal static int ai_core_json_item_at(InteropSafeHandle parserOrBuilder, int item, int index, string find)
		{
			using Utf8StringHandle find2 = new Utf8StringHandle(find);
			return native.ai_core_json_item_at(parserOrBuilder, item, index, find2);
		}

		internal static string ai_core_json_value_as_string_ptr(InteropSafeHandle parserOrBuilder, int item, string defaultValue)
		{
			using (new Utf8StringHandle(defaultValue))
			{
				IntPtr size;
				IntPtr native = ai_core_json.native.ai_core_json_value_as_string_ptr(parserOrBuilder, item, out size);
				return Utf8StringMarshaler.MarshalNativeToManaged(native, size.ToInt32());
			}
		}

		internal static string ai_core_json_value_as_string_copy(InteropSafeHandle parserOrBuilder, int item, string defaultValue)
		{
			using Utf8StringHandle defaultValue2 = new Utf8StringHandle(defaultValue);
			using InteropSafeHandle interopSafeHandle = new InteropSafeHandle(native.ai_core_json_value_as_string_copy(parserOrBuilder, item, defaultValue2), (Action<IntPtr>)native.ai_core_string_free);
			return Utf8StringMarshaler.MarshalNativeToManaged(interopSafeHandle.DangerousGetHandle());
		}

		internal static string ai_core_json_value_as_json_copy(InteropSafeHandle parserOrBuilder, int item)
		{
			using InteropSafeHandle interopSafeHandle = new InteropSafeHandle(native.ai_core_json_value_as_json_copy(parserOrBuilder, item), (Action<IntPtr>)native.ai_core_string_free);
			return Utf8StringMarshaler.MarshalNativeToManaged(interopSafeHandle.DangerousGetHandle());
		}
	}
}
namespace Microsoft.CognitiveServices.Speech
{
	public class AudioDataStream : IDisposable
	{
		internal volatile bool disposed = false;

		internal InteropSafeHandle streamHandle;

		public PropertyCollection Properties { get; private set; }

		public static AudioDataStream FromWavFileInput(string fileName)
		{
			IntPtr audioStream = IntPtr.Zero;
			IntPtr fileName2 = Utf8StringMarshaler.MarshalManagedToNative(fileName);
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_create_from_file(out audioStream, fileName2));
			return new AudioDataStream(audioStream);
		}

		public static AudioDataStream FromResult(SpeechSynthesisResult result)
		{
			SpxExceptionThrower.ThrowIfNull(result);
			IntPtr audioStream = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_create_from_result(out audioStream, result.resultHandle));
			return new AudioDataStream(audioStream);
		}

		public static AudioDataStream FromResult(KeywordRecognitionResult result)
		{
			SpxExceptionThrower.ThrowIfNull(result);
			IntPtr audioStream = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_create_from_keyword_result(out audioStream, result.resultHandle));
			return new AudioDataStream(audioStream);
		}

		internal AudioDataStream(IntPtr streamHandlePtr)
		{
			SpxExceptionThrower.ThrowIfNull(streamHandlePtr);
			streamHandle = new InteropSafeHandle(streamHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_release);
			IntPtr propbag = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_get_property_bag(streamHandle, out propbag));
			Properties = new PropertyCollection(propbag);
		}

		public StreamStatus GetStatus()
		{
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_get_status(streamHandle, out var status));
			return status;
		}

		public bool CanReadData(uint bytesRequested)
		{
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			return Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_can_read_data(streamHandle, bytesRequested);
		}

		public bool CanReadData(uint pos, uint bytesRequested)
		{
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			return Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_can_read_data_from_position(streamHandle, bytesRequested, pos);
		}

		public uint ReadData(byte[] buffer)
		{
			SpxExceptionThrower.ThrowIfNull(buffer, "buffer can not be Null.");
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			IntPtr intPtr = Marshal.AllocHGlobal(buffer.Length);
			uint filledSize;
			try
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_read(streamHandle, intPtr, (uint)buffer.Length, out filledSize));
				filledSize %= int.MaxValue;
				Marshal.Copy(intPtr, buffer, 0, (int)filledSize);
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
			return filledSize;
		}

		public uint ReadData(uint pos, byte[] buffer)
		{
			SpxExceptionThrower.ThrowIfNull(buffer, "buffer can not be Null.");
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			IntPtr intPtr = Marshal.AllocHGlobal(buffer.Length);
			uint filledSize;
			try
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_read_from_position(streamHandle, intPtr, (uint)buffer.Length, pos, out filledSize));
				filledSize %= int.MaxValue;
				Marshal.Copy(intPtr, buffer, 0, (int)filledSize);
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
			return filledSize;
		}

		public Task SaveToWaveFileAsync(string fileName)
		{
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			return Task.Run(delegate
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_save_to_wave_file(streamHandle, fileName));
			});
		}

		public void SetPosition(uint pos)
		{
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_set_position(streamHandle, pos));
		}

		public uint GetPosition()
		{
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_get_position(streamHandle, out var position));
			return position;
		}

		public void DetachInput()
		{
			SpxExceptionThrower.ThrowIfNull(streamHandle, "Invalid stream handle.");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AudioDataStream.audio_data_stream_detach_input(streamHandle));
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (disposing)
				{
					Properties?.Close();
					streamHandle?.Dispose();
				}
				disposed = true;
			}
		}
	}
	public class AutoDetectSourceLanguageConfig
	{
		internal InteropSafeHandle configHandle;

		internal AutoDetectSourceLanguageConfig(IntPtr configPtr)
		{
			SpxExceptionThrower.ThrowIfNull(configPtr);
			configHandle = new InteropSafeHandle(configPtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.auto_detect_source_lang_config_release);
		}

		public static AutoDetectSourceLanguageConfig FromOpenRange()
		{
			IntPtr hAutoDetectSourceLanguageconfig = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.create_auto_detect_source_lang_config_from_open_range(out hAutoDetectSourceLanguageconfig));
			return new AutoDetectSourceLanguageConfig(hAutoDetectSourceLanguageconfig);
		}

		public static AutoDetectSourceLanguageConfig FromLanguages(string[] languages)
		{
			if (languages == null || languages.Length == 0)
			{
				throw new ArgumentNullException("languages");
			}
			foreach (string text in languages)
			{
				if (string.IsNullOrEmpty(text))
				{
					throw new ArgumentNullException(text, "language in languages cannot be null or empty");
				}
			}
			IntPtr hAutoDetectSourceLanguageconfig = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.create_auto_detect_source_lang_config_from_languages(out hAutoDetectSourceLanguageconfig, string.Join(",", languages)));
			return new AutoDetectSourceLanguageConfig(hAutoDetectSourceLanguageconfig);
		}

		public static AutoDetectSourceLanguageConfig FromSourceLanguageConfigs(SourceLanguageConfig[] sourceLanguageConfigs)
		{
			if (sourceLanguageConfigs == null || sourceLanguageConfigs.Length == 0)
			{
				throw new ArgumentNullException("sourceLanguageConfigs");
			}
			IntPtr hAutoDetectSourceLanguageconfig = IntPtr.Zero;
			bool flag = true;
			foreach (SourceLanguageConfig sourceLanguageConfig in sourceLanguageConfigs)
			{
				if (sourceLanguageConfig == null)
				{
					throw new ArgumentNullException("sourceLanguageConfig in sourceLanguageConfigs cannot be null");
				}
				if (flag)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.create_auto_detect_source_lang_config_from_source_lang_config(out hAutoDetectSourceLanguageconfig, sourceLanguageConfig.configHandle));
					flag = false;
				}
				else
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.AutoDetectSourceLanguageConfig.add_source_lang_config_to_auto_detect_source_lang_config(hAutoDetectSourceLanguageconfig, sourceLanguageConfig.configHandle));
				}
			}
			return new AutoDetectSourceLanguageConfig(hAutoDetectSourceLanguageconfig);
		}
	}
	public class AutoDetectSourceLanguageResult
	{
		public string Language { get; }

		public static AutoDetectSourceLanguageResult FromResult(SpeechRecognitionResult result)
		{
			return new AutoDetectSourceLanguageResult(result);
		}

		public static AutoDetectSourceLanguageResult FromResult(TranslationRecognitionResult result)
		{
			return new AutoDetectSourceLanguageResult(result);
		}

		internal AutoDetectSourceLanguageResult(RecognitionResult result)
		{
			SpxExceptionThrower.ThrowIfNull(result);
			Language = result.Properties.GetProperty(PropertyId.SpeechServiceConnection_AutoDetectSourceLanguageResult);
		}
	}
	public sealed class Connection : IDisposable
	{
		private GCHandle gch;

		private volatile bool disposed = false;

		private volatile bool isDisposing = false;

		private InteropSafeHandle connectionHandle;

		private ConnectionCallbackFunctionDelegate connectedCallbackDelegate;

		private ConnectionCallbackFunctionDelegate disconnectedCallbackDelegate;

		private ConnectionCallbackFunctionDelegate messageReceivedCallbackDelegate;

		private object connectionLock = new object();

		private int activeAsyncConnectionCounter = 0;

		private PropertyCollection Properties { get; set; }

		private event EventHandler<ConnectionEventArgs> _Connected;

		private event EventHandler<ConnectionEventArgs> _Disconnected;

		private event EventHandler<ConnectionMessageEventArgs> _MessageReceived;

		public event EventHandler<ConnectionEventArgs> Connected
		{
			add
			{
				if (this._Connected == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_connected_set_callback(connectionHandle, connectedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_Connected += value;
			}
			remove
			{
				_Connected -= value;
				if (this._Connected == null && connectionHandle != null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_connected_set_callback(connectionHandle, null, IntPtr.Zero));
				}
			}
		}

		public event EventHandler<ConnectionEventArgs> Disconnected
		{
			add
			{
				if (this._Disconnected == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_disconnected_set_callback(connectionHandle, disconnectedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_Disconnected += value;
			}
			remove
			{
				_Disconnected -= value;
				if (this._Disconnected == null && connectionHandle != null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_disconnected_set_callback(connectionHandle, null, IntPtr.Zero));
				}
			}
		}

		public event EventHandler<ConnectionMessageEventArgs> MessageReceived
		{
			add
			{
				if (this._MessageReceived == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_set_callback(connectionHandle, messageReceivedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_MessageReceived += value;
			}
			remove
			{
				_MessageReceived -= value;
				if (this._MessageReceived == null && connectionHandle != null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_set_callback(connectionHandle, null, IntPtr.Zero));
				}
			}
		}

		public static Connection FromRecognizer(Recognizer recognizer)
		{
			SpxExceptionThrower.ThrowIfNull(recognizer, "null recognizer");
			IntPtr zero = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_from_recognizer(recognizer.recoHandle, out zero));
			return new Connection(zero);
		}

		public static Connection FromConversationTranslator(Microsoft.CognitiveServices.Speech.Transcription.ConversationTranslator convTrans)
		{
			SpxExceptionThrower.ThrowIfNull(convTrans, "null conversation translator");
			IntPtr zero = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_from_conversation_translator(convTrans._nativeHandle, out zero));
			return new Connection(zero);
		}

		public static Connection FromDialogServiceConnector(Microsoft.CognitiveServices.Speech.Dialog.DialogServiceConnector dialogServiceConnector)
		{
			SpxExceptionThrower.ThrowIfNull(dialogServiceConnector, "null dialog service connector");
			IntPtr zero = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_from_dialog_service_connector(dialogServiceConnector.dialogServiceConnectorHandle, out zero));
			return new Connection(zero);
		}

		public static Connection FromSpeechSynthesizer(SpeechSynthesizer speechSynthesizer)
		{
			SpxExceptionThrower.ThrowIfNull(speechSynthesizer, "null speech synthesizer");
			IntPtr zero = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_from_speech_synthesizer(speechSynthesizer.synthHandle, out zero));
			return new Connection(zero);
		}

		~Connection()
		{
			isDisposing = true;
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			try
			{
				isDisposing = true;
				lock (connectionLock)
				{
					if (activeAsyncConnectionCounter != 0)
					{
						throw new InvalidOperationException("Cannot dispose a connection while async operation is running. Await async connections to avoid unexpected disposals.");
					}
				}
			}
			finally
			{
				Dispose(disposing: true);
				GC.SuppressFinalize(this);
			}
		}

		private void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (connectionHandle != null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_connected_set_callback(connectionHandle, null, IntPtr.Zero));
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_disconnected_set_callback(connectionHandle, null, IntPtr.Zero));
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_set_callback(connectionHandle, null, IntPtr.Zero));
				}
				if (disposing)
				{
					connectionHandle?.Dispose();
					Properties?.Close();
				}
				if (gch.IsAllocated)
				{
					gch.Free();
				}
				disposed = true;
				connectedCallbackDelegate = null;
				disconnectedCallbackDelegate = null;
				messageReceivedCallbackDelegate = null;
			}
		}

		internal Connection(IntPtr connectionPtr)
		{
			SpxExceptionThrower.ThrowIfNull(connectionPtr, "Invalid connectionPtr.");
			connectionHandle = new InteropSafeHandle(connectionPtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_handle_release);
			connectedCallbackDelegate = FireEvent_Connected;
			disconnectedCallbackDelegate = FireEvent_Disconnected;
			messageReceivedCallbackDelegate = FireEvent_MessageReceived;
			IntPtr propbag = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_get_property_bag(connectionHandle, out propbag));
			if (propbag != IntPtr.Zero)
			{
				Properties = new PropertyCollection(propbag);
			}
			gch = GCHandle.Alloc(this, GCHandleType.Weak);
		}

		public void Open(bool forContinuousRecognition)
		{
			bool item = connectionHandle != null;
			IntPtr invalidHandle = SpxError.InvalidHandle;
			SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32());
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_open(connectionHandle, forContinuousRecognition));
		}

		public void Close()
		{
			bool item = connectionHandle != null;
			IntPtr invalidHandle = SpxError.InvalidHandle;
			SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32());
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_close(connectionHandle));
		}

		public Task SendMessageAsync(string path, string payload)
		{
			InteropSafeHandle asyncHandle = null;
			Utf8StringHandle payloadString = new Utf8StringHandle(payload);
			DoAsyncConnectionAction(delegate
			{
				asyncHandle = SendMessage(path, payloadString);
			});
			string s = Properties?.GetProperty("SPEECH-SendMessageTimeout");
			if (!uint.TryParse(s, out var timeout))
			{
				timeout = 90000u;
			}
			return Task.Run(delegate
			{
				DoAsyncConnectionAction(delegate
				{
					try
					{
						SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_send_message_wait_for(asyncHandle, timeout));
					}
					finally
					{
						payloadString.Dispose();
						asyncHandle.Dispose();
					}
				});
			});
		}

		public Task SendMessageAsync(string path, byte[] payload, uint size)
		{
			InteropSafeHandle asyncHandle = null;
			DoAsyncConnectionAction(delegate
			{
				asyncHandle = SendMessageData(path, payload, size);
			});
			string s = Properties?.GetProperty("SPEECH-SendMessageTimeout");
			if (!uint.TryParse(s, out var timeout))
			{
				timeout = 90000u;
			}
			return Task.Run(delegate
			{
				DoAsyncConnectionAction(delegate
				{
					try
					{
						SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_send_message_wait_for(asyncHandle, timeout));
					}
					finally
					{
						asyncHandle.Dispose();
					}
				});
			});
		}

		public void SetMessageProperty(string path, string propertyName, string propertyValue)
		{
			bool item = connectionHandle != null;
			IntPtr invalidHandle = SpxError.InvalidHandle;
			SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32());
			IntPtr name = Utf8StringMarshaler.MarshalManagedToNative(propertyName);
			IntPtr value = Utf8StringMarshaler.MarshalManagedToNative(propertyValue);
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_set_message_property(connectionHandle, path, name, value));
		}

		[MonoPInvokeCallback(typeof(ConnectionCallbackFunctionDelegate))]
		private static void FireEvent_Connected(IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				Connection objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Connection>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					ConnectionEventArgs e = new ConnectionEventArgs(hevent);
					objectFromWeakHandle._Connected?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}

		[MonoPInvokeCallback(typeof(ConnectionCallbackFunctionDelegate))]
		private static void FireEvent_Disconnected(IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				Connection objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Connection>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					ConnectionEventArgs e = new ConnectionEventArgs(hevent);
					objectFromWeakHandle._Disconnected?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}

		[MonoPInvokeCallback(typeof(ConnectionCallbackFunctionDelegate))]
		private static void FireEvent_MessageReceived(IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				Connection objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Connection>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					ConnectionMessageEventArgs e = new ConnectionMessageEventArgs(hevent);
					objectFromWeakHandle._MessageReceived?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}

		private void DoAsyncConnectionAction(Action connectionImplAction)
		{
			lock (connectionLock)
			{
				activeAsyncConnectionCounter++;
			}
			if (disposed || isDisposing)
			{
				throw new ObjectDisposedException(GetType().Name);
			}
			try
			{
				connectionImplAction();
			}
			finally
			{
				lock (connectionLock)
				{
					activeAsyncConnectionCounter--;
				}
			}
		}

		internal InteropSafeHandle SendMessage(string path, Utf8StringHandle payload)
		{
			IntPtr asyncHandle = IntPtr.Zero;
			bool item = connectionHandle != null;
			IntPtr invalidHandle = SpxError.InvalidHandle;
			SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32());
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_send_message_async(connectionHandle, path, payload, out asyncHandle));
			return new InteropSafeHandle(asyncHandle, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_async_handle_release);
		}

		internal InteropSafeHandle SendMessageData(string path, byte[] payload, uint size)
		{
			IntPtr asyncHandle = IntPtr.Zero;
			bool item = connectionHandle != null;
			IntPtr invalidHandle = SpxError.InvalidHandle;
			SpxExceptionThrower.ThrowIfFalse(item, invalidHandle.ToInt32());
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_send_message_data_async(connectionHandle, path, payload, size, out asyncHandle));
			return new InteropSafeHandle(asyncHandle, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_async_handle_release);
		}
	}
	public sealed class ConnectionEventArgs : SessionEventArgs
	{
		internal ConnectionEventArgs(IntPtr eventHandlePtr)
			: base(eventHandlePtr)
		{
		}
	}
	internal enum ConnectionEventType
	{
		ConnectedEvent,
		DisconnectedEvent
	}
	public class ConnectionMessage
	{
		internal InteropSafeHandle connectionMessageHandle;

		public string Path { get; }

		public PropertyCollection Properties { get; private set; }

		internal ConnectionMessage(IntPtr connectionMessageHandlePtr)
		{
			SpxExceptionThrower.ThrowIfNull(connectionMessageHandlePtr);
			connectionMessageHandle = new InteropSafeHandle(connectionMessageHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_handle_release);
			IntPtr propbag = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_get_property_bag(connectionMessageHandle, out propbag));
			Properties = new PropertyCollection(propbag);
			Path = Properties.GetProperty("connection.message.path");
		}

		public bool IsTextMessage()
		{
			SpxExceptionThrower.ThrowIfNull(connectionMessageHandle);
			return Properties.GetProperty("connection.message.type") == "text";
		}

		public bool IsBinaryMessage()
		{
			SpxExceptionThrower.ThrowIfNull(connectionMessageHandle);
			return Properties.GetProperty("connection.message.type") == "binary";
		}

		public string GetTextMessage()
		{
			SpxExceptionThrower.ThrowIfNull(connectionMessageHandle);
			return Properties.GetProperty("connection.message.text.message");
		}

		public byte[] GetBinaryMessage()
		{
			SpxExceptionThrower.ThrowIfNull(connectionMessageHandle);
			uint num = Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_get_data_size(connectionMessageHandle);
			IntPtr intPtr = Marshal.AllocHGlobal((int)num);
			try
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_get_data(connectionMessageHandle, intPtr, num));
				byte[] array = new byte[num];
				Marshal.Copy(intPtr, array, 0, (int)num);
				return array;
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
		}

		public override string ToString()
		{
			return IsTextMessage() ? string.Format(CultureInfo.InvariantCulture, "Path:{0} Type:text Message:{1}", Path, GetTextMessage()) : string.Format(CultureInfo.InvariantCulture, "Path:{0} Type:binary Size:{1}", Path, GetBinaryMessage().Length);
		}
	}
	public sealed class ConnectionMessageEventArgs : System.EventArgs
	{
		internal InteropSafeHandle eventHandle;

		public ConnectionMessage Message { get; }

		internal ConnectionMessageEventArgs(IntPtr eventHandlePtr)
		{
			SpxExceptionThrower.ThrowIfNull(eventHandlePtr);
			eventHandle = new InteropSafeHandle(eventHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_event_handle_release);
			IntPtr hcm = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Connection.connection_message_received_event_get_message(eventHandle, out hcm));
			Message = new ConnectionMessage(hcm);
		}

		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "Message: {0}.", Message.ToString());
		}
	}
	[DataContract]
	internal sealed class DetailedSpeechRecognitionResultCollection
	{
		[DataMember]
		public IEnumerable<DetailedSpeechRecognitionResult> NBest { get; set; }
	}
	[DataContract]
	public sealed class DetailedSpeechRecognitionResult
	{
		[DataMember]
		public double Confidence { get; private set; }

		[DataMember(Name = "Display")]
		public string Text { get; private set; }

		[DataMember(Name = "Lexical")]
		public string LexicalForm { get; private set; }

		[DataMember(Name = "ITN")]
		public string NormalizedForm { get; private set; }

		[DataMember(Name = "MaskedITN")]
		public string MaskedNormalizedForm { get; private set; }

		[DataMember(Name = "PronunciationAssessment")]
		internal SentenceLevelPronunciationAssessmentResult PronunciationAssessment { get; private set; }

		[DataMember(Name = "ContentAssessment")]
		internal ContentAssessmentResult ContentAssessmentResult { get; private set; }

		[DataMember(Name = "Words")]
		public IEnumerable<WordLevelTimingResult> Words { get; private set; }

		[DataMember(Name = "DisplayWords")]
		public IEnumerable<WordLevelTimingResult> DisplayWords { get; private set; }

		internal DetailedSpeechRecognitionResult()
		{
		}

		internal DetailedSpeechRecognitionResult(double confidence, string text, string lexicalForm, string normalizedForm)
		{
			Confidence = confidence;
			Text = text;
			LexicalForm = lexicalForm;
			NormalizedForm = normalizedForm;
			MaskedNormalizedForm = normalizedForm;
		}
	}
	[DataContract]
	public sealed class WordLevelTimingResult
	{
		[DataMember]
		public double Confidence { get; private set; }

		[DataMember]
		public int Duration { get; private set; }

		[DataMember]
		public long Offset { get; private set; }

		[DataMember]
		public string Word { get; private set; }

		[DataMember(Name = "PronunciationAssessment")]
		internal WordLevelPronunciationAssessmentResult PronunciationAssessment { get; private set; }

		[DataMember(Name = "Phonemes")]
		internal IEnumerable<PhonemeLevelTimingResult> Phonemes { get; private set; }

		[DataMember(Name = "Syllables")]
		internal IEnumerable<SyllableLevelTimingResult> Syllables { get; private set; }

		internal WordLevelTimingResult()
		{
		}

		internal WordLevelTimingResult(int duration, long offset, string word)
		{
			Duration = duration;
			Offset = offset;
			Word = word;
		}
	}
	[DataContract]
	public sealed class PhonemeLevelTimingResult
	{
		[DataMember]
		public int Duration { get; private set; }

		[DataMember]
		public long Offset { get; private set; }

		[DataMember]
		public string Phoneme { get; private set; }

		public double AccuracyScore => PronunciationAssessment?.AccuracyScore ?? 0.0;

		public IEnumerable<PronunciationAssessmentNBestPhoneme> NBestPhonemes => PronunciationAssessment?.NBestPhonemes;

		[DataMember(Name = "PronunciationAssessment")]
		private PronunciationAssessmentPhonemeResult PronunciationAssessment { get; set; }

		internal PhonemeLevelTimingResult()
		{
		}
	}
	[DataContract]
	public sealed class SyllableLevelTimingResult
	{
		[DataMember]
		public int Duration { get; private set; }

		[DataMember]
		public long Offset { get; private set; }

		[DataMember]
		public string Syllable { get; private set; }

		[DataMember]
		public string Grapheme { get; private set; }

		public double AccuracyScore => PronunciationAssessment?.AccuracyScore ?? 0.0;

		[DataMember(Name = "PronunciationAssessment")]
		private PronunciationAssessmentAccuracyScore PronunciationAssessment { get; set; }

		internal SyllableLevelTimingResult()
		{
		}
	}
	[DataContract]
	internal sealed class SentenceLevelPronunciationAssessmentResult
	{
		[DataMember]
		public double AccuracyScore { get; private set; }

		[DataMember(Name = "PronScore")]
		public double PronunciationScore { get; private set; }

		[DataMember]
		public double CompletenessScore { get; private set; }

		[DataMember]
		public double FluencyScore { get; private set; }

		[DataMember]
		public double ProsodyScore { get; private set; }
	}
	[DataContract]
	internal sealed class WordLevelPronunciationAssessmentResult
	{
		[DataMember]
		public double AccuracyScore { get; private set; }

		[DataMember]
		public string ErrorType { get; private set; }
	}
	[DataContract]
	internal class PronunciationAssessmentAccuracyScore
	{
		[DataMember]
		public double AccuracyScore { get; private set; }
	}
	[DataContract]
	public sealed class PronunciationAssessmentNBestPhoneme
	{
		[DataMember]
		public string Phoneme { get; private set; }

		[DataMember]
		public double Score { get; private set; }
	}
	[DataContract]
	internal sealed class PronunciationAssessmentPhonemeResult : PronunciationAssessmentAccuracyScore
	{
		[DataMember]
		public IEnumerable<PronunciationAssessmentNBestPhoneme> NBestPhonemes { get; private set; }
	}
	[DataContract]
	public sealed class ContentAssessmentResult
	{
		[DataMember]
		public double GrammarScore { get; private set; }

		[DataMember]
		public double VocabularyScore { get; private set; }

		[DataMember]
		public double TopicScore { get; private set; }
	}
	public sealed class EmbeddedSpeechConfig
	{
		private SpeechConfig config;

		internal InteropSafeHandle configHandle => config.configHandle;

		public string SpeechRecognitionModelName => GetProperty(PropertyId.SpeechServiceConnection_RecoModelName);

		public OutputFormat SpeechRecognitionOutputFormat
		{
			get
			{
				return config.OutputFormat;
			}
			set
			{
				config.OutputFormat = value;
			}
		}

		public string SpeechSynthesisVoiceName => GetProperty(PropertyId.SpeechServiceConnection_SynthOfflineVoice);

		public string SpeechSynthesisOutputFormat => config.SpeechSynthesisOutputFormat;

		public string SpeechTranslationModelName => GetProperty(PropertyId.SpeechTranslation_ModelName);

		public string KeywordRecognitionModelName => GetProperty(PropertyId.KeywordRecognition_ModelName);

		internal EmbeddedSpeechConfig(IntPtr handle)
		{
			config = new SpeechConfig(handle);
		}

		public static EmbeddedSpeechConfig FromPath(string path)
		{
			IntPtr zero = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_create(out zero));
			if (string.IsNullOrWhiteSpace(path))
			{
				throw new ArgumentNullException(path, "path cannot be null or empty");
			}
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_add_path(zero, path));
			return new EmbeddedSpeechConfig(zero);
		}

		public static EmbeddedSpeechConfig FromPaths(string[] paths)
		{
			if (paths == null || paths.Length == 0)
			{
				throw new ArgumentNullException("paths");
			}
			IntPtr zero = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_create(out zero));
			foreach (string text in paths)
			{
				if (string.IsNullOrWhiteSpace(text))
				{
					throw new ArgumentNullException(text, "path cannot be null or empty");
				}
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_add_path(zero, text));
			}
			return new EmbeddedSpeechConfig(zero);
		}

		public ReadOnlyCollection<SpeechRecognitionModel> GetSpeechRecognitionModels()
		{
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_get_num_speech_reco_models(configHandle, out var numModels));
			List<SpeechRecognitionModel> list = new List<SpeechRecognitionModel>();
			IntPtr model = IntPtr.Zero;
			try
			{
				for (uint num = 0u; num < numModels; num++)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_get_speech_reco_model(configHandle, num, out model));
					if (model != Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.SPXHANDLE_INVALID)
					{
						list.Add(new SpeechRecognitionModel(model));
						model = IntPtr.Zero;
					}
				}
			}
			catch
			{
				foreach (SpeechRecognitionModel item in list)
				{
					item.Dispose();
				}
				throw;
			}
			finally
			{
				if (model != Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.SPXHANDLE_INVALID && model != IntPtr.Zero)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.SpeechRecognitionModel.speech_recognition_model_handle_release(model));
				}
			}
			return new ReadOnlyCollection<SpeechRecognitionModel>(list);
		}

		public void SetProperty(string name, string value)
		{
			config.SetProperty(name, value);
		}

		public void SetProperty(PropertyId id, string value)
		{
			config.SetProperty(id, value);
		}

		public string GetProperty(string name)
		{
			return config.GetProperty(name);
		}

		public string GetProperty(PropertyId id)
		{
			return config.GetProperty(id);
		}

		public void SetSpeechRecognitionModel(string name, string license)
		{
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_set_speech_recognition_model(configHandle, name, license));
		}

		public void SetProfanity(ProfanityOption profanity)
		{
			config.SetProfanity(profanity);
		}

		public void SetSpeechSynthesisVoice(string name, string license)
		{
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_set_speech_synthesis_voice(configHandle, name, license));
		}

		public void SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat format)
		{
			config.SetSpeechSynthesisOutputFormat(format);
		}

		public ReadOnlyCollection<SpeechTranslationModel> GetSpeechTranslationModels()
		{
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_get_num_speech_translation_models(configHandle, out var numModels));
			List<SpeechTranslationModel> list = new List<SpeechTranslationModel>();
			IntPtr model = IntPtr.Zero;
			try
			{
				for (uint num = 0u; num < numModels; num++)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_get_speech_translation_model(configHandle, num, out model));
					if (model != Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.SPXHANDLE_INVALID)
					{
						list.Add(new SpeechTranslationModel(model));
						model = IntPtr.Zero;
					}
				}
			}
			catch
			{
				foreach (SpeechTranslationModel item in list)
				{
					item.Dispose();
				}
				throw;
			}
			finally
			{
				if (model != Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.SPXHANDLE_INVALID && model != IntPtr.Zero)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.SpeechTranslationModel.speech_translation_model_handle_release(model));
				}
			}
			return new ReadOnlyCollection<SpeechTranslationModel>(list);
		}

		public void SetSpeechTranslationModel(string name, string license)
		{
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_set_speech_translation_model(configHandle, name, license));
		}

		public void SetKeywordRecognitionModel(string name, string license)
		{
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.EmbeddedSpeechConfig.embedded_speech_config_set_keyword_recognition_model(configHandle, name, license));
		}
	}
	public sealed class HybridSpeechConfig
	{
		private SpeechConfig config;

		internal InteropSafeHandle configHandle => config.configHandle;

		public OutputFormat SpeechRecognitionOutputFormat
		{
			get
			{
				return config.OutputFormat;
			}
			set
			{
				config.OutputFormat = value;
			}
		}

		public string SpeechSynthesisOutputFormat => config.SpeechSynthesisOutputFormat;

		internal HybridSpeechConfig(IntPtr handle)
		{
			config = new SpeechConfig(handle);
		}

		public static HybridSpeechConfig FromConfigs(SpeechConfig cloudSpeechConfig, EmbeddedSpeechConfig embeddedSpeechConfig)
		{
			if (cloudSpeechConfig == null)
			{
				throw new ArgumentNullException("cloudSpeechConfig");
			}
			if (embeddedSpeechConfig == null)
			{
				throw new ArgumentNullException("embeddedSpeechConfig");
			}
			IntPtr zero = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.HybridSpeechConfig.hybrid_speech_config_create(out zero, cloudSpeechConfig.configHandle, embeddedSpeechConfig.configHandle));
			return new HybridSpeechConfig(zero);
		}

		public void SetSpeechSynthesisOutputFormat(SpeechSynthesisOutputFormat format)
		{
			config.SetSpeechSynthesisOutputFormat(format);
		}

		public void SetProperty(string name, string value)
		{
			config.SetProperty(name, value);
		}

		public void SetProperty(PropertyId id, string value)
		{
			config.SetProperty(id, value);
		}

		public string GetProperty(string name)
		{
			return config.GetProperty(name);
		}

		public string GetProperty(PropertyId id)
		{
			return config.GetProperty(id);
		}
	}
	public sealed class KeywordRecognitionModel : IDisposable
	{
		private bool disposed = false;

		internal InteropSafeHandle keywordHandle;

		public static KeywordRecognitionModel FromFile(string fileName)
		{
			IntPtr kwmodel = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_create_from_file(fileName, out kwmodel));
			return new KeywordRecognitionModel(kwmodel);
		}

		public static KeywordRecognitionModel FromConfig(EmbeddedSpeechConfig embeddedSpeechConfig)
		{
			if (embeddedSpeechConfig == null)
			{
				throw new ArgumentNullException("embeddedSpeechConfig");
			}
			IntPtr keywordModel = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_create_from_config(embeddedSpeechConfig.configHandle, out keywordModel));
			return new KeywordRecognitionModel(keywordModel);
		}

		public static KeywordRecognitionModel FromConfig(EmbeddedSpeechConfig embeddedSpeechConfig, string[] userDefinedWakeWords)
		{
			if (embeddedSpeechConfig == null)
			{
				throw new ArgumentNullException("embeddedSpeechConfig");
			}
			IntPtr keywordModel = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_create_from_config(embeddedSpeechConfig.configHandle, out keywordModel));
			foreach (string text in userDefinedWakeWords)
			{
				if (string.IsNullOrWhiteSpace(text))
				{
					throw new ArgumentNullException(text, "wake word cannot be null or empty");
				}
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_add_user_defined_wake_word(keywordModel, text));
			}
			return new KeywordRecognitionModel(keywordModel);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		private void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (disposing)
				{
					keywordHandle?.Dispose();
				}
				disposed = true;
			}
		}

		private KeywordRecognitionModel(IntPtr keywordHandlePtr)
		{
			keywordHandle = new InteropSafeHandle(keywordHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.KeywordRecognitionModel.keyword_recognition_model_handle_release);
		}
	}
	public class KeywordRecognitionEventArgs : RecognitionEventArgs
	{
		public KeywordRecognitionResult Result { get; }

		internal KeywordRecognitionEventArgs(IntPtr eventHandlePtr)
			: base(eventHandlePtr)
		{
			IntPtr result = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognition_event_get_result(eventHandle, out result));
			Result = new KeywordRecognitionResult(result);
		}

		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "SessionId:{0} ResultId:{1} Reason:{2} Recognized text:<{3}>.", base.SessionId, Result.ResultId, Result.Reason, Result.Text);
		}
	}
	public class KeywordRecognitionResult : RecognitionResult
	{
		internal KeywordRecognitionResult(IntPtr resultPtr)
			: base(resultPtr)
		{
		}
	}
	public sealed class KeywordRecognizer : IDisposable
	{
		private GCHandle gch;

		private SpeechRecognizer recognizer;

		private Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioInputKeepAlive;

		private volatile bool isDisposing = false;

		private CallbackFunctionDelegate recognizedCallbackDelegate;

		public PropertyCollection Properties => recognizer.Properties;

		public event EventHandler<KeywordRecognitionEventArgs> Recognized
		{
			add
			{
				if (this._Recognized == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognized_set_callback(recognizer.recoHandle, recognizedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_Recognized += value;
			}
			remove
			{
				_Recognized -= value;
				if (this._Recognized == null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognized_set_callback(recognizer.recoHandle, null, IntPtr.Zero));
				}
			}
		}

		public event EventHandler<SpeechRecognitionCanceledEventArgs> Canceled
		{
			add
			{
				recognizer.Canceled += value;
			}
			remove
			{
				recognizer.Canceled -= value;
			}
		}

		private event EventHandler<KeywordRecognitionEventArgs> _Recognized;

		public KeywordRecognizer(Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig)
		{
			Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig2 = ((audioConfig == null) ? Microsoft.CognitiveServices.Speech.Audio.AudioConfig.FromDefaultMicrophoneInput() : audioConfig);
			try
			{
				recognizer = new SpeechRecognizer(Recognizer.FromConfig(SpxFactory.recognizer_create_keyword_recognizer_from_audio_config, audioConfig2));
				recognizedCallbackDelegate = FireEvent_Recognized;
				gch = GCHandle.Alloc(this, GCHandleType.Weak);
			}
			finally
			{
				if (audioConfig == null)
				{
					audioConfig2.Dispose();
					audioConfig2 = null;
				}
				audioInputKeepAlive = audioConfig;
			}
		}

		public Task<KeywordRecognitionResult> RecognizeOnceAsync(KeywordRecognitionModel model)
		{
			return Task.Run(delegate
			{
				KeywordRecognitionResult result = null;
				recognizer.DoAsyncRecognitionAction(delegate
				{
					IntPtr result2 = IntPtr.Zero;
					SpxExceptionThrower.ThrowIfNull(recognizer.recoHandle, "Invalid recognizer handle");
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognize_keyword_once(recognizer.recoHandle, model.keywordHandle, out result2));
					result = new KeywordRecognitionResult(result2);
				});
				return result;
			});
		}

		public Task StopRecognitionAsync()
		{
			return recognizer.StopKeywordRecognitionAsync();
		}

		public void Dispose()
		{
			if (!isDisposing)
			{
				isDisposing = true;
				recognizedCallbackDelegate = null;
				SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognized_set_callback(recognizer.recoHandle, null, IntPtr.Zero));
				recognizer.Dispose();
				audioInputKeepAlive = null;
			}
		}

		[MonoPInvokeCallback(typeof(CallbackFunctionDelegate))]
		private static void FireEvent_Recognized(IntPtr hreco, IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				KeywordRecognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<KeywordRecognizer>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					KeywordRecognitionEventArgs e = new KeywordRecognitionEventArgs(hevent);
					objectFromWeakHandle._Recognized?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}
	}
	public enum NoMatchReason
	{
		NotRecognized = 1,
		InitialSilenceTimeout,
		InitialBabbleTimeout,
		KeywordNotRecognized,
		EndSilenceTimeout
	}
	public enum OutputFormat
	{
		Simple,
		Detailed
	}
	public enum ProfanityOption
	{
		Masked,
		Removed,
		Raw
	}
	public class PropertyCollection
	{
		private InteropSafeHandle propbagHandle;

		protected internal PropertyCollection(IntPtr propertyBagPtr)
		{
			if (propertyBagPtr != IntPtr.Zero)
			{
				propbagHandle = new InteropSafeHandle(propertyBagPtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_release);
			}
		}

		public virtual void Close()
		{
			propbagHandle.Dispose();
		}

		public virtual string GetProperty(PropertyId id)
		{
			SpxExceptionThrower.ThrowIfNull(propbagHandle);
			return GetPropertyString(propbagHandle, (int)id, null, "");
		}

		public virtual string GetProperty(string propertyName)
		{
			SpxExceptionThrower.ThrowIfNull(propbagHandle);
			return GetPropertyString(propbagHandle, -1, propertyName, "");
		}

		public virtual string GetProperty(PropertyId id, string defaultValue)
		{
			SpxExceptionThrower.ThrowIfNull(propbagHandle);
			return GetPropertyString(propbagHandle, (int)id, null, defaultValue);
		}

		public virtual string GetProperty(string propertyName, string defaultValue)
		{
			SpxExceptionThrower.ThrowIfNull(propbagHandle);
			return GetPropertyString(propbagHandle, -1, propertyName, defaultValue);
		}

		public virtual void SetProperty(PropertyId id, string value)
		{
			SpxExceptionThrower.ThrowIfNull(propbagHandle);
			IntPtr intPtr = Utf8StringMarshaler.MarshalManagedToNative(value);
			try
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_set_string(propbagHandle, (int)id, IntPtr.Zero, intPtr));
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
			}
		}

		public virtual void SetProperty(string propertyName, string value)
		{
			SpxExceptionThrower.ThrowIfNull(propbagHandle);
			IntPtr intPtr = Utf8StringMarshaler.MarshalManagedToNative(value);
			IntPtr intPtr2 = Utf8StringMarshaler.MarshalManagedToNative(propertyName);
			try
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_set_string(propbagHandle, -1, intPtr2, intPtr));
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
				Marshal.FreeHGlobal(intPtr2);
			}
		}

		private string GetPropertyString(InteropSafeHandle propHandle, int id, string name, string defaultValue)
		{
			string result = string.Empty;
			IntPtr intPtr = Utf8StringMarshaler.MarshalManagedToNative(name);
			IntPtr intPtr2 = Utf8StringMarshaler.MarshalManagedToNative(defaultValue);
			try
			{
				IntPtr intPtr3 = Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_get_string(propHandle, id, intPtr, intPtr2);
				if (intPtr3 != IntPtr.Zero)
				{
					try
					{
						result = Utf8StringMarshaler.MarshalNativeToManaged(intPtr3);
					}
					finally
					{
						SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.PropertyCollection.property_bag_free_string(intPtr3));
					}
				}
			}
			finally
			{
				Marshal.FreeHGlobal(intPtr);
				Marshal.FreeHGlobal(intPtr2);
			}
			return result;
		}
	}
	public enum PropertyId
	{
		SpeechServiceConnection_Key = 1000,
		SpeechServiceConnection_Endpoint = 1001,
		SpeechServiceConnection_Region = 1002,
		SpeechServiceAuthorization_Token = 1003,
		SpeechServiceAuthorization_Type = 1004,
		SpeechServiceConnection_EndpointId = 1005,
		SpeechServiceConnection_Host = 1006,
		SpeechServiceConnection_ProxyHostName = 1100,
		SpeechServiceConnection_ProxyPort = 1101,
		SpeechServiceConnection_ProxyUserName = 1102,
		SpeechServiceConnection_ProxyPassword = 1103,
		SpeechServiceConnection_Url = 1104,
		SpeechServiceConnection_ProxyHostBypass = 1105,
		SpeechServiceConnection_TranslationToLanguages = 2000,
		SpeechServiceConnection_TranslationVoice = 2001,
		SpeechServiceConnection_TranslationFeatures = 2002,
		SpeechServiceConnection_IntentRegion = 2003,
		SpeechServiceConnection_RecoMode = 3000,
		SpeechServiceConnection_RecoLanguage = 3001,
		SpeechServiceConnection_RecoBackend = 3004,
		SpeechServiceConnection_RecoModelName = 3005,
		[EditorBrowsable(EditorBrowsableState.Never)]
		SpeechServiceConnection_RecoModelKey = 3006,
		Speech_SessionId = 3002,
		SpeechServiceConnection_SynthLanguage = 3100,
		SpeechServiceConnection_SynthVoice = 3101,
		SpeechServiceConnection_SynthOutputFormat = 3102,
		SpeechServiceConnection_SynthEnableCompressedAudioTransmission = 3103,
		SpeechServiceConnection_SynthBackend = 3110,
		SpeechServiceConnection_SynthOfflineDataPath = 3112,
		SpeechServiceConnection_SynthOfflineVoice = 3113,
		[EditorBrowsable(EditorBrowsableState.Never)]
		SpeechServiceConnection_SynthModelKey = 3114,
		SpeechServiceConnection_VoicesListEndpoint = 3130,
		SpeechServiceConnection_InitialSilenceTimeoutMs = 3200,
		SpeechServiceConnection_EndSilenceTimeoutMs = 3201,
		SpeechServiceConnection_EnableAudioLogging = 3202,
		SpeechServiceConnection_AutoDetectSourceLanguages = 3300,
		SpeechServiceConnection_AutoDetectSourceLanguageResult = 3301,
		SpeechServiceConnection_LanguageIdMode = 3205,
		SpeechServiceConnection_TranslationCategoryId = 3206,
		SpeechServiceResponse_RequestDetailedResultTrueFalse = 4000,
		SpeechServiceResponse_RequestProfanityFilterTrueFalse = 4001,
		SpeechServiceResponse_ProfanityOption = 4002,
		SpeechServiceResponse_PostProcessingOption = 4003,
		SpeechServiceResponse_RequestWordLevelTimestamps = 4004,
		SpeechServiceResponse_StablePartialResultThreshold = 4005,
		SpeechServiceResponse_OutputFormatOption = 4006,
		SpeechServiceResponse_RequestSnr = 4007,
		SpeechServiceResponse_TranslationRequestStablePartialResult = 4100,
		SpeechServiceResponse_RequestWordBoundary = 4200,
		SpeechServiceResponse_RequestPunctuationBoundary = 4201,
		SpeechServiceResponse_RequestSentenceBoundary = 4202,
		SpeechServiceResponse_SynthesisEventsSyncToAudio = 4210,
		SpeechServiceResponse_JsonResult = 5000,
		SpeechServiceResponse_JsonErrorDetails = 5001,
		SpeechServiceResponse_RecognitionLatencyMs = 5002,
		SpeechServiceResponse_RecognitionBackend = 5003,
		SpeechServiceResponse_SynthesisFirstByteLatencyMs = 5010,
		SpeechServiceResponse_SynthesisFinishLatencyMs = 5011,
		SpeechServiceResponse_SynthesisUnderrunTimeMs = 5012,
		SpeechServiceResponse_SynthesisConnectionLatencyMs = 5013,
		SpeechServiceResponse_SynthesisNetworkLatencyMs = 5014,
		SpeechServiceResponse_SynthesisServiceLatencyMs = 5015,
		SpeechServiceResponse_SynthesisBackend = 5020,
		SpeechServiceResponse_DiarizeIntermediateResults = 5025,
		CancellationDetails_Reason = 6000,
		CancellationDetails_ReasonText = 6001,
		CancellationDetails_ReasonDetailedText = 6002,
		LanguageUnderstandingServiceResponse_JsonResult = 7000,
		AudioConfig_DeviceNameForRender = 8005,
		AudioConfig_PlaybackBufferLengthInMs = 8006,
		Speech_LogFilename = 9001,
		Speech_SegmentationSilenceTimeoutMs = 9002,
		Speech_SegmentationMaximumTimeMs = 9003,
		Speech_SegmentationStrategy = 9004,
		Conversation_ApplicationId = 10000,
		Conversation_DialogType = 10001,
		Conversation_Initial_Silence_Timeout = 10002,
		Conversation_From_Id = 10003,
		Conversation_Conversation_Id = 10004,
		Conversation_Custom_Voice_Deployment_Ids = 10005,
		Conversation_Speech_Activity_Template = 10006,
		Conversation_Request_Bot_Status_Messages = 10008,
		Conversation_Connection_Id = 10009,
		Conversation_ParticipantId = 10007,
		ConversationTranscribingService_DataBufferUserId = 11002,
		ConversationTranscribingService_DataBufferTimeStamp = 11001,
		PronunciationAssessment_ReferenceText = 12001,
		PronunciationAssessment_GradingSystem = 12002,
		PronunciationAssessment_Granularity = 12003,
		PronunciationAssessment_EnableMiscue = 12005,
		PronunciationAssessment_PhonemeAlphabet = 12006,
		PronunciationAssessment_NBestPhonemeCount = 12007,
		PronunciationAssessment_EnableProsodyAssessment = 12008,
		PronunciationAssessment_Json = 12009,
		PronunciationAssessment_Params = 12010,
		PronunciationAssessment_ContentTopic = 12020,
		SpeakerRecognition_Api_Version = 13001,
		SpeechTranslation_ModelName = 13100,
		[EditorBrowsable(EditorBrowsableState.Never)]
		SpeechTranslation_ModelKey = 13101,
		KeywordRecognition_ModelName = 13200,
		[EditorBrowsable(EditorBrowsableState.Never)]
		KeywordRecognition_ModelKey = 13201,
		EmbeddedSpeech_EnablePerformanceMetrics = 13300,
		SpeechSynthesisRequest_Pitch = 14001,
		SpeechSynthesisRequest_Rate = 14002,
		SpeechSynthesisRequest_Volume = 14003,
		SpeechSynthesis_FrameTimeoutInterval = 14101,
		SpeechSynthesis_RtfTimeoutThreshold = 14102
	}
	public enum ResultReason
	{
		NoMatch,
		Canceled,
		RecognizingSpeech,
		RecognizedSpeech,
		RecognizingIntent,
		RecognizedIntent,
		TranslatingSpeech,
		TranslatedSpeech,
		SynthesizingAudio,
		SynthesizingAudioCompleted,
		RecognizingKeyword,
		RecognizedKeyword,
		SynthesizingAudioStarted,
		TranslatingParticipantSpeech,
		TranslatedParticipantSpeech,
		TranslatedInstantMessage,
		TranslatedParticipantInstantMessage,
		EnrollingVoiceProfile,
		EnrolledVoiceProfile,
		RecognizedSpeakers,
		RecognizedSpeaker,
		ResetVoiceProfile,
		DeletedVoiceProfile,
		VoicesListRetrieved
	}
	public enum CancellationReason
	{
		Error = 1,
		EndOfStream,
		CancelledByUser
	}
	public enum CancellationErrorCode
	{
		NoError = 0,
		AuthenticationFailure = 1,
		BadRequest = 2,
		TooManyRequests = 3,
		Forbidden = 4,
		ConnectionFailure = 5,
		ServiceTimeout = 6,
		ServiceError = 7,
		ServiceUnavailable = 8,
		RuntimeError = 9,
		EmbeddedModelError = 12
	}
	public class RecognitionEventArgs : SessionEventArgs
	{
		public ulong Offset { get; }

		internal RecognitionEventArgs(IntPtr eventHandlePtr)
			: base(eventHandlePtr)
		{
			SpxExceptionThrower.ThrowIfNull(eventHandle);
			ulong offset = 0uL;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognition_event_get_offset(eventHandle, ref offset));
			Offset = offset;
		}

		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "SessionId: {0} Offset: {1}", base.SessionId, Offset);
		}
	}
	internal enum RecognitionEventType
	{
		SpeechStartDetectedEvent,
		SpeechEndDetectedEvent
	}
	public class RecognitionResult
	{
		internal InteropSafeHandle resultHandle;

		internal const int maxCharCount = 2048;

		public virtual string ResultId { get; }

		public virtual ResultReason Reason { get; }

		public virtual string Text { get; }

		public virtual TimeSpan Duration => TimeSpan.FromTicks((long)GetDuration());

		public virtual long OffsetInTicks => (long)GetOffset();

		public virtual int Channel => (int)GetChannel();

		public virtual PropertyCollection Properties { get; private set; }

		internal RecognitionResult(IntPtr resultHandlePtr)
		{
			if (resultHandlePtr != IntPtr.Zero)
			{
				resultHandle = new InteropSafeHandle(resultHandlePtr, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.recognizer_result_handle_release);
				ResultId = SpxFactory.GetDataFromHandleUsingDelegate(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_result_id, resultHandle, 2048);
				Text = SpxFactory.GetDataFromHandleUsingDelegate(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_text, resultHandle, 2048);
				ResultReason reason = ResultReason.NoMatch;
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_reason(resultHandle, ref reason));
				Reason = reason;
				IntPtr hpropbag = IntPtr.Zero;
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_property_bag(resultHandle, out hpropbag));
				Properties = new PropertyCollection(hpropbag);
			}
		}

		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "ResultId:{0} Reason:{1} Recognized text:<{2}>. Json:{3}", ResultId, Reason, Text, Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonResult));
		}

		private ulong GetDuration()
		{
			SpxExceptionThrower.ThrowIfNull(resultHandle);
			ulong duration = 0uL;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_duration(resultHandle, ref duration));
			return duration;
		}

		private ulong GetOffset()
		{
			SpxExceptionThrower.ThrowIfNull(resultHandle);
			ulong offset = 0uL;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_offset(resultHandle, ref offset));
			return offset;
		}

		private uint GetChannel()
		{
			SpxExceptionThrower.ThrowIfNull(resultHandle);
			uint channel = 0u;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.RecognitionResult.result_get_channel(resultHandle, ref channel));
			return channel;
		}
	}
	public class CancellationDetails
	{
		private RecognitionResult recognitionResult = null;

		public CancellationReason Reason { get; private set; }

		public CancellationErrorCode ErrorCode { get; private set; }

		public string ErrorDetails { get; private set; }

		public static CancellationDetails FromResult(RecognitionResult result)
		{
			return new CancellationDetails(result);
		}

		internal CancellationDetails(RecognitionResult result)
		{
			SpxExceptionThrower.ThrowIfNull(result);
			recognitionResult = result;
			SpxExceptionThrower.ThrowIfNull(recognitionResult.resultHandle, "Invalid result handle.");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.CancellationDetails.result_get_reason_canceled(recognitionResult.resultHandle, out var reason));
			Reason = reason;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.CancellationDetails.result_get_canceled_error_code(recognitionResult.resultHandle, out var errorCode));
			ErrorCode = errorCode;
			ErrorDetails = recognitionResult.Properties.GetProperty(PropertyId.SpeechServiceResponse_JsonErrorDetails);
		}

		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "Reason:{0} ErrorDetails:<{1}>", Reason, ErrorDetails);
		}
	}
	public class NoMatchDetails
	{
		private RecognitionResult recognitionResult = null;

		public NoMatchReason Reason { get; private set; }

		public static NoMatchDetails FromResult(RecognitionResult result)
		{
			return new NoMatchDetails(result);
		}

		internal NoMatchDetails(RecognitionResult result)
		{
			SpxExceptionThrower.ThrowIfNull(result);
			recognitionResult = result;
			SpxExceptionThrower.ThrowIfNull(recognitionResult.resultHandle, "Invalid result handle.");
			NoMatchReason reason = NoMatchReason.NotRecognized;
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.NoMatchDetails.result_get_no_match_reason(recognitionResult.resultHandle, ref reason));
			Reason = reason;
		}

		public override string ToString()
		{
			return string.Format(CultureInfo.InvariantCulture, "NoMatchReason:{0}", Reason);
		}
	}
	public class Recognizer : IDisposable
	{
		internal delegate IntPtr GetRecognizerFromConfigDelegate(out IntPtr phreco, InteropSafeHandle speechconfig, InteropSafeHandle audioInput);

		internal delegate IntPtr GetRecognizerFromConfigWithLanguageConfigDelegate(out IntPtr phreco, InteropSafeHandle speechconfig, InteropSafeHandle sourceLanguageConfig, InteropSafeHandle audioInput);

		internal delegate IntPtr GetRecognizerFromAudioConfigDelegate(out IntPtr reco, InteropSafeHandle audioConfig);

		private const string AuthTokenExpiryProperty = "service.auth.token.expirems";

		private const string AuthTokenErrorProperty = "service.auth.token.lasterror";

		private const string AuthTokenRefreshIntervalMsProperty = "service.auth.token.refreshintervalms";

		private static readonly string[] TokenRequestScopes = new string[1] { "https://cognitiveservices.azure.com/.default" };

		protected readonly TokenCredential _tokenCredential;

		internal InteropSafeHandle recoHandle;

		protected readonly string pointerHandle;

		private IntPtr asyncStartContinuousHandle = IntPtr.Zero;

		private IntPtr asyncStopContinuousHandle = IntPtr.Zero;

		private IntPtr asyncStartKeywordHandle = IntPtr.Zero;

		private IntPtr asyncStopKeywordHandle = IntPtr.Zero;

		private CallbackFunctionDelegate speechStartDetectedCallbackDelegate;

		private CallbackFunctionDelegate speechEndDetectedCallbackDelegate;

		private CallbackFunctionDelegate sessionStartedCallbackDelegate;

		private CallbackFunctionDelegate sessionStoppedCallbackDelegate;

		private CallbackFunctionDelegate tokenRequestedCallbackDelegate;

		protected GCHandle gch;

		protected volatile bool disposed = false;

		protected volatile bool isDisposing = false;

		protected object recognizerLock = new object();

		private int activeAsyncRecognitionCounter = 0;

		private event EventHandler<SessionEventArgs> _SessionStarted;

		private event EventHandler<SessionEventArgs> _SessionStopped;

		private event EventHandler<SessionEventArgs> _TokenRequested;

		private event EventHandler<RecognitionEventArgs> _SpeechStartDetected;

		private event EventHandler<RecognitionEventArgs> _SpeechEndDetected;

		public event EventHandler<SessionEventArgs> SessionStarted
		{
			add
			{
				if (this._SessionStarted == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_session_started_set_callback(recoHandle, sessionStartedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_SessionStarted += value;
			}
			remove
			{
				_SessionStarted -= value;
				if (this._SessionStarted == null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_session_started_set_callback(recoHandle, null, IntPtr.Zero));
				}
			}
		}

		public event EventHandler<SessionEventArgs> SessionStopped
		{
			add
			{
				if (this._SessionStopped == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_session_stopped_set_callback(recoHandle, sessionStoppedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_SessionStopped += value;
			}
			remove
			{
				_SessionStopped -= value;
				if (this._SessionStopped == null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_session_stopped_set_callback(recoHandle, null, IntPtr.Zero));
				}
			}
		}

		public event EventHandler<RecognitionEventArgs> SpeechStartDetected
		{
			add
			{
				if (this._SpeechStartDetected == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_speech_start_detected_set_callback(recoHandle, speechStartDetectedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_SpeechStartDetected += value;
			}
			remove
			{
				_SpeechStartDetected -= value;
				if (this._SpeechStartDetected == null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_speech_start_detected_set_callback(recoHandle, null, IntPtr.Zero));
				}
			}
		}

		public event EventHandler<RecognitionEventArgs> SpeechEndDetected
		{
			add
			{
				if (this._SpeechEndDetected == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_speech_end_detected_set_callback(recoHandle, speechEndDetectedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_SpeechEndDetected += value;
			}
			remove
			{
				_SpeechEndDetected -= value;
				if (this._SpeechEndDetected == null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_speech_end_detected_set_callback(recoHandle, null, IntPtr.Zero));
				}
			}
		}

		protected event EventHandler<SessionEventArgs> TokenRequested
		{
			add
			{
				if (this._TokenRequested == null)
				{
					SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_token_requested_set_callback(recoHandle, tokenRequestedCallbackDelegate, GCHandle.ToIntPtr(gch)));
				}
				_TokenRequested += value;
			}
			remove
			{
				_TokenRequested -= value;
				if (this._TokenRequested == null)
				{
					SpxExceptionThrower.LogErrorIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_token_requested_set_callback(recoHandle, null, IntPtr.Zero));
				}
			}
		}

		internal Recognizer(InteropSafeHandle recoPtr, TokenCredential tokenCredential = null)
		{
			SpxExceptionThrower.ThrowIfNull(recoPtr);
			recoHandle = recoPtr;
			pointerHandle = recoPtr.ToString();
			Microsoft.CognitiveServices.Speech.Internal.Diagnostics.SPX_TRACE_VERBOSE("Constructor for " + pointerHandle, 148, ".ctor", "D:\\a\\_work\\1\\s\\source\\bindings\\csharp\\recognizer.cs");
			_tokenCredential = tokenCredential;
			gch = GCHandle.Alloc(this, GCHandleType.Weak);
			speechStartDetectedCallbackDelegate = FireEvent_SpeechStartDetected;
			speechEndDetectedCallbackDelegate = FireEvent_SpeechEndDetected;
			sessionStartedCallbackDelegate = FireEvent_SetSessionStarted;
			sessionStoppedCallbackDelegate = FireEvent_SetSessionStopped;
			tokenRequestedCallbackDelegate = FireEvent_TokenRequested;
		}

		~Recognizer()
		{
			Microsoft.CognitiveServices.Speech.Internal.Diagnostics.SPX_TRACE_VERBOSE("Finalizer for " + pointerHandle, 161, "Finalize", "D:\\a\\_work\\1\\s\\source\\bindings\\csharp\\recognizer.cs");
			isDisposing = true;
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			try
			{
				isDisposing = true;
				lock (recognizerLock)
				{
					if (activeAsyncRecognitionCounter != 0)
					{
						throw new InvalidOperationException("Cannot dispose a recognizer while async recognition is running. Await async recognitions to avoid unexpected disposals.");
					}
				}
			}
			finally
			{
				Dispose(disposing: true);
				GC.SuppressFinalize(this);
			}
		}

		protected virtual void Dispose(bool disposing)
		{
			Microsoft.CognitiveServices.Speech.Internal.Diagnostics.SPX_TRACE_VERBOSE($"Dispose({disposing}) called for {pointerHandle}", 222, "Dispose", "D:\\a\\_work\\1\\s\\source\\bindings\\csharp\\recognizer.cs");
			if (!disposed)
			{
				speechStartDetectedCallbackDelegate = null;
				speechEndDetectedCallbackDelegate = null;
				sessionStartedCallbackDelegate = null;
				sessionStoppedCallbackDelegate = null;
				tokenRequestedCallbackDelegate = null;
				if (gch.IsAllocated)
				{
					gch.Free();
				}
				disposed = true;
			}
		}

		protected void SetUpTokenRefreshCallback(PropertyCollection property)
		{
			if (_tokenCredential != null && property != null && this._TokenRequested == null)
			{
				TokenRequested += delegate
				{
					UpdateAuthToken(property);
				};
				property.SetProperty("service.auth.token.expirems", "infinite");
			}
		}

		private void UpdateAuthToken(PropertyCollection property)
		{
			//IL_0061: 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_0075: Unknown result type (might be due to invalid IL or missing references)
			if (property == null || _tokenCredential == null)
			{
				return;
			}
			string value = property.GetProperty(PropertyId.SpeechServiceAuthorization_Token, string.Empty);
			string value2 = property.GetProperty("service.auth.token.expirems", string.Empty);
			string property2 = property.GetProperty("service.auth.token.refreshintervalms", string.Empty);
			try
			{
				AccessToken token = _tokenCredential.GetToken(new TokenRequestContext(TokenRequestScopes, (string)null, (string)null, (string)null, false, false, (string)null, (Uri)null, (string)null), default(CancellationToken));
				value = ((AccessToken)(ref token)).Token;
				value2 = ((!int.TryParse(property2, out var result)) ? $"{((AccessToken)(ref token)).ExpiresOn.ToUnixTimeMilliseconds()}" : $"{new DateTimeOffset(DateTime.UtcNow.AddMilliseconds(result * 2)).ToUnixTimeMilliseconds()}");
				property.SetProperty("service.auth.token.lasterror", string.Empty);
			}
			catch (Exception ex)
			{
				property.SetProperty("service.auth.token.lasterror", ex.ToString());
			}
			finally
			{
				property.SetProperty(PropertyId.SpeechServiceAuthorization_Token, value);
				property.SetProperty("service.auth.token.expirems", value2);
			}
		}

		[MonoPInvokeCallback(typeof(CallbackFunctionDelegate))]
		private static void FireEvent_SetSessionStarted(IntPtr hreco, IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					SessionEventArgs e = new SessionEventArgs(hevent);
					objectFromWeakHandle._SessionStarted?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}

		[MonoPInvokeCallback(typeof(CallbackFunctionDelegate))]
		private static void FireEvent_SetSessionStopped(IntPtr hreco, IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					SessionEventArgs e = new SessionEventArgs(hevent);
					objectFromWeakHandle._SessionStopped?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}

		[MonoPInvokeCallback(typeof(CallbackFunctionDelegate))]
		private static void FireEvent_TokenRequested(IntPtr hreco, IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					SessionEventArgs e = new SessionEventArgs(hevent);
					objectFromWeakHandle._TokenRequested?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}

		[MonoPInvokeCallback(typeof(CallbackFunctionDelegate))]
		private static void FireEvent_SpeechStartDetected(IntPtr hreco, IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					RecognitionEventArgs e = new RecognitionEventArgs(hevent);
					objectFromWeakHandle._SpeechStartDetected?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}

		[MonoPInvokeCallback(typeof(CallbackFunctionDelegate))]
		private static void FireEvent_SpeechEndDetected(IntPtr hreco, IntPtr hevent, IntPtr pvContext)
		{
			try
			{
				Recognizer objectFromWeakHandle = InteropSafeHandle.GetObjectFromWeakHandle<Recognizer>(pvContext);
				if (objectFromWeakHandle != null && !objectFromWeakHandle.isDisposing)
				{
					RecognitionEventArgs e = new RecognitionEventArgs(hevent);
					objectFromWeakHandle._SpeechEndDetected?.Invoke(objectFromWeakHandle, e);
				}
			}
			catch (Exception ex)
			{
				SpxExceptionThrower.LogError(ex.Message);
			}
		}

		internal void DoAsyncRecognitionAction(Action recoImplAction)
		{
			lock (recognizerLock)
			{
				activeAsyncRecognitionCounter++;
			}
			if (disposed || isDisposing)
			{
				throw new ObjectDisposedException(GetType().Name);
			}
			try
			{
				SpxExceptionThrower.ThrowIfNull(recoImplAction);
				recoImplAction();
			}
			finally
			{
				lock (recognizerLock)
				{
					activeAsyncRecognitionCounter--;
				}
			}
		}

		internal IntPtr RecognizeOnce()
		{
			IntPtr result = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_recognize_once(recoHandle, out result));
			return result;
		}

		internal void StartContinuousRecognition()
		{
			if (asyncStartContinuousHandle != IntPtr.Zero)
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStartContinuousHandle));
			}
			SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_start_continuous_recognition_async(recoHandle, out asyncStartContinuousHandle));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_start_continuous_recognition_async_wait_for(asyncStartContinuousHandle, uint.MaxValue));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStartContinuousHandle));
			asyncStartContinuousHandle = IntPtr.Zero;
		}

		internal void StopContinuousRecognition()
		{
			if (asyncStopContinuousHandle != IntPtr.Zero)
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopContinuousHandle));
			}
			SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_continuous_recognition_async(recoHandle, out asyncStopContinuousHandle));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_continuous_recognition_async_wait_for(asyncStopContinuousHandle, uint.MaxValue));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopContinuousHandle));
			asyncStopContinuousHandle = IntPtr.Zero;
		}

		internal void StopTranscribing(bool destroyResource)
		{
			if (asyncStopContinuousHandle != IntPtr.Zero)
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopContinuousHandle));
			}
			SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_continuous_recognition_async(recoHandle, out asyncStopContinuousHandle));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_continuous_recognition_async_wait_for(asyncStopContinuousHandle, uint.MaxValue));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopContinuousHandle));
			asyncStopContinuousHandle = IntPtr.Zero;
		}

		internal void StartKeywordRecognition(KeywordRecognitionModel model)
		{
			if (asyncStartKeywordHandle != IntPtr.Zero)
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStartKeywordHandle));
			}
			SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_start_keyword_recognition_async(recoHandle, model.keywordHandle, out asyncStartKeywordHandle));
			GC.KeepAlive(model);
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_start_keyword_recognition_async_wait_for(asyncStartKeywordHandle, uint.MaxValue));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStartKeywordHandle));
			asyncStartKeywordHandle = IntPtr.Zero;
		}

		internal void StopKeywordRecognition()
		{
			if (asyncStopKeywordHandle != IntPtr.Zero)
			{
				SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopKeywordHandle));
			}
			SpxExceptionThrower.ThrowIfNull(recoHandle, "Invalid recognizer handle");
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_keyword_recognition_async(recoHandle, out asyncStopKeywordHandle));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_stop_keyword_recognition_async_wait_for(asyncStopKeywordHandle, uint.MaxValue));
			SpxExceptionThrower.ThrowIfFail(Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_async_handle_release(asyncStopKeywordHandle));
			asyncStopKeywordHandle = IntPtr.Zero;
		}

		internal static InteropSafeHandle FromConfig(GetRecognizerFromConfigDelegate fromConfig, SpeechConfig speechConfig, Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig)
		{
			if (speechConfig == null)
			{
				throw new ArgumentNullException("speechConfig");
			}
			if (audioConfig == null)
			{
				throw new ArgumentNullException("audioConfig");
			}
			IntPtr phreco = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioConfig.configHandle));
			InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release);
			GC.KeepAlive(speechConfig);
			GC.KeepAlive(audioConfig);
			return result;
		}

		internal static InteropSafeHandle FromEmbeddedConfig(GetRecognizerFromConfigDelegate fromConfig, EmbeddedSpeechConfig speechConfig, Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig)
		{
			if (speechConfig == null)
			{
				throw new ArgumentNullException("speechConfig");
			}
			if (audioConfig == null)
			{
				throw new ArgumentNullException("audioConfig");
			}
			IntPtr phreco = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioConfig.configHandle));
			InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release);
			GC.KeepAlive(speechConfig);
			GC.KeepAlive(audioConfig);
			return result;
		}

		internal static InteropSafeHandle FromHybridConfig(GetRecognizerFromConfigDelegate fromConfig, HybridSpeechConfig speechConfig, Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig)
		{
			if (speechConfig == null)
			{
				throw new ArgumentNullException("speechConfig");
			}
			if (audioConfig == null)
			{
				throw new ArgumentNullException("audioConfig");
			}
			IntPtr phreco = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioConfig.configHandle));
			InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release);
			GC.KeepAlive(speechConfig);
			GC.KeepAlive(audioConfig);
			return result;
		}

		internal static InteropSafeHandle FromConfig(GetRecognizerFromConfigDelegate fromConfig, SpeechConfig speechConfig)
		{
			if (speechConfig == null)
			{
				throw new ArgumentNullException("speechConfig");
			}
			IntPtr zero = IntPtr.Zero;
			using InteropSafeHandle audioInput = new InteropSafeHandle(zero, (HandleRelease)null);
			IntPtr phreco = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioInput));
			InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release);
			GC.KeepAlive(speechConfig);
			return result;
		}

		internal static InteropSafeHandle FromEmbeddedConfig(GetRecognizerFromConfigDelegate fromConfig, EmbeddedSpeechConfig speechConfig)
		{
			if (speechConfig == null)
			{
				throw new ArgumentNullException("speechConfig");
			}
			IntPtr zero = IntPtr.Zero;
			using InteropSafeHandle audioInput = new InteropSafeHandle(zero, (HandleRelease)null);
			IntPtr phreco = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioInput));
			InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release);
			GC.KeepAlive(speechConfig);
			return result;
		}

		internal static InteropSafeHandle FromHybridConfig(GetRecognizerFromConfigDelegate fromConfig, HybridSpeechConfig speechConfig)
		{
			if (speechConfig == null)
			{
				throw new ArgumentNullException("speechConfig");
			}
			IntPtr zero = IntPtr.Zero;
			using InteropSafeHandle audioInput = new InteropSafeHandle(zero, (HandleRelease)null);
			IntPtr phreco = IntPtr.Zero;
			SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, audioInput));
			InteropSafeHandle result = new InteropSafeHandle(phreco, (HandleRelease)Microsoft.CognitiveServices.Speech.Internal.Recognizer.recognizer_handle_release);
			GC.KeepAlive(speechConfig);
			return result;
		}

		internal static InteropSafeHandle FromConfig(GetRecognizerFromConfigWithLanguageConfigDelegate fromConfig, SpeechConfig speechConfig, SourceLanguageConfig sourceLanguageConfig, Microsoft.CognitiveServices.Speech.Audio.AudioConfig audioConfig)
		{
			if (speechConfig == null)
			{
				throw new ArgumentNullException("speechConfig");
			}
			if (sourceLanguageConfig == null)
			{
				throw new ArgumentNullException("sourceLanguageConfig");
			}
			IntPtr phreco = IntPtr.Zero;
			InteropSafeHandle audioConfigHandle = getAudioConfigHandle(audioConfig);
			SpxExceptionThrower.ThrowIfFail(fromConfig(out phreco, speechConfig.configHandle, sourceLanguageConfig.configHandle, audioConfigHandle));
			InteropSafeHandle

BepInEx/core/Microsoft.Extensions.AI.Abstractions.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Schema;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Shared.Collections;
using Microsoft.Shared.Diagnostics;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Abstractions representing generative AI components.")]
[assembly: AssemblyFileVersion("10.100.125.61202")]
[assembly: AssemblyInformationalVersion("10.1.1+8a57aae6b42651573f06fd3904b9a0d1023f9aeb")]
[assembly: AssemblyProduct("Microsoft.Extensions.AI.Abstractions")]
[assembly: AssemblyTitle("Microsoft.Extensions.AI.Abstractions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/extensions")]
[assembly: AssemblyVersion("10.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Microsoft.Extensions.AI
{
	public sealed class AdditionalPropertiesDictionary : AdditionalPropertiesDictionary<object?>
	{
		public AdditionalPropertiesDictionary()
		{
		}

		public AdditionalPropertiesDictionary(IDictionary<string, object?> dictionary)
			: base(dictionary)
		{
		}

		public AdditionalPropertiesDictionary(IEnumerable<KeyValuePair<string, object?>> collection)
			: base(collection)
		{
		}

		public new AdditionalPropertiesDictionary Clone()
		{
			return new AdditionalPropertiesDictionary(this);
		}
	}
	[DebuggerDisplay("Count = {Count}")]
	[DebuggerTypeProxy(typeof(AdditionalPropertiesDictionary<>.DebugView))]
	public class AdditionalPropertiesDictionary<TValue> : IDictionary<string, TValue>, ICollection<KeyValuePair<string, TValue>>, IEnumerable<KeyValuePair<string, TValue>>, IEnumerable, IReadOnlyDictionary<string, TValue>, IReadOnlyCollection<KeyValuePair<string, TValue>>
	{
		public struct Enumerator : IEnumerator<KeyValuePair<string, TValue>>, IEnumerator, IDisposable
		{
			private Dictionary<string, TValue>.Enumerator _dictionaryEnumerator;

			public KeyValuePair<string, TValue> Current => _dictionaryEnumerator.Current;

			object IEnumerator.Current => Current;

			internal Enumerator(Dictionary<string, TValue>.Enumerator dictionaryEnumerator)
			{
				_dictionaryEnumerator = dictionaryEnumerator;
			}

			public void Dispose()
			{
				_dictionaryEnumerator.Dispose();
			}

			public bool MoveNext()
			{
				return _dictionaryEnumerator.MoveNext();
			}

			public void Reset()
			{
				Reset(ref _dictionaryEnumerator);
			}

			private static void Reset<TEnumerator>(ref TEnumerator enumerator) where TEnumerator : struct, IEnumerator
			{
				enumerator.Reset();
			}
		}

		private sealed class DebugView
		{
			[DebuggerDisplay("{Value}", Name = "[{Key}]")]
			public readonly struct AdditionalProperty
			{
				[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
				public string Key { get; }

				[DebuggerBrowsable(DebuggerBrowsableState.Collapsed)]
				public TValue Value { get; }

				public AdditionalProperty(string key, TValue value)
				{
					Key = key;
					Value = value;
				}
			}

			private readonly AdditionalPropertiesDictionary<TValue> _properties = Throw.IfNull(properties, "properties");

			[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
			public AdditionalProperty[] Items => _properties.Select<KeyValuePair<string, TValue>, AdditionalProperty>(delegate(KeyValuePair<string, TValue> p)
			{
				KeyValuePair<string, TValue> keyValuePair = p;
				string key = keyValuePair.Key;
				keyValuePair = p;
				return new AdditionalProperty(key, keyValuePair.Value);
			}).ToArray();

			public DebugView(AdditionalPropertiesDictionary<TValue> properties)
			{
			}
		}

		private readonly Dictionary<string, TValue> _dictionary;

		public TValue this[string key]
		{
			get
			{
				return _dictionary[key];
			}
			set
			{
				_dictionary[key] = value;
			}
		}

		public ICollection<string> Keys => _dictionary.Keys;

		public ICollection<TValue> Values => _dictionary.Values;

		public int Count => _dictionary.Count;

		bool ICollection<KeyValuePair<string, TValue>>.IsReadOnly => false;

		IEnumerable<string> IReadOnlyDictionary<string, TValue>.Keys => _dictionary.Keys;

		IEnumerable<TValue> IReadOnlyDictionary<string, TValue>.Values => _dictionary.Values;

		public AdditionalPropertiesDictionary()
		{
			_dictionary = new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase);
		}

		public AdditionalPropertiesDictionary(IDictionary<string, TValue> dictionary)
		{
			_dictionary = new Dictionary<string, TValue>(dictionary, StringComparer.OrdinalIgnoreCase);
		}

		public AdditionalPropertiesDictionary(IEnumerable<KeyValuePair<string, TValue>> collection)
		{
			_dictionary = new Dictionary<string, TValue>(StringComparer.OrdinalIgnoreCase);
			foreach (KeyValuePair<string, TValue> item in collection)
			{
				_dictionary.Add(item.Key, item.Value);
			}
		}

		public AdditionalPropertiesDictionary<TValue> Clone()
		{
			return new AdditionalPropertiesDictionary<TValue>(_dictionary);
		}

		public void Add(string key, TValue value)
		{
			_dictionary.Add(key, value);
		}

		public bool TryAdd(string key, TValue value)
		{
			if (!_dictionary.ContainsKey(key))
			{
				_dictionary.Add(key, value);
				return true;
			}
			return false;
		}

		void ICollection<KeyValuePair<string, TValue>>.Add(KeyValuePair<string, TValue> item)
		{
			((ICollection<KeyValuePair<string, TValue>>)_dictionary).Add(item);
		}

		public void Clear()
		{
			_dictionary.Clear();
		}

		bool ICollection<KeyValuePair<string, TValue>>.Contains(KeyValuePair<string, TValue> item)
		{
			return ((ICollection<KeyValuePair<string, TValue>>)_dictionary).Contains(item);
		}

		public bool ContainsKey(string key)
		{
			return _dictionary.ContainsKey(key);
		}

		void ICollection<KeyValuePair<string, TValue>>.CopyTo(KeyValuePair<string, TValue>[] array, int arrayIndex)
		{
			((ICollection<KeyValuePair<string, TValue>>)_dictionary).CopyTo(array, arrayIndex);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(_dictionary.GetEnumerator());
		}

		IEnumerator<KeyValuePair<string, TValue>> IEnumerable<KeyValuePair<string, TValue>>.GetEnumerator()
		{
			return GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public bool Remove(string key)
		{
			return _dictionary.Remove(key);
		}

		bool ICollection<KeyValuePair<string, TValue>>.Remove(KeyValuePair<string, TValue> item)
		{
			return ((ICollection<KeyValuePair<string, TValue>>)_dictionary).Remove(item);
		}

		public bool TryGetValue<T>(string key, [NotNullWhen(true)] out T? value)
		{
			if (TryGetValue(key, out var value2))
			{
				if (value2 is T)
				{
					object obj = value2;
					T val = (T)((obj is T) ? obj : null);
					value = val;
					return true;
				}
				if (value2 is IConvertible)
				{
					try
					{
						value = (T)Convert.ChangeType(value2, typeof(T), CultureInfo.InvariantCulture);
						return true;
					}
					catch (Exception ex) when (((ex is ArgumentException || ex is FormatException || ex is InvalidCastException || ex is OverflowException) ? 1 : 0) != 0)
					{
					}
				}
			}
			value = default(T);
			return false;
		}

		public bool TryGetValue(string key, [MaybeNullWhen(false)] out TValue value)
		{
			return _dictionary.TryGetValue(key, out value);
		}

		bool IDictionary<string, TValue>.TryGetValue(string key, out TValue value)
		{
			return _dictionary.TryGetValue(key, out value);
		}

		bool IReadOnlyDictionary<string, TValue>.TryGetValue(string key, out TValue value)
		{
			return _dictionary.TryGetValue(key, out value);
		}

		internal void SetAll(IEnumerable<KeyValuePair<string, TValue>> items)
		{
			Throw.IfNull(items, "items");
			foreach (KeyValuePair<string, TValue> item in items)
			{
				_dictionary[item.Key] = item.Value;
			}
		}
	}
	[DebuggerDisplay("Auto")]
	public sealed class AutoChatToolMode : ChatToolMode
	{
		public override bool Equals(object? obj)
		{
			return obj is AutoChatToolMode;
		}

		public override int GetHashCode()
		{
			return typeof(AutoChatToolMode).GetHashCode();
		}
	}
	public static class ChatClientExtensions
	{
		public static TService? GetService<TService>(this IChatClient client, object? serviceKey = null)
		{
			Throw.IfNull(client, "client");
			object service = client.GetService(typeof(TService), serviceKey);
			if (service is TService)
			{
				return (TService)service;
			}
			return default(TService);
		}

		public static object GetRequiredService(this IChatClient client, Type serviceType, object? serviceKey = null)
		{
			Throw.IfNull(client, "client");
			Throw.IfNull(serviceType, "serviceType");
			return client.GetService(serviceType, serviceKey) ?? throw Throw.CreateMissingServiceException(serviceType, serviceKey);
		}

		public static TService GetRequiredService<TService>(this IChatClient client, object? serviceKey = null)
		{
			Throw.IfNull(client, "client");
			object service = client.GetService(typeof(TService), serviceKey);
			if (service is TService)
			{
				return (TService)service;
			}
			throw Throw.CreateMissingServiceException(typeof(TService), serviceKey);
		}

		public static Task<ChatResponse> GetResponseAsync(this IChatClient client, string chatMessage, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(client, "client");
			Throw.IfNull(chatMessage, "chatMessage");
			return client.GetResponseAsync(new ChatMessage(ChatRole.User, chatMessage), options, cancellationToken);
		}

		public static Task<ChatResponse> GetResponseAsync(this IChatClient client, ChatMessage chatMessage, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(client, "client");
			Throw.IfNull(chatMessage, "chatMessage");
			return client.GetResponseAsync(new <>z__ReadOnlySingleElementList<ChatMessage>(chatMessage), options, cancellationToken);
		}

		public static IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(this IChatClient client, string chatMessage, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(client, "client");
			Throw.IfNull(chatMessage, "chatMessage");
			return client.GetStreamingResponseAsync(new ChatMessage(ChatRole.User, chatMessage), options, cancellationToken);
		}

		public static IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(this IChatClient client, ChatMessage chatMessage, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(client, "client");
			Throw.IfNull(chatMessage, "chatMessage");
			return client.GetStreamingResponseAsync(new <>z__ReadOnlySingleElementList<ChatMessage>(chatMessage), options, cancellationToken);
		}
	}
	public class ChatClientMetadata
	{
		public string? ProviderName { get; }

		public Uri? ProviderUri { get; }

		public string? DefaultModelId { get; }

		public ChatClientMetadata(string? providerName = null, Uri? providerUri = null, string? defaultModelId = null)
		{
			DefaultModelId = defaultModelId;
			ProviderName = providerName;
			ProviderUri = providerUri;
		}
	}
	[JsonConverter(typeof(Converter))]
	public readonly struct ChatFinishReason : IEquatable<ChatFinishReason>
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public sealed class Converter : JsonConverter<ChatFinishReason>
		{
			public override ChatFinishReason Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				return new ChatFinishReason(reader.GetString());
			}

			public override void Write(Utf8JsonWriter writer, ChatFinishReason value, JsonSerializerOptions options)
			{
				Throw.IfNull(writer, "writer").WriteStringValue(value.Value);
			}
		}

		[CompilerGenerated]
		private readonly string <Value>k__BackingField;

		public string Value => <Value>k__BackingField ?? Stop.Value;

		public static ChatFinishReason Stop { get; } = new ChatFinishReason("stop");


		public static ChatFinishReason Length { get; } = new ChatFinishReason("length");


		public static ChatFinishReason ToolCalls { get; } = new ChatFinishReason("tool_calls");


		public static ChatFinishReason ContentFilter { get; } = new ChatFinishReason("content_filter");


		[JsonConstructor]
		public ChatFinishReason(string value)
		{
			<Value>k__BackingField = Throw.IfNullOrWhitespace(value, "value");
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ChatFinishReason other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(ChatFinishReason other)
		{
			return StringComparer.OrdinalIgnoreCase.Equals(Value, other.Value);
		}

		public override int GetHashCode()
		{
			return StringComparer.OrdinalIgnoreCase.GetHashCode(Value);
		}

		public static bool operator ==(ChatFinishReason left, ChatFinishReason right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ChatFinishReason left, ChatFinishReason right)
		{
			return !(left == right);
		}

		public override string ToString()
		{
			return Value;
		}
	}
	[DebuggerDisplay("[{Role}] {ContentForDebuggerDisplay}{EllipsesForDebuggerDisplay,nq}")]
	public class ChatMessage
	{
		private IList<AIContent>? _contents;

		private string? _authorName;

		public string? AuthorName
		{
			get
			{
				return _authorName;
			}
			set
			{
				_authorName = (string.IsNullOrWhiteSpace(value) ? null : value);
			}
		}

		public DateTimeOffset? CreatedAt { get; set; }

		public ChatRole Role { get; set; } = ChatRole.User;


		[JsonIgnore]
		public string Text => Contents.ConcatText();

		public IList<AIContent> Contents
		{
			get
			{
				return _contents ?? (_contents = new List<AIContent>());
			}
			[param: AllowNull]
			set
			{
				_contents = value;
			}
		}

		public string? MessageId { get; set; }

		[JsonIgnore]
		public object? RawRepresentation { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AIContent? ContentForDebuggerDisplay
		{
			get
			{
				string text = Text;
				if (string.IsNullOrWhiteSpace(text))
				{
					IList<AIContent> contents = _contents;
					if (contents == null || contents.Count <= 0)
					{
						return null;
					}
					return _contents[0];
				}
				return new TextContent(text);
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string EllipsesForDebuggerDisplay
		{
			get
			{
				IList<AIContent> contents = _contents;
				if (contents == null || contents.Count <= 1)
				{
					return string.Empty;
				}
				return ", ...";
			}
		}

		[JsonConstructor]
		public ChatMessage()
		{
		}

		public ChatMessage(ChatRole role, string? content)
			: this(role, (content == null) ? new List<AIContent>() : new List<AIContent>(1)
			{
				new TextContent(content)
			})
		{
		}

		public ChatMessage(ChatRole role, IList<AIContent>? contents)
		{
			Role = role;
			_contents = contents;
		}

		public ChatMessage Clone()
		{
			return new ChatMessage
			{
				AdditionalProperties = AdditionalProperties,
				_authorName = _authorName,
				_contents = _contents,
				CreatedAt = CreatedAt,
				RawRepresentation = RawRepresentation,
				Role = Role,
				MessageId = MessageId
			};
		}

		public override string ToString()
		{
			return Text;
		}
	}
	public class ChatOptions
	{
		public string? ConversationId { get; set; }

		public string? Instructions { get; set; }

		public float? Temperature { get; set; }

		public int? MaxOutputTokens { get; set; }

		public float? TopP { get; set; }

		public int? TopK { get; set; }

		public float? FrequencyPenalty { get; set; }

		public float? PresencePenalty { get; set; }

		public long? Seed { get; set; }

		public ChatResponseFormat? ResponseFormat { get; set; }

		public string? ModelId { get; set; }

		public IList<string>? StopSequences { get; set; }

		public bool? AllowMultipleToolCalls { get; set; }

		public ChatToolMode? ToolMode { get; set; }

		[JsonIgnore]
		public IList<AITool>? Tools { get; set; }

		[Experimental("MEAI001")]
		[JsonIgnore]
		public bool? AllowBackgroundResponses { get; set; }

		[Experimental("MEAI001")]
		[JsonIgnore]
		public ResponseContinuationToken? ContinuationToken { get; set; }

		[JsonIgnore]
		public Func<IChatClient, object?>? RawRepresentationFactory { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }

		public ChatOptions()
		{
		}

		protected ChatOptions(ChatOptions? other)
		{
			if (other != null)
			{
				AdditionalProperties = other.AdditionalProperties?.Clone();
				AllowBackgroundResponses = other.AllowBackgroundResponses;
				AllowMultipleToolCalls = other.AllowMultipleToolCalls;
				ConversationId = other.ConversationId;
				ContinuationToken = other.ContinuationToken;
				FrequencyPenalty = other.FrequencyPenalty;
				Instructions = other.Instructions;
				MaxOutputTokens = other.MaxOutputTokens;
				ModelId = other.ModelId;
				PresencePenalty = other.PresencePenalty;
				RawRepresentationFactory = other.RawRepresentationFactory;
				ResponseFormat = other.ResponseFormat;
				Seed = other.Seed;
				Temperature = other.Temperature;
				ToolMode = other.ToolMode;
				TopK = other.TopK;
				TopP = other.TopP;
				if (other.StopSequences != null)
				{
					IList<string> stopSequences = other.StopSequences;
					List<string> list = new List<string>(stopSequences.Count);
					list.AddRange(stopSequences);
					StopSequences = list;
				}
				if (other.Tools != null)
				{
					IList<AITool> tools = other.Tools;
					List<AITool> list2 = new List<AITool>(tools.Count);
					list2.AddRange(tools);
					Tools = list2;
				}
			}
		}

		public virtual ChatOptions Clone()
		{
			return new ChatOptions(this);
		}
	}
	public class ChatResponse
	{
		private IList<ChatMessage>? _messages;

		public IList<ChatMessage> Messages
		{
			get
			{
				return _messages ?? (_messages = new List<ChatMessage>(1));
			}
			[param: AllowNull]
			set
			{
				_messages = value;
			}
		}

		[JsonIgnore]
		public string Text => _messages?.ConcatText() ?? string.Empty;

		public string? ResponseId { get; set; }

		public string? ConversationId { get; set; }

		public string? ModelId { get; set; }

		public DateTimeOffset? CreatedAt { get; set; }

		public ChatFinishReason? FinishReason { get; set; }

		public UsageDetails? Usage { get; set; }

		[Experimental("MEAI001")]
		[JsonIgnore]
		public ResponseContinuationToken? ContinuationToken { get; set; }

		[JsonIgnore]
		public object? RawRepresentation { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }

		public ChatResponse()
		{
		}

		public ChatResponse(ChatMessage message)
		{
			Throw.IfNull(message, "message");
			Messages.Add(message);
		}

		public ChatResponse(IList<ChatMessage>? messages)
		{
			_messages = messages;
		}

		public override string ToString()
		{
			return Text;
		}

		public ChatResponseUpdate[] ToChatResponseUpdates()
		{
			ChatResponseUpdate chatResponseUpdate = null;
			if (AdditionalProperties != null || Usage != null)
			{
				chatResponseUpdate = new ChatResponseUpdate
				{
					AdditionalProperties = AdditionalProperties
				};
				UsageDetails usage = Usage;
				if (usage != null)
				{
					chatResponseUpdate.Contents.Add(new UsageContent(usage));
				}
			}
			int num = _messages?.Count ?? 0;
			ChatResponseUpdate[] array = new ChatResponseUpdate[num + ((chatResponseUpdate != null) ? 1 : 0)];
			int i;
			for (i = 0; i < num; i++)
			{
				ChatMessage chatMessage = _messages[i];
				array[i] = new ChatResponseUpdate
				{
					AdditionalProperties = chatMessage.AdditionalProperties,
					AuthorName = chatMessage.AuthorName,
					Contents = chatMessage.Contents,
					MessageId = chatMessage.MessageId,
					RawRepresentation = chatMessage.RawRepresentation,
					Role = chatMessage.Role,
					ConversationId = ConversationId,
					FinishReason = FinishReason,
					ModelId = ModelId,
					ResponseId = ResponseId,
					CreatedAt = (chatMessage.CreatedAt ?? CreatedAt),
					ContinuationToken = ContinuationToken
				};
			}
			if (chatResponseUpdate != null)
			{
				array[i] = chatResponseUpdate;
			}
			return array;
		}
	}
	public static class ChatResponseExtensions
	{
		public static void AddMessages(this IList<ChatMessage> list, ChatResponse response)
		{
			Throw.IfNull(list, "list");
			Throw.IfNull(response, "response");
			if (list is List<ChatMessage> list2)
			{
				list2.AddRange(response.Messages);
				return;
			}
			foreach (ChatMessage message in response.Messages)
			{
				list.Add(message);
			}
		}

		public static void AddMessages(this IList<ChatMessage> list, IEnumerable<ChatResponseUpdate> updates)
		{
			Throw.IfNull(list, "list");
			Throw.IfNull(updates, "updates");
			if (!(updates is ICollection<ChatResponseUpdate> collection) || collection.Count != 0)
			{
				list.AddMessages(updates.ToChatResponse());
			}
		}

		public static void AddMessages(this IList<ChatMessage> list, ChatResponseUpdate update, Func<AIContent, bool>? filter = null)
		{
			Throw.IfNull(list, "list");
			Throw.IfNull(update, "update");
			IList<AIContent> list3;
			if (filter != null)
			{
				IList<AIContent> list2 = update.Contents.Where(filter).ToList();
				list3 = list2;
			}
			else
			{
				list3 = update.Contents;
			}
			IList<AIContent> list4 = list3;
			if (list4.Count > 0)
			{
				list.Add(new ChatMessage(update.Role ?? ChatRole.Assistant, list4)
				{
					AuthorName = update.AuthorName,
					CreatedAt = update.CreatedAt,
					RawRepresentation = update.RawRepresentation,
					AdditionalProperties = update.AdditionalProperties
				});
			}
		}

		public static Task AddMessagesAsync(this IList<ChatMessage> list, IAsyncEnumerable<ChatResponseUpdate> updates, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(list, "list");
			Throw.IfNull(updates, "updates");
			return AddMessagesAsync(list, updates, cancellationToken);
			static async Task AddMessagesAsync(IList<ChatMessage> list, IAsyncEnumerable<ChatResponseUpdate> updates, CancellationToken cancellationToken)
			{
				list.AddMessages(await updates.ToChatResponseAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
			}
		}

		public static ChatResponse ToChatResponse(this IEnumerable<ChatResponseUpdate> updates)
		{
			Throw.IfNull(updates, "updates");
			ChatResponse chatResponse = new ChatResponse();
			foreach (ChatResponseUpdate update in updates)
			{
				ProcessUpdate(update, chatResponse);
			}
			FinalizeResponse(chatResponse);
			return chatResponse;
		}

		public static Task<ChatResponse> ToChatResponseAsync(this IAsyncEnumerable<ChatResponseUpdate> updates, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(updates, "updates");
			return ToChatResponseAsync(updates, cancellationToken);
			static async Task<ChatResponse> ToChatResponseAsync(IAsyncEnumerable<ChatResponseUpdate> updates, CancellationToken cancellationToken)
			{
				ChatResponse response = new ChatResponse();
				await foreach (ChatResponseUpdate item in updates.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					ProcessUpdate(item, response);
				}
				FinalizeResponse(response);
				return response;
			}
		}

		private static void CoalesceImageResultContent(IList<AIContent> contents)
		{
			Dictionary<string, int> dictionary = null;
			bool flag = false;
			for (int i = 0; i < contents.Count; i++)
			{
				if (contents[i] is ImageGenerationToolResultContent imageGenerationToolResultContent && !string.IsNullOrEmpty(imageGenerationToolResultContent.ImageId))
				{
					if (dictionary == null)
					{
						dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
					}
					if (dictionary.TryGetValue(imageGenerationToolResultContent.ImageId, out var value))
					{
						contents[value] = imageGenerationToolResultContent;
						contents[i] = null;
						flag = true;
					}
					else
					{
						dictionary[imageGenerationToolResultContent.ImageId] = i;
					}
				}
			}
			if (flag)
			{
				RemoveNullContents(contents);
			}
		}

		internal static void CoalesceContent(IList<AIContent> contents)
		{
			Coalesce<TextContent>(contents, mergeSingle: false, null, (IList<AIContent> contents, int start, int end) => new TextContent(MergeText(contents, start, end))
			{
				AdditionalProperties = contents[start].AdditionalProperties?.Clone()
			});
			Coalesce<TextReasoningContent>(contents, mergeSingle: false, (TextReasoningContent r1, TextReasoningContent r2) => string.IsNullOrEmpty(r1.ProtectedData), delegate(IList<AIContent> contents, int start, int end)
			{
				TextReasoningContent textReasoningContent = new TextReasoningContent(MergeText(contents, start, end))
				{
					AdditionalProperties = contents[start].AdditionalProperties?.Clone()
				};
				string protectedData = ((TextReasoningContent)contents[end - 1]).ProtectedData;
				if (protectedData != null)
				{
					textReasoningContent.ProtectedData = protectedData;
				}
				return textReasoningContent;
			});
			CoalesceImageResultContent(contents);
			Coalesce<DataContent>(contents, mergeSingle: false, (DataContent r1, DataContent r2) => r1.MediaType == r2.MediaType && r1.HasTopLevelMediaType("text") && r1.Name == r2.Name, delegate(IList<AIContent> contents, int start, int end)
			{
				MemoryStream memoryStream = new MemoryStream();
				for (int l = start; l < end; l++)
				{
					DataContent dataContent = (DataContent)contents[l];
					if (!MemoryMarshal.TryGetArray(dataContent.Data, out var segment))
					{
						segment = new ArraySegment<byte>(dataContent.Data.ToArray());
					}
					memoryStream.Write(segment.Array, segment.Offset, segment.Count);
				}
				DataContent dataContent2 = (DataContent)contents[start];
				return new DataContent(new ReadOnlyMemory<byte>(memoryStream.GetBuffer(), 0, (int)memoryStream.Length), dataContent2.MediaType)
				{
					Name = dataContent2.Name
				};
			});
			Coalesce<CodeInterpreterToolCallContent>(contents, mergeSingle: true, (CodeInterpreterToolCallContent r1, CodeInterpreterToolCallContent r2) => r1.CallId == r2.CallId, delegate(IList<AIContent> contents, int start, int end)
			{
				CodeInterpreterToolCallContent codeInterpreterToolCallContent = (CodeInterpreterToolCallContent)contents[start];
				if (start == end - 1)
				{
					if (codeInterpreterToolCallContent.Inputs != null)
					{
						CoalesceContent(codeInterpreterToolCallContent.Inputs);
					}
					return codeInterpreterToolCallContent;
				}
				List<AIContent> list2 = null;
				for (int k = start; k < end; k++)
				{
					(list2 ?? (list2 = new List<AIContent>())).AddRange(((CodeInterpreterToolCallContent)contents[k]).Inputs ?? new List<AIContent>());
				}
				if (list2 != null)
				{
					CoalesceContent(list2);
				}
				return new CodeInterpreterToolCallContent
				{
					CallId = codeInterpreterToolCallContent.CallId,
					Inputs = list2,
					AdditionalProperties = codeInterpreterToolCallContent.AdditionalProperties?.Clone()
				};
			});
			Coalesce<CodeInterpreterToolResultContent>(contents, mergeSingle: true, (CodeInterpreterToolResultContent r1, CodeInterpreterToolResultContent r2) => r1.CallId != null && r2.CallId != null && r1.CallId == r2.CallId, delegate(IList<AIContent> contents, int start, int end)
			{
				CodeInterpreterToolResultContent codeInterpreterToolResultContent = (CodeInterpreterToolResultContent)contents[start];
				if (start == end - 1)
				{
					if (codeInterpreterToolResultContent.Outputs != null)
					{
						CoalesceContent(codeInterpreterToolResultContent.Outputs);
					}
					return codeInterpreterToolResultContent;
				}
				List<AIContent> list = null;
				for (int j = start; j < end; j++)
				{
					(list ?? (list = new List<AIContent>())).AddRange(((CodeInterpreterToolResultContent)contents[j]).Outputs ?? new List<AIContent>());
				}
				if (list != null)
				{
					CoalesceContent(list);
				}
				return new CodeInterpreterToolResultContent
				{
					CallId = codeInterpreterToolResultContent.CallId,
					Outputs = list,
					AdditionalProperties = codeInterpreterToolResultContent.AdditionalProperties?.Clone()
				};
			});
			static void Coalesce<TContent>(IList<AIContent> contents, bool mergeSingle, Func<TContent, TContent, bool>? canMerge, Func<IList<AIContent>, int, int, TContent> merge) where TContent : notnull, AIContent
			{
				int num = 0;
				while (num < contents.Count)
				{
					if (!TryAsCoalescable<TContent>(contents[num], out var coalescable2))
					{
						num++;
					}
					else
					{
						int num2 = num + 1;
						TContent arg = coalescable2;
						TContent coalescable3;
						while (num2 < contents.Count && TryAsCoalescable<TContent>(contents[num2], out coalescable3) && (canMerge == null || canMerge(arg, coalescable3)))
						{
							num2++;
							arg = coalescable3;
						}
						if (num == num2 - 1 && !mergeSingle)
						{
							num++;
						}
						else
						{
							contents[num] = merge(contents, num, num2);
							num++;
							while (num < num2)
							{
								contents[num++] = null;
							}
						}
					}
				}
				RemoveNullContents(contents);
			}
			static string MergeText(IList<AIContent> contents, int start, int end)
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int i = start; i < end; i++)
				{
					stringBuilder.Append(contents[i]);
				}
				return stringBuilder.ToString();
			}
			static bool TryAsCoalescable<TContent>(AIContent content, [NotNullWhen(true)] out TContent? coalescable) where TContent : notnull, AIContent
			{
				if (content is TContent val)
				{
					IList<AIAnnotation> annotations = val.Annotations;
					if (annotations == null || annotations.Count <= 0)
					{
						coalescable = val;
						return true;
					}
				}
				coalescable = null;
				return false;
			}
		}

		private static void RemoveNullContents<T>(IList<T> contents) where T : class
		{
			if (contents is List<AIContent> list)
			{
				list.RemoveAll((AIContent u) => u == null);
				return;
			}
			int num = 0;
			int count = contents.Count;
			for (int i = 0; i < count; i++)
			{
				T val = contents[i];
				if (val != null)
				{
					contents[num++] = val;
				}
			}
			for (int num2 = count - 1; num2 >= num; num2--)
			{
				contents.RemoveAt(num2);
			}
		}

		private static void FinalizeResponse(ChatResponse response)
		{
			int count = response.Messages.Count;
			for (int i = 0; i < count; i++)
			{
				CoalesceContent((List<AIContent>)response.Messages[i].Contents);
			}
		}

		private static void ProcessUpdate(ChatResponseUpdate update, ChatResponse response)
		{
			bool flag = true;
			if (response.Messages.Count != 0)
			{
				ChatMessage chatMessage = response.Messages[response.Messages.Count - 1];
				flag = NotEmptyOrEqual(update.AuthorName, chatMessage.AuthorName) || NotEmptyOrEqual(update.MessageId, chatMessage.MessageId) || NotNullOrEqual(update.Role, chatMessage.Role);
			}
			ChatMessage chatMessage2;
			if (flag)
			{
				chatMessage2 = new ChatMessage(ChatRole.Assistant, new List<AIContent>());
				response.Messages.Add(chatMessage2);
			}
			else
			{
				chatMessage2 = response.Messages[response.Messages.Count - 1];
			}
			if (update.AuthorName != null)
			{
				chatMessage2.AuthorName = update.AuthorName;
			}
			if (!chatMessage2.CreatedAt.HasValue || (update.CreatedAt.HasValue && update.CreatedAt > chatMessage2.CreatedAt))
			{
				chatMessage2.CreatedAt = update.CreatedAt;
			}
			ChatRole? role = update.Role;
			if (role.HasValue)
			{
				ChatRole valueOrDefault = role.GetValueOrDefault();
				chatMessage2.Role = valueOrDefault;
			}
			string messageId = update.MessageId;
			if (messageId != null && messageId.Length > 0)
			{
				chatMessage2.MessageId = update.MessageId;
			}
			foreach (AIContent content in update.Contents)
			{
				if (content is UsageContent usageContent)
				{
					(response.Usage ?? (response.Usage = new UsageDetails())).Add(usageContent.Details);
				}
				else
				{
					chatMessage2.Contents.Add(content);
				}
			}
			messageId = update.ResponseId;
			if (messageId != null && messageId.Length > 0)
			{
				response.ResponseId = update.ResponseId;
			}
			if (update.ConversationId != null)
			{
				response.ConversationId = update.ConversationId;
			}
			if (!response.CreatedAt.HasValue || (update.CreatedAt.HasValue && update.CreatedAt > response.CreatedAt))
			{
				response.CreatedAt = update.CreatedAt;
			}
			if (update.FinishReason.HasValue)
			{
				response.FinishReason = update.FinishReason;
			}
			if (update.ModelId != null)
			{
				response.ModelId = update.ModelId;
			}
			if (update.AdditionalProperties != null)
			{
				if (response.AdditionalProperties == null)
				{
					response.AdditionalProperties = new AdditionalPropertiesDictionary(update.AdditionalProperties);
				}
				else
				{
					response.AdditionalProperties.SetAll(update.AdditionalProperties);
				}
			}
		}

		private static bool NotEmptyOrEqual(string? s1, string? s2)
		{
			if (s1 != null && s1.Length > 0)
			{
				if (s2 != null && s2.Length > 0)
				{
					return s1 != s2;
				}
			}
			return false;
		}

		private static bool NotNullOrEqual(ChatRole? r1, ChatRole? r2)
		{
			if (r1.HasValue && r2.HasValue)
			{
				return r1.Value != r2.Value;
			}
			return false;
		}
	}
	[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
	[JsonDerivedType(typeof(ChatResponseFormatText), "text")]
	[JsonDerivedType(typeof(ChatResponseFormatJson), "json")]
	public class ChatResponseFormat
	{
		private static readonly AIJsonSchemaCreateOptions _inferenceOptions = new AIJsonSchemaCreateOptions
		{
			IncludeSchemaKeyword = true
		};

		private static readonly Regex _invalidNameCharsRegex = new Regex("[^0-9A-Za-z_]", RegexOptions.Compiled);

		public static ChatResponseFormatText Text { get; } = new ChatResponseFormatText();


		public static ChatResponseFormatJson Json { get; } = new ChatResponseFormatJson(null);


		private protected ChatResponseFormat()
		{
		}

		public static ChatResponseFormatJson ForJsonSchema(JsonElement schema, string? schemaName = null, string? schemaDescription = null)
		{
			return new ChatResponseFormatJson(schema, schemaName, schemaDescription);
		}

		public static ChatResponseFormatJson ForJsonSchema<T>(JsonSerializerOptions? serializerOptions = null, string? schemaName = null, string? schemaDescription = null)
		{
			return ForJsonSchema(typeof(T), serializerOptions, schemaName, schemaDescription);
		}

		public static ChatResponseFormatJson ForJsonSchema(Type schemaType, JsonSerializerOptions? serializerOptions = null, string? schemaName = null, string? schemaDescription = null)
		{
			Throw.IfNull(schemaType, "schemaType");
			JsonElement schema = AIJsonUtilities.CreateJsonSchema(schemaType, null, hasDefaultValue: false, null, serializerOptions ?? AIJsonUtilities.DefaultOptions, _inferenceOptions);
			return ForJsonSchema(schema, schemaName ?? schemaType.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? InvalidNameCharsRegex().Replace(schemaType.Name, "_"), schemaDescription ?? schemaType.GetCustomAttribute<DescriptionAttribute>()?.Description);
		}

		private static Regex InvalidNameCharsRegex()
		{
			return _invalidNameCharsRegex;
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public sealed class ChatResponseFormatJson : ChatResponseFormat
	{
		public JsonElement? Schema { get; }

		public string? SchemaName { get; }

		public string? SchemaDescription { get; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay => Schema?.ToString() ?? "JSON";

		[JsonConstructor]
		public ChatResponseFormatJson(JsonElement? schema, string? schemaName = null, string? schemaDescription = null)
		{
			if (!schema.HasValue && (schemaName != null || schemaDescription != null))
			{
				Throw.ArgumentException((schemaName != null) ? "schemaName" : "schemaDescription", "Schema name and description can only be specified if a schema is provided.");
			}
			Schema = schema;
			SchemaName = schemaName;
			SchemaDescription = schemaDescription;
		}
	}
	[DebuggerDisplay("Text")]
	public sealed class ChatResponseFormatText : ChatResponseFormat
	{
		public override bool Equals(object? obj)
		{
			return obj is ChatResponseFormatText;
		}

		public override int GetHashCode()
		{
			return typeof(ChatResponseFormatText).GetHashCode();
		}
	}
	[DebuggerDisplay("[{Role}] {ContentForDebuggerDisplay}{EllipsesForDebuggerDisplay,nq}")]
	public class ChatResponseUpdate
	{
		private IList<AIContent>? _contents;

		[CompilerGenerated]
		private string? <AuthorName>k__BackingField;

		public string? AuthorName
		{
			[CompilerGenerated]
			get
			{
				return <AuthorName>k__BackingField;
			}
			set
			{
				<AuthorName>k__BackingField = (string.IsNullOrWhiteSpace(value) ? null : value);
			}
		}

		public ChatRole? Role { get; set; }

		[JsonIgnore]
		public string Text
		{
			get
			{
				if (_contents == null)
				{
					return string.Empty;
				}
				return _contents.ConcatText();
			}
		}

		public IList<AIContent> Contents
		{
			get
			{
				return _contents ?? (_contents = new List<AIContent>());
			}
			[param: AllowNull]
			set
			{
				_contents = value;
			}
		}

		[JsonIgnore]
		public object? RawRepresentation { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }

		public string? ResponseId { get; set; }

		public string? MessageId { get; set; }

		public string? ConversationId { get; set; }

		public DateTimeOffset? CreatedAt { get; set; }

		public ChatFinishReason? FinishReason { get; set; }

		public string? ModelId { get; set; }

		[Experimental("MEAI001")]
		[JsonIgnore]
		public ResponseContinuationToken? ContinuationToken { get; set; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private AIContent? ContentForDebuggerDisplay
		{
			get
			{
				string text = Text;
				if (string.IsNullOrWhiteSpace(text))
				{
					IList<AIContent> contents = _contents;
					if (contents == null || contents.Count <= 0)
					{
						return null;
					}
					return _contents[0];
				}
				return new TextContent(text);
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string EllipsesForDebuggerDisplay
		{
			get
			{
				IList<AIContent> contents = _contents;
				if (contents == null || contents.Count <= 1)
				{
					return string.Empty;
				}
				return ", ...";
			}
		}

		[JsonConstructor]
		public ChatResponseUpdate()
		{
		}

		public ChatResponseUpdate(ChatRole? role, string? content)
			: this(role, (content == null) ? null : new List<AIContent>(1)
			{
				new TextContent(content)
			})
		{
		}

		public ChatResponseUpdate(ChatRole? role, IList<AIContent>? contents)
		{
			Role = role;
			_contents = contents;
		}

		public ChatResponseUpdate Clone()
		{
			return new ChatResponseUpdate
			{
				AdditionalProperties = AdditionalProperties,
				AuthorName = AuthorName,
				Contents = Contents,
				CreatedAt = CreatedAt,
				ConversationId = ConversationId,
				FinishReason = FinishReason,
				MessageId = MessageId,
				ModelId = ModelId,
				RawRepresentation = RawRepresentation,
				ResponseId = ResponseId,
				Role = Role
			};
		}

		public override string ToString()
		{
			return Text;
		}
	}
	[JsonConverter(typeof(Converter))]
	[DebuggerDisplay("{Value,nq}")]
	public readonly struct ChatRole : IEquatable<ChatRole>
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public sealed class Converter : JsonConverter<ChatRole>
		{
			public override ChatRole Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				return new ChatRole(reader.GetString());
			}

			public override void Write(Utf8JsonWriter writer, ChatRole value, JsonSerializerOptions options)
			{
				Throw.IfNull(writer, "writer").WriteStringValue(value.Value);
			}
		}

		public static ChatRole System { get; } = new ChatRole("system");


		public static ChatRole Assistant { get; } = new ChatRole("assistant");


		public static ChatRole User { get; } = new ChatRole("user");


		public static ChatRole Tool { get; } = new ChatRole("tool");


		public string Value { get; }

		[JsonConstructor]
		public ChatRole(string value)
		{
			Value = Throw.IfNullOrWhitespace(value, "value");
		}

		public static bool operator ==(ChatRole left, ChatRole right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ChatRole left, ChatRole right)
		{
			return !(left == right);
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ChatRole other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(ChatRole other)
		{
			return string.Equals(Value, other.Value, StringComparison.OrdinalIgnoreCase);
		}

		public override int GetHashCode()
		{
			return StringComparer.OrdinalIgnoreCase.GetHashCode(Value);
		}

		public override string ToString()
		{
			return Value;
		}
	}
	[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
	[JsonDerivedType(typeof(NoneChatToolMode), "none")]
	[JsonDerivedType(typeof(AutoChatToolMode), "auto")]
	[JsonDerivedType(typeof(RequiredChatToolMode), "required")]
	public class ChatToolMode
	{
		public static AutoChatToolMode Auto { get; } = new AutoChatToolMode();


		public static NoneChatToolMode None { get; } = new NoneChatToolMode();


		public static RequiredChatToolMode RequireAny { get; } = new RequiredChatToolMode(null);


		private protected ChatToolMode()
		{
		}

		public static RequiredChatToolMode RequireSpecific(string functionName)
		{
			return new RequiredChatToolMode(functionName);
		}
	}
	public class DelegatingChatClient : IChatClient, IDisposable
	{
		protected IChatClient InnerClient { get; }

		protected DelegatingChatClient(IChatClient innerClient)
		{
			InnerClient = Throw.IfNull(innerClient, "innerClient");
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		public virtual Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return InnerClient.GetResponseAsync(messages, options, cancellationToken);
		}

		public virtual IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return InnerClient.GetStreamingResponseAsync(messages, options, cancellationToken);
		}

		public virtual object? GetService(Type serviceType, object? serviceKey = null)
		{
			Throw.IfNull(serviceType, "serviceType");
			if (serviceKey != null || !serviceType.IsInstanceOfType(this))
			{
				return InnerClient.GetService(serviceType, serviceKey);
			}
			return this;
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				InnerClient.Dispose();
			}
		}
	}
	public interface IChatClient : IDisposable
	{
		Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken));

		IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken));

		object? GetService(Type serviceType, object? serviceKey = null);
	}
	[DebuggerDisplay("None")]
	public sealed class NoneChatToolMode : ChatToolMode
	{
		public override bool Equals(object? obj)
		{
			return obj is NoneChatToolMode;
		}

		public override int GetHashCode()
		{
			return typeof(NoneChatToolMode).GetHashCode();
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public sealed class RequiredChatToolMode : ChatToolMode
	{
		public string? RequiredFunctionName { get; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay => "Required: " + (RequiredFunctionName ?? "Any");

		public RequiredChatToolMode(string? requiredFunctionName)
		{
			if (requiredFunctionName != null)
			{
				Throw.IfNullOrWhitespace(requiredFunctionName, "requiredFunctionName");
			}
			RequiredFunctionName = requiredFunctionName;
		}

		public override bool Equals(object? obj)
		{
			if (obj is RequiredChatToolMode requiredChatToolMode)
			{
				return RequiredFunctionName == requiredChatToolMode.RequiredFunctionName;
			}
			return false;
		}

		public override int GetHashCode()
		{
			string? requiredFunctionName = RequiredFunctionName;
			if (requiredFunctionName == null)
			{
				return typeof(RequiredChatToolMode).GetHashCode();
			}
			return StringHash.GetHashCode(requiredFunctionName, StringComparison.Ordinal);
		}
	}
	[Experimental("MEAI001")]
	public interface IChatReducer
	{
		Task<IEnumerable<ChatMessage>> ReduceAsync(IEnumerable<ChatMessage> messages, CancellationToken cancellationToken);
	}
	[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
	[JsonDerivedType(typeof(CitationAnnotation), "citation")]
	public class AIAnnotation
	{
		public IList<AnnotatedRegion>? AnnotatedRegions { get; set; }

		[JsonIgnore]
		public object? RawRepresentation { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }
	}
	[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
	[JsonDerivedType(typeof(DataContent), "data")]
	[JsonDerivedType(typeof(ErrorContent), "error")]
	[JsonDerivedType(typeof(FunctionCallContent), "functionCall")]
	[JsonDerivedType(typeof(FunctionResultContent), "functionResult")]
	[JsonDerivedType(typeof(HostedFileContent), "hostedFile")]
	[JsonDerivedType(typeof(HostedVectorStoreContent), "hostedVectorStore")]
	[JsonDerivedType(typeof(TextContent), "text")]
	[JsonDerivedType(typeof(TextReasoningContent), "reasoning")]
	[JsonDerivedType(typeof(UriContent), "uri")]
	[JsonDerivedType(typeof(UsageContent), "usage")]
	public class AIContent
	{
		public IList<AIAnnotation>? Annotations { get; set; }

		[JsonIgnore]
		public object? RawRepresentation { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }
	}
	internal static class AIContentExtensions
	{
		public static string ConcatText(this IEnumerable<AIContent> contents)
		{
			if (contents is IList<AIContent> list)
			{
				int count = list.Count;
				switch (count)
				{
				case 0:
					return string.Empty;
				case 1:
					return (list[0] as TextContent)?.Text ?? string.Empty;
				default:
				{
					StringBuilder stringBuilder = new StringBuilder();
					for (int i = 0; i < count; i++)
					{
						if (list[i] is TextContent textContent)
						{
							stringBuilder.Append(textContent.Text);
						}
					}
					return stringBuilder.ToString();
				}
				}
			}
			return string.Concat(contents.OfType<TextContent>());
		}

		public static string ConcatText(this IList<ChatMessage> messages)
		{
			int count = messages.Count;
			switch (count)
			{
			case 0:
				return string.Empty;
			case 1:
				return messages[0].Text;
			default:
			{
				StringBuilder stringBuilder = new StringBuilder();
				for (int i = 0; i < count; i++)
				{
					string text = messages[i].Text;
					if (text.Length > 0)
					{
						if (stringBuilder.Length > 0)
						{
							stringBuilder.AppendLine();
						}
						stringBuilder.Append(text);
					}
				}
				return stringBuilder.ToString();
			}
			}
		}
	}
	[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
	[JsonDerivedType(typeof(TextSpanAnnotatedRegion), "textSpan")]
	public class AnnotatedRegion
	{
	}
	public class CitationAnnotation : AIAnnotation
	{
		public string? Title { get; set; }

		public Uri? Url { get; set; }

		public string? FileId { get; set; }

		public string? ToolName { get; set; }

		public string? Snippet { get; set; }
	}
	[Experimental("MEAI001")]
	public sealed class CodeInterpreterToolCallContent : AIContent
	{
		public string? CallId { get; set; }

		public IList<AIContent>? Inputs { get; set; }
	}
	[Experimental("MEAI001")]
	public sealed class CodeInterpreterToolResultContent : AIContent
	{
		public string? CallId { get; set; }

		public IList<AIContent>? Outputs { get; set; }
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public class DataContent : AIContent
	{
		private readonly DataUriParser.DataUri? _dataUri;

		private string? _uri;

		private ReadOnlyMemory<byte>? _data;

		[StringSyntax("Uri")]
		public string Uri
		{
			get
			{
				if (_uri == null)
				{
					ReadOnlyMemory<byte> valueOrDefault = _data.GetValueOrDefault();
					ArraySegment<byte> segment;
					string text = (MemoryMarshal.TryGetArray(valueOrDefault, out segment) ? Convert.ToBase64String(segment.Array, segment.Offset, segment.Count) : Convert.ToBase64String(valueOrDefault.ToArray()));
					_uri = "data:" + MediaType + ";base64," + text;
				}
				return _uri;
			}
		}

		[JsonIgnore]
		public string MediaType { get; }

		public string? Name { get; set; }

		[JsonIgnore]
		public ReadOnlyMemory<byte> Data
		{
			get
			{
				ReadOnlyMemory<byte>? data = _data;
				if (!data.HasValue)
				{
					_data = _dataUri.ToByteArray();
				}
				return _data.GetValueOrDefault();
			}
		}

		[JsonIgnore]
		public ReadOnlyMemory<char> Base64Data
		{
			get
			{
				string uri = Uri;
				int num = uri.IndexOf(',');
				return uri.AsMemory(num + 1);
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay
		{
			get
			{
				if (HasTopLevelMediaType("text"))
				{
					return "MediaType = " + MediaType + ", Text = \"" + Encoding.UTF8.GetString(Data.ToArray()) + "\"";
				}
				if ("application/json".Equals(MediaType, StringComparison.OrdinalIgnoreCase))
				{
					return "JSON = " + Encoding.UTF8.GetString(Data.ToArray());
				}
				string uri = Uri;
				if (uri.Length > 80)
				{
					return "Data = " + uri.Substring(0, 80) + "...";
				}
				return "Data = " + uri;
			}
		}

		public DataContent(Uri uri, string? mediaType = null)
			: this(Throw.IfNull(uri, "uri").ToString(), mediaType)
		{
		}

		[JsonConstructor]
		public DataContent([StringSyntax("Uri")] string uri, string? mediaType = null)
		{
			_uri = Throw.IfNullOrWhitespace(uri, "uri");
			if (!uri.StartsWith(DataUriParser.Scheme, StringComparison.OrdinalIgnoreCase))
			{
				Throw.ArgumentException("uri", "The provided URI is not a data URI.");
			}
			_dataUri = DataUriParser.Parse(uri.AsMemory());
			if (mediaType == null)
			{
				mediaType = _dataUri.MediaType;
			}
			if (mediaType == null)
			{
				Throw.ArgumentNullException("mediaType", "uri did not contain a media type, and mediaType was not provided.");
			}
			MediaType = DataUriParser.ThrowIfInvalidMediaType(mediaType, "mediaType");
			if (!_dataUri.IsBase64 || mediaType != _dataUri.MediaType)
			{
				_data = _dataUri.ToByteArray();
				_dataUri = null;
				_uri = null;
			}
		}

		public DataContent(ReadOnlyMemory<byte> data, string mediaType)
		{
			MediaType = DataUriParser.ThrowIfInvalidMediaType(mediaType, "mediaType");
			_data = data;
		}

		public bool HasTopLevelMediaType(string topLevelType)
		{
			return DataUriParser.HasTopLevelMediaType(MediaType, topLevelType);
		}
	}
	internal static class DataUriParser
	{
		public sealed class DataUri
		{
			public string? MediaType { get; }

			public ReadOnlyMemory<char> Data { get; }

			public bool IsBase64 { get; }

			public DataUri(ReadOnlyMemory<char> data, bool isBase64, string? mediaType)
			{
				MediaType = mediaType;
				Data = data;
				IsBase64 = isBase64;
				base..ctor();
			}

			public byte[] ToByteArray()
			{
				if (!IsBase64)
				{
					return Encoding.UTF8.GetBytes(WebUtility.UrlDecode(Data.ToString()));
				}
				return Convert.FromBase64String(Data.ToString());
			}
		}

		public static string Scheme => "data:";

		public static DataUri Parse(ReadOnlyMemory<char> dataUri)
		{
			if (!dataUri.Span.StartsWith(Scheme.AsSpan(), StringComparison.OrdinalIgnoreCase))
			{
				throw new UriFormatException("Invalid data URI format: the data URI must start with 'data:'.");
			}
			dataUri = dataUri.Slice(Scheme.Length);
			int num = dataUri.Span.IndexOf(',');
			if (num < 0)
			{
				throw new UriFormatException("Invalid data URI format: the data URI must contain a comma separating the metadata and the data.");
			}
			ReadOnlyMemory<char> readOnlyMemory = dataUri.Slice(0, num);
			ReadOnlyMemory<char> data = dataUri.Slice(num + 1);
			bool isBase = false;
			if (readOnlyMemory.Span.EndsWith(";base64".AsSpan(), StringComparison.OrdinalIgnoreCase))
			{
				readOnlyMemory = readOnlyMemory.Slice(0, readOnlyMemory.Length - ";base64".Length);
				isBase = true;
				if (!IsValidBase64Data(data.Span))
				{
					throw new UriFormatException("Invalid data URI format: the data URI is base64-encoded, but the data is not a valid base64 string.");
				}
			}
			ReadOnlySpan<char> mediaTypeSpan = readOnlyMemory.Span.Trim();
			string mediaType = null;
			if (!mediaTypeSpan.IsEmpty && !IsValidMediaType(mediaTypeSpan, ref mediaType))
			{
				throw new UriFormatException("Invalid data URI format: the media type is not a valid.");
			}
			return new DataUri(data, isBase, mediaType);
		}

		public static string ThrowIfInvalidMediaType(string mediaType, [CallerArgumentExpression("mediaType")] string parameterName = "")
		{
			Throw.IfNullOrWhitespace(mediaType, parameterName);
			if (!IsValidMediaType(mediaType))
			{
				Throw.ArgumentException(parameterName, "An invalid media type was specified: '" + mediaType + "'");
			}
			return mediaType;
		}

		public static bool IsValidMediaType(string mediaType)
		{
			return IsValidMediaType(mediaType.AsSpan(), ref mediaType);
		}

		public static bool IsValidMediaType(ReadOnlySpan<char> mediaTypeSpan, [NotNull] ref string? mediaType)
		{
			string text;
			switch (mediaTypeSpan.Length)
			{
			case 24:
			{
				char c = mediaTypeSpan[0];
				if (c != 'a')
				{
					if (c == 't' && mediaTypeSpan.SequenceEqual("text/plain;charset=UTF-8".AsSpan()))
					{
						text = "text/plain;charset=UTF-8";
						break;
					}
				}
				else if (mediaTypeSpan.SequenceEqual("application/octet-stream".AsSpan()))
				{
					text = "application/octet-stream";
					break;
				}
				goto IL_045b;
			}
			case 15:
			{
				char c = mediaTypeSpan[12];
				if (c != 'i')
				{
					if (c != 'p')
					{
						if (c == 'x' && mediaTypeSpan.SequenceEqual("application/xml".AsSpan()))
						{
							text = "application/xml";
							break;
						}
					}
					else if (mediaTypeSpan.SequenceEqual("application/pdf".AsSpan()))
					{
						text = "application/pdf";
						break;
					}
				}
				else if (mediaTypeSpan.SequenceEqual("text/javascript".AsSpan()))
				{
					text = "text/javascript";
					break;
				}
				goto IL_045b;
			}
			case 10:
				switch (mediaTypeSpan[6])
				{
				case 'm':
					break;
				case 'a':
					goto IL_01f3;
				case 'j':
					goto IL_0222;
				case 't':
					goto IL_023c;
				case 'w':
					goto IL_0256;
				case 'l':
					goto IL_0270;
				default:
					goto IL_045b;
				}
				if (!mediaTypeSpan.SequenceEqual("audio/mpeg".AsSpan()))
				{
					goto IL_045b;
				}
				text = "audio/mpeg";
				break;
			case 9:
			{
				char c = mediaTypeSpan[6];
				if ((uint)c <= 111u)
				{
					if (c != 'b')
					{
						if (c != 'g')
						{
							if (c == 'o' && mediaTypeSpan.SequenceEqual("audio/ogg".AsSpan()))
							{
								text = "audio/ogg";
								break;
							}
						}
						else if (mediaTypeSpan.SequenceEqual("image/gif".AsSpan()))
						{
							text = "image/gif";
							break;
						}
					}
					else if (mediaTypeSpan.SequenceEqual("image/bmp".AsSpan()))
					{
						text = "image/bmp";
						break;
					}
				}
				else if (c != 'p')
				{
					if (c != 't')
					{
						if (c == 'w' && mediaTypeSpan.SequenceEqual("audio/wav".AsSpan()))
						{
							text = "audio/wav";
							break;
						}
					}
					else if (mediaTypeSpan.SequenceEqual("text/html".AsSpan()))
					{
						text = "text/html";
						break;
					}
				}
				else if (mediaTypeSpan.SequenceEqual("image/png".AsSpan()))
				{
					text = "image/png";
					break;
				}
				goto IL_045b;
			}
			case 8:
			{
				char c = mediaTypeSpan[7];
				if (c != 'l')
				{
					if (c != 's')
					{
						if (c == 'v' && mediaTypeSpan.SequenceEqual("text/csv".AsSpan()))
						{
							text = "text/csv";
							break;
						}
					}
					else if (mediaTypeSpan.SequenceEqual("text/css".AsSpan()))
					{
						text = "text/css";
						break;
					}
				}
				else if (mediaTypeSpan.SequenceEqual("text/xml".AsSpan()))
				{
					text = "text/xml";
					break;
				}
				goto IL_045b;
			}
			case 16:
				if (!mediaTypeSpan.SequenceEqual("application/json".AsSpan()))
				{
					goto IL_045b;
				}
				text = "application/json";
				break;
			case 13:
				if (!mediaTypeSpan.SequenceEqual("image/svg+xml".AsSpan()))
				{
					goto IL_045b;
				}
				text = "image/svg+xml";
				break;
			default:
				goto IL_045b;
				IL_0270:
				if (!mediaTypeSpan.SequenceEqual("text/plain".AsSpan()))
				{
					goto IL_045b;
				}
				text = "text/plain";
				break;
				IL_0256:
				if (!mediaTypeSpan.SequenceEqual("image/webp".AsSpan()))
				{
					goto IL_045b;
				}
				text = "image/webp";
				break;
				IL_0222:
				if (!mediaTypeSpan.SequenceEqual("image/jpeg".AsSpan()))
				{
					goto IL_045b;
				}
				text = "image/jpeg";
				break;
				IL_045b:
				text = null;
				break;
				IL_023c:
				if (!mediaTypeSpan.SequenceEqual("image/tiff".AsSpan()))
				{
					goto IL_045b;
				}
				text = "image/tiff";
				break;
				IL_01f3:
				if (!mediaTypeSpan.SequenceEqual("image/apng".AsSpan()))
				{
					if (!mediaTypeSpan.SequenceEqual("image/avif".AsSpan()))
					{
						goto IL_045b;
					}
					text = "image/avif";
					break;
				}
				text = "image/apng";
				break;
			}
			string text2 = text;
			if (text2 != null)
			{
				mediaType = text2;
				return true;
			}
			if (mediaType == null)
			{
				mediaType = mediaTypeSpan.ToString();
			}
			MediaTypeHeaderValue parsedValue;
			return MediaTypeHeaderValue.TryParse(mediaType, out parsedValue);
		}

		public static bool HasTopLevelMediaType(string mediaType, string topLevelMediaType)
		{
			int num = mediaType.IndexOf('/');
			ReadOnlySpan<char> span = ((num < 0) ? mediaType.AsSpan() : mediaType.AsSpan(0, num));
			span = span.Trim();
			return MemoryExtensions.Equals(span, topLevelMediaType.AsSpan(), StringComparison.OrdinalIgnoreCase);
		}

		private static bool IsValidBase64Data(ReadOnlySpan<char> value)
		{
			if (value.IsEmpty)
			{
				return true;
			}
			if (value.Length % 4 != 0)
			{
				return false;
			}
			int num = value.Length - 1;
			if (value[num] == '=')
			{
				num--;
			}
			if (value[num] == '=')
			{
				num--;
			}
			for (int i = 0; i <= num; i++)
			{
				bool flag;
				switch (value[i])
				{
				case '+':
				case '/':
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
				case '8':
				case '9':
				case 'A':
				case 'B':
				case 'C':
				case 'D':
				case 'E':
				case 'F':
				case 'G':
				case 'H':
				case 'I':
				case 'J':
				case 'K':
				case 'L':
				case 'M':
				case 'N':
				case 'O':
				case 'P':
				case 'Q':
				case 'R':
				case 'S':
				case 'T':
				case 'U':
				case 'V':
				case 'W':
				case 'X':
				case 'Y':
				case 'Z':
				case 'a':
				case 'b':
				case 'c':
				case 'd':
				case 'e':
				case 'f':
				case 'g':
				case 'h':
				case 'i':
				case 'j':
				case 'k':
				case 'l':
				case 'm':
				case 'n':
				case 'o':
				case 'p':
				case 'q':
				case 'r':
				case 's':
				case 't':
				case 'u':
				case 'v':
				case 'w':
				case 'x':
				case 'y':
				case 'z':
					flag = true;
					break;
				default:
					flag = false;
					break;
				}
				if (!flag)
				{
					return false;
				}
			}
			return true;
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public class ErrorContent : AIContent
	{
		[CompilerGenerated]
		private string <Message>k__BackingField;

		public string Message
		{
			get
			{
				return <Message>k__BackingField ?? string.Empty;
			}
			[CompilerGenerated]
			[param: AllowNull]
			set
			{
				<Message>k__BackingField = value;
			}
		}

		public string? ErrorCode { get; set; }

		public string? Details { get; set; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay => "Error = \"" + Message + "\"" + ((!string.IsNullOrWhiteSpace(ErrorCode)) ? (" (" + ErrorCode + ")") : string.Empty) + ((!string.IsNullOrWhiteSpace(Details)) ? (" - \"" + Details + "\"") : string.Empty);

		public ErrorContent(string? message)
		{
			Message = message;
		}
	}
	[Experimental("MEAI001")]
	public sealed class FunctionApprovalRequestContent : UserInputRequestContent
	{
		public FunctionCallContent FunctionCall { get; }

		public FunctionApprovalRequestContent(string id, FunctionCallContent functionCall)
			: base(id)
		{
			FunctionCall = Throw.IfNull(functionCall, "functionCall");
		}

		public FunctionApprovalResponseContent CreateResponse(bool approved)
		{
			return new FunctionApprovalResponseContent(base.Id, approved, FunctionCall);
		}
	}
	[Experimental("MEAI001")]
	public sealed class FunctionApprovalResponseContent : UserInputResponseContent
	{
		public bool Approved { get; }

		public FunctionCallContent FunctionCall { get; }

		public FunctionApprovalResponseContent(string id, bool approved, FunctionCallContent functionCall)
			: base(id)
		{
			Approved = approved;
			FunctionCall = Throw.IfNull(functionCall, "functionCall");
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public sealed class FunctionCallContent : AIContent
	{
		public string CallId { get; }

		public string Name { get; }

		public IDictionary<string, object?>? Arguments { get; set; }

		[JsonIgnore]
		public Exception? Exception { get; set; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay
		{
			get
			{
				string text = "FunctionCall = ";
				if (CallId != null)
				{
					text = text + CallId + ", ";
				}
				return text + ((Arguments != null) ? (Name + "(" + string.Join(", ", Arguments) + ")") : (Name + "()"));
			}
		}

		[JsonConstructor]
		public FunctionCallContent(string callId, string name, IDictionary<string, object?>? arguments = null)
		{
			CallId = Throw.IfNull(callId, "callId");
			Name = Throw.IfNull(name, "name");
			Arguments = arguments;
		}

		public static FunctionCallContent CreateFromParsedArguments<TEncoding>(TEncoding encodedArguments, string callId, string name, Func<TEncoding, IDictionary<string, object?>?> argumentParser)
		{
			Throw.IfNull(encodedArguments, "encodedArguments");
			Throw.IfNull(callId, "callId");
			Throw.IfNull(name, "name");
			Throw.IfNull(argumentParser, "argumentParser");
			IDictionary<string, object> arguments = null;
			Exception exception = null;
			try
			{
				arguments = argumentParser(encodedArguments);
			}
			catch (Exception innerException)
			{
				exception = new InvalidOperationException("Error parsing function call arguments.", innerException);
			}
			return new FunctionCallContent(callId, name, arguments)
			{
				Exception = exception
			};
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public sealed class FunctionResultContent : AIContent
	{
		public string CallId { get; }

		public object? Result { get; set; }

		[JsonIgnore]
		public Exception? Exception { get; set; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay
		{
			get
			{
				string text = "FunctionResult = ";
				if (CallId != null)
				{
					text = text + CallId + ", ";
				}
				return text + ((Exception != null) ? (Exception.GetType().Name + "(\"" + Exception.Message + "\")") : ((Result?.ToString() ?? "(null)") ?? ""));
			}
		}

		[JsonConstructor]
		public FunctionResultContent(string callId, object? result)
		{
			CallId = Throw.IfNull(callId, "callId");
			Result = result;
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public sealed class HostedFileContent : AIContent
	{
		[CompilerGenerated]
		private string <FileId>k__BackingField;

		[CompilerGenerated]
		private string? <MediaType>k__BackingField;

		public string FileId
		{
			get
			{
				return <FileId>k__BackingField;
			}
			set
			{
				<FileId>k__BackingField = Throw.IfNullOrWhitespace(value, "value");
			}
		}

		public string? MediaType
		{
			[CompilerGenerated]
			get
			{
				return <MediaType>k__BackingField;
			}
			set
			{
				<MediaType>k__BackingField = ((value != null) ? DataUriParser.ThrowIfInvalidMediaType(value, "value") : value);
			}
		}

		public string? Name { get; set; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay
		{
			get
			{
				string text = "FileId = " + FileId;
				string mediaType = MediaType;
				if (mediaType != null)
				{
					text = text + ", MediaType = " + mediaType;
				}
				string name = Name;
				if (name != null)
				{
					text = text + ", Name = \"" + name + "\"";
				}
				return text;
			}
		}

		public HostedFileContent(string fileId)
		{
			FileId = Throw.IfNullOrWhitespace(fileId, "fileId");
		}

		public bool HasTopLevelMediaType(string topLevelType)
		{
			if (MediaType != null)
			{
				return DataUriParser.HasTopLevelMediaType(MediaType, topLevelType);
			}
			return false;
		}
	}
	[DebuggerDisplay("VectorStoreId = {VectorStoreId}")]
	public sealed class HostedVectorStoreContent : AIContent
	{
		private string _vectorStoreId;

		public string VectorStoreId
		{
			get
			{
				return _vectorStoreId;
			}
			set
			{
				_vectorStoreId = Throw.IfNullOrWhitespace(value, "value");
			}
		}

		public HostedVectorStoreContent(string vectorStoreId)
		{
			_vectorStoreId = Throw.IfNullOrWhitespace(vectorStoreId, "vectorStoreId");
		}
	}
	[Experimental("MEAI001")]
	public sealed class ImageGenerationToolCallContent : AIContent
	{
		public string? ImageId { get; set; }
	}
	[Experimental("MEAI001")]
	public sealed class ImageGenerationToolResultContent : AIContent
	{
		public string? ImageId { get; set; }

		public IList<AIContent>? Outputs { get; set; }
	}
	[Experimental("MEAI001")]
	public sealed class McpServerToolApprovalRequestContent : UserInputRequestContent
	{
		public McpServerToolCallContent ToolCall { get; }

		public McpServerToolApprovalRequestContent(string id, McpServerToolCallContent toolCall)
			: base(id)
		{
			ToolCall = Throw.IfNull(toolCall, "toolCall");
		}

		public McpServerToolApprovalResponseContent CreateResponse(bool approved)
		{
			return new McpServerToolApprovalResponseContent(base.Id, approved);
		}
	}
	[Experimental("MEAI001")]
	public sealed class McpServerToolApprovalResponseContent : UserInputResponseContent
	{
		public bool Approved { get; }

		public McpServerToolApprovalResponseContent(string id, bool approved)
			: base(id)
		{
			Approved = approved;
		}
	}
	[Experimental("MEAI001")]
	public sealed class McpServerToolCallContent : AIContent
	{
		public string CallId { get; }

		public string ToolName { get; }

		public string? ServerName { get; }

		public IReadOnlyDictionary<string, object?>? Arguments { get; set; }

		public McpServerToolCallContent(string callId, string toolName, string? serverName)
		{
			CallId = Throw.IfNullOrWhitespace(callId, "callId");
			ToolName = Throw.IfNullOrWhitespace(toolName, "toolName");
			ServerName = serverName;
		}
	}
	[Experimental("MEAI001")]
	public sealed class McpServerToolResultContent : AIContent
	{
		public string CallId { get; }

		public IList<AIContent>? Output { get; set; }

		public McpServerToolResultContent(string callId)
		{
			CallId = Throw.IfNullOrWhitespace(callId, "callId");
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public sealed class TextContent : AIContent
	{
		[CompilerGenerated]
		private string <Text>k__BackingField;

		public string Text
		{
			get
			{
				return <Text>k__BackingField ?? string.Empty;
			}
			[CompilerGenerated]
			[param: AllowNull]
			set
			{
				<Text>k__BackingField = value;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay => "Text = \"" + Text + "\"";

		public TextContent(string? text)
		{
			Text = text;
		}

		public override string ToString()
		{
			return Text;
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public sealed class TextReasoningContent : AIContent
	{
		[CompilerGenerated]
		private string <Text>k__BackingField;

		public string Text
		{
			get
			{
				return <Text>k__BackingField ?? string.Empty;
			}
			[CompilerGenerated]
			[param: AllowNull]
			set
			{
				<Text>k__BackingField = value;
			}
		}

		public string? ProtectedData { get; set; }

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay => "Reasoning = \"" + Text + "\"";

		public TextReasoningContent(string? text)
		{
			Text = text;
		}

		public override string ToString()
		{
			return Text;
		}
	}
	[DebuggerDisplay("[{StartIndex}, {EndIndex})")]
	public sealed class TextSpanAnnotatedRegion : AnnotatedRegion
	{
		[JsonPropertyName("start")]
		public int? StartIndex { get; set; }

		[JsonPropertyName("end")]
		public int? EndIndex { get; set; }
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public class UriContent : AIContent
	{
		private Uri _uri;

		private string _mediaType;

		public Uri Uri
		{
			get
			{
				return _uri;
			}
			set
			{
				_uri = Throw.IfNull(value, "value");
			}
		}

		public string MediaType
		{
			get
			{
				return _mediaType;
			}
			set
			{
				_mediaType = DataUriParser.ThrowIfInvalidMediaType(value, "value");
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay => $"Uri = {_uri}";

		public UriContent(string uri, string mediaType)
			: this(new Uri(Throw.IfNull(uri, "uri")), mediaType)
		{
		}

		[JsonConstructor]
		public UriContent(Uri uri, string mediaType)
		{
			_uri = Throw.IfNull(uri, "uri");
			_mediaType = DataUriParser.ThrowIfInvalidMediaType(mediaType, "mediaType");
		}

		public bool HasTopLevelMediaType(string topLevelType)
		{
			return DataUriParser.HasTopLevelMediaType(MediaType, topLevelType);
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	public class UsageContent : AIContent
	{
		private UsageDetails _details;

		public UsageDetails Details
		{
			get
			{
				return _details;
			}
			set
			{
				_details = Throw.IfNull(value, "value");
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay => "Usage = " + _details.DebuggerDisplay;

		public UsageContent()
		{
			_details = new UsageDetails();
		}

		[JsonConstructor]
		public UsageContent(UsageDetails details)
		{
			_details = Throw.IfNull(details, "details");
		}
	}
	[Experimental("MEAI001")]
	[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
	[JsonDerivedType(typeof(FunctionApprovalRequestContent), "functionApprovalRequest")]
	[JsonDerivedType(typeof(McpServerToolApprovalRequestContent), "mcpServerToolApprovalRequest")]
	public class UserInputRequestContent : AIContent
	{
		public string Id { get; }

		protected UserInputRequestContent(string id)
		{
			Id = Throw.IfNullOrWhitespace(id, "id");
		}
	}
	[Experimental("MEAI001")]
	[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
	[JsonDerivedType(typeof(FunctionApprovalResponseContent), "functionApprovalResponse")]
	[JsonDerivedType(typeof(McpServerToolApprovalResponseContent), "mcpServerToolApprovalResponse")]
	public class UserInputResponseContent : AIContent
	{
		public string Id { get; }

		protected UserInputResponseContent(string id)
		{
			Id = Throw.IfNullOrWhitespace(id, "id");
		}
	}
	public sealed class BinaryEmbedding : Embedding
	{
		[EditorBrowsable(EditorBrowsableState.Never)]
		public sealed class VectorConverter : JsonConverter<BitArray>
		{
			public override BitArray Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
			{
				Throw.IfNull(typeToConvert, "typeToConvert");
				Throw.IfNull(options, "options");
				if (reader.TokenType != JsonTokenType.String)
				{
					throw new JsonException("Expected string property.");
				}
				byte[] array = null;
				ReadOnlySpan<byte> readOnlySpan;
				if (!reader.HasValueSequence && !reader.ValueIsEscaped)
				{
					readOnlySpan = reader.ValueSpan;
				}
				else
				{
					int minimumLength = (reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length);
					array = ArrayPool<byte>.Shared.Rent(minimumLength);
					readOnlySpan = array.AsSpan(0, reader.CopyString((Span<byte>)array));
				}
				BitArray bitArray = new BitArray(readOnlySpan.Length);
				for (int i = 0; i < readOnlySpan.Length; i++)
				{
					BitArray bitArray2 = bitArray;
					int index = i;
					bitArray2[index] = readOnlySpan[i] switch
					{
						48 => false, 
						49 => true, 
						_ => throw new JsonException("Expected binary character sequence."), 
					};
				}
				if (array != null)
				{
					ArrayPool<byte>.Shared.Return(array);
				}
				return bitArray;
			}

			public override void Write(Utf8JsonWriter writer, BitArray value, JsonSerializerOptions options)
			{
				Throw.IfNull(writer, "writer");
				Throw.IfNull(value, "value");
				Throw.IfNull(options, "options");
				int length = value.Length;
				byte[] array = ArrayPool<byte>.Shared.Rent(length);
				Span<byte> span = array.AsSpan(0, length);
				for (int i = 0; i < span.Length; i++)
				{
					span[i] = (byte)(value[i] ? 49 : 48);
				}
				writer.WriteStringValue(span);
				ArrayPool<byte>.Shared.Return(array);
			}
		}

		private BitArray _vector;

		[JsonConverter(typeof(VectorConverter))]
		public BitArray Vector
		{
			get
			{
				return _vector;
			}
			set
			{
				_vector = Throw.IfNull(value, "value");
			}
		}

		[JsonIgnore]
		public override int Dimensions => _vector.Length;

		public BinaryEmbedding(BitArray vector)
		{
			_vector = Throw.IfNull(vector, "vector");
		}
	}
	public class DelegatingEmbeddingGenerator<TInput, TEmbedding> : IEmbeddingGenerator<TInput, TEmbedding>, IEmbeddingGenerator, IDisposable where TEmbedding : Embedding
	{
		protected IEmbeddingGenerator<TInput, TEmbedding> InnerGenerator { get; }

		protected DelegatingEmbeddingGenerator(IEmbeddingGenerator<TInput, TEmbedding> innerGenerator)
		{
			InnerGenerator = Throw.IfNull(innerGenerator, "innerGenerator");
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		public virtual Task<GeneratedEmbeddings<TEmbedding>> GenerateAsync(IEnumerable<TInput> values, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return InnerGenerator.GenerateAsync(values, options, cancellationToken);
		}

		public virtual object? GetService(Type serviceType, object? serviceKey = null)
		{
			Throw.IfNull(serviceType, "serviceType");
			if (serviceKey != null || !serviceType.IsInstanceOfType(this))
			{
				return InnerGenerator.GetService(serviceType, serviceKey);
			}
			return this;
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				InnerGenerator.Dispose();
			}
		}
	}
	[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
	[JsonDerivedType(typeof(BinaryEmbedding), "binary")]
	[JsonDerivedType(typeof(Embedding<byte>), "uint8")]
	[JsonDerivedType(typeof(Embedding<sbyte>), "int8")]
	[JsonDerivedType(typeof(Embedding<float>), "float32")]
	[JsonDerivedType(typeof(Embedding<double>), "float64")]
	[DebuggerDisplay("Dimensions = {Dimensions}")]
	public class Embedding
	{
		public DateTimeOffset? CreatedAt { get; set; }

		[JsonIgnore]
		public virtual int Dimensions { get; }

		public string? ModelId { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }

		protected Embedding()
		{
		}
	}
	public class EmbeddingGenerationOptions
	{
		[CompilerGenerated]
		private int? <Dimensions>k__BackingField;

		public int? Dimensions
		{
			[CompilerGenerated]
			get
			{
				return <Dimensions>k__BackingField;
			}
			set
			{
				if (value.HasValue)
				{
					Throw.IfLessThan(value.Value, 1, "value");
				}
				<Dimensions>k__BackingField = value;
			}
		}

		public string? ModelId { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }

		[JsonIgnore]
		public Func<IEmbeddingGenerator, object?>? RawRepresentationFactory { get; set; }

		public EmbeddingGenerationOptions()
		{
		}

		protected EmbeddingGenerationOptions(EmbeddingGenerationOptions? other)
		{
			if (other != null)
			{
				AdditionalProperties = other.AdditionalProperties?.Clone();
				Dimensions = other.Dimensions;
				ModelId = other.ModelId;
				RawRepresentationFactory = other.RawRepresentationFactory;
			}
		}

		public virtual EmbeddingGenerationOptions Clone()
		{
			return new EmbeddingGenerationOptions(this);
		}
	}
	public static class EmbeddingGeneratorExtensions
	{
		public static TService? GetService<TService>(this IEmbeddingGenerator generator, object? serviceKey = null)
		{
			Throw.IfNull(generator, "generator");
			object service = generator.GetService(typeof(TService), serviceKey);
			if (service is TService)
			{
				return (TService)service;
			}
			return default(TService);
		}

		public static object GetRequiredService(this IEmbeddingGenerator generator, Type serviceType, object? serviceKey = null)
		{
			Throw.IfNull(generator, "generator");
			Throw.IfNull(serviceType, "serviceType");
			return generator.GetService(serviceType, serviceKey) ?? throw Throw.CreateMissingServiceException(serviceType, serviceKey);
		}

		public static TService GetRequiredService<TService>(this IEmbeddingGenerator generator, object? serviceKey = null)
		{
			Throw.IfNull(generator, "generator");
			object service = generator.GetService(typeof(TService), serviceKey);
			if (service is TService)
			{
				return (TService)service;
			}
			throw Throw.CreateMissingServiceException(typeof(TService), serviceKey);
		}

		public static async Task<ReadOnlyMemory<TEmbeddingElement>> GenerateVectorAsync<TInput, TEmbeddingElement>(this IEmbeddingGenerator<TInput, Embedding<TEmbeddingElement>> generator, TInput value, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return (await generator.GenerateAsync(value, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Vector;
		}

		public static async Task<TEmbedding> GenerateAsync<TInput, TEmbedding>(this IEmbeddingGenerator<TInput, TEmbedding> generator, TInput value, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) where TEmbedding : Embedding
		{
			Throw.IfNull(generator, "generator");
			Throw.IfNull(value, "value");
			GeneratedEmbeddings<TEmbedding> generatedEmbeddings = await generator.GenerateAsync(new <>z__ReadOnlySingleElementList<TInput>(value), options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (generatedEmbeddings == null)
			{
				Throw.InvalidOperationException("Embedding generator returned a null collection of embeddings.");
			}
			if (generatedEmbeddings.Count != 1)
			{
				Throw.InvalidOperationException($"Expected the number of embeddings ({generatedEmbeddings.Count}) to match the number of inputs (1).");
			}
			TEmbedding val = generatedEmbeddings[0];
			if (val == null)
			{
				Throw.InvalidOperationException("Embedding generator generated a null embedding.");
			}
			return val;
		}

		public static async Task<(TInput Value, TEmbedding Embedding)[]> GenerateAndZipAsync<TInput, TEmbedding>(this IEmbeddingGenerator<TInput, TEmbedding> generator, IEnumerable<TInput> values, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken)) where TEmbedding : Embedding
		{
			Throw.IfNull(generator, "generator");
			Throw.IfNull(values, "values");
			IList<TInput> inputs = (values as IList<TInput>) ?? values.ToList();
			int inputsCount = inputs.Count;
			if (inputsCount == 0)
			{
				return Array.Empty<(TInput, TEmbedding)>();
			}
			GeneratedEmbeddings<TEmbedding> generatedEmbeddings = await generator.GenerateAsync(values, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (generatedEmbeddings.Count != inputsCount)
			{
				Throw.InvalidOperationException($"Expected the number of embeddings ({generatedEmbeddings.Count}) to match the number of inputs ({inputsCount}).");
			}
			(TInput, TEmbedding)[] array = new(TInput, TEmbedding)[generatedEmbeddings.Count];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = (inputs[i], generatedEmbeddings[i]);
			}
			return array;
		}
	}
	public class EmbeddingGeneratorMetadata
	{
		public string? ProviderName { get; }

		public Uri? ProviderUri { get; }

		public string? DefaultModelId { get; }

		public int? DefaultModelDimensions { get; }

		public EmbeddingGeneratorMetadata(string? providerName = null, Uri? providerUri = null, string? defaultModelId = null, int? defaultModelDimensions = null)
		{
			DefaultModelId = defaultModelId;
			ProviderName = providerName;
			ProviderUri = providerUri;
			DefaultModelDimensions = defaultModelDimensions;
		}
	}
	public sealed class Embedding<T> : Embedding
	{
		public ReadOnlyMemory<T> Vector { get; set; }

		[JsonIgnore]
		public override int Dimensions => Vector.Length;

		public Embedding(ReadOnlyMemory<T> vector)
		{
			Vector = vector;
		}
	}
	[DebuggerDisplay("Count = {Count}")]
	public sealed class GeneratedEmbeddings<TEmbedding> : IList<TEmbedding>, ICollection<TEmbedding>, IEnumerable<TEmbedding>, IEnumerable, IReadOnlyList<TEmbedding>, IReadOnlyCollection<TEmbedding> where TEmbedding : Embedding
	{
		private List<TEmbedding> _embeddings;

		public UsageDetails? Usage { get; set; }

		public AdditionalPropertiesDictionary? AdditionalProperties { get; set; }

		public TEmbedding this[int index]
		{
			get
			{
				return _embeddings[index];
			}
			set
			{
				_embeddings[index] = value;
			}
		}

		public int Count => _embeddings.Count;

		bool ICollection<TEmbedding>.IsReadOnly => false;

		public GeneratedEmbeddings()
		{
			_embeddings = new List<TEmbedding>();
		}

		public GeneratedEmbeddings(int capacity)
		{
			_embeddings = new List<TEmbedding>(Throw.IfLessThan(capacity, 0, "capacity"));
		}

		public GeneratedEmbeddings(IEnumerable<TEmbedding> embeddings)
		{
			_embeddings = new List<TEmbedding>(Throw.IfNull(embeddings, "embeddings"));
		}

		public void Add(TEmbedding item)
		{
			_embeddings.Add(item);
		}

		public void AddRange(IEnumerable<TEmbedding> items)
		{
			_embeddings.AddRange(items);
		}

		public void Clear()
		{
			_embeddings.Clear();
		}

		public bool Contains(TEmbedding item)
		{
			return _embeddings.Contains(item);
		}

		public void CopyTo(TEmbedding[] array, int arrayIndex)
		{
			_embeddings.CopyTo(array, arrayIndex);
		}

		public IEnumerator<TEmbedding> GetEnumerator()
		{
			return _embeddings.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public int IndexOf(TEmbedding item)
		{
			return _embeddings.IndexOf(item);
		}

		public void Insert(int index, TEmbedding item)
		{
			_embeddings.Insert(index, item);
		}

		public bool Remove(TEmbedding item)
		{
			return _embeddings.Remove(item);
		}

		public void RemoveAt(int index)
		{
			_embeddings.RemoveAt(index);
		}
	}
	public interface IEmbeddingGenerator : IDisposable
	{
		object? GetService(Type serviceType, object? serviceKey = null);
	}
	public interface IEmbeddingGenerator<in TInput, TEmbedding> : IEmbeddingGenerator, IDisposable where TEmbedding : Embedding
	{
		Task<GeneratedEmbeddings<TEmbedding>> GenerateAsync(IEnumerable<TInput> values, EmbeddingGenerationOptions? options = null, CancellationToken cancellationToken = default(CancellationToken));
	}
	public abstract class AIFunction : AIFunctionDeclaration
	{
		private sealed class NonInvocableAIFunction : DelegatingAIFunctionDeclaration
		{
			public NonInvocableAIFunction(AIFunction function)
				: base(function)
			{
			}
		}

		public virtual MethodInfo? UnderlyingMethod => null;

		public virtual JsonSerializerOptions JsonSerializerOptions => AIJsonUtilities.DefaultOptions;

		public ValueTask<object?> InvokeAsync(AIFunctionArguments? arguments = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return InvokeCoreAsync(arguments ?? new AIFunctionArguments(), cancellationToken);
		}

		protected abstract ValueTask<object?> InvokeCoreAsync(AIFunctionArguments arguments, CancellationToken cancellationToken);

		public AIFunctionDeclaration AsDeclarationOnly()
		{
			return new NonInvocableAIFunction(this);
		}
	}
	[DebuggerDisplay("Count = {Count}")]
	public class AIFunctionArguments : IDictionary<string, object?>, ICollection<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyDictionary<string, object?>, IReadOnlyCollection<KeyValuePair<string, object?>>
	{
		private readonly Dictionary<string, object?> _arguments;

		public IServiceProvider? Services { get; set; }

		public IDictionary<object, object?>? Context { get; set; }

		public object? this[string key]
		{
			get
			{
				return _arguments[key];
			}
			set
			{
				_arguments[key] = value;
			}
		}

		public ICollection<string> Keys => _arguments.Keys;

		public ICollection<object?> Values => _arguments.Values;

		public int Count => _arguments.Count;

		bool ICollection<KeyValuePair<string, object>>.IsReadOnly => false;

		IEnumerable<string> IReadOnlyDictionary<string, object>.Keys => Keys;

		IEnumerable<object?> IReadOnlyDictionary<string, object>.Values => Values;

		public AIFunctionArguments()
			: this(null, null)
		{
		}

		public AIFunctionArguments(IDictionary<string, object?>? arguments)
			: this(arguments, null)
		{
		}

		public AIFunctionArguments(IEqualityComparer<string>? comparer)
			: this(null, comparer)
		{
		}

		public AIFunctionArguments(IDictionary<string, object?>? arguments, IEqualityComparer<string>? comparer)
		{
			_arguments = ((arguments == null) ? new Dictionary<string, object>(comparer) : ((arguments is Dictionary<string, object> dictionary && (comparer == null || dictionary.Comparer == comparer)) ? dictionary : new Dictionary<string, object>(arguments, comparer)));
		}

		public void Add(string key, object? value)
		{
			_arguments.Add(key, value);
		}

		void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object?> item)
		{
			((ICollection<KeyValuePair<string, object>>)_arguments).Add(item);
		}

		public void Clear()
		{
			_arguments.Clear();
		}

		bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object?> item)
		{
			return ((ICollection<KeyValuePair<string, object>>)_arguments).Contains(item);
		}

		public bool ContainsKey(string key)
		{
			return _arguments.ContainsKey(key);
		}

		public void CopyTo(KeyValuePair<string, object?>[] array, int arrayIndex)
		{
			((ICollection<KeyValuePair<string, object>>)_arguments).CopyTo(array, arrayIndex);
		}

		public IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
		{
			return _arguments.GetEnumerator();
		}

		public bool Remove(string key)
		{
			return _arguments.Remove(key);
		}

		bool ICollection<KeyValuePair<string, object>>.Remove(KeyValuePair<string, object?> item)
		{
			return ((ICollection<KeyValuePair<string, object>>)_arguments).Remove(item);
		}

		public bool TryGetValue(string key, out object? value)
		{
			return _arguments.TryGetValue(key, out value);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public abstract class AIFunctionDeclaration : AITool
	{
		public virtual JsonElement JsonSchema => AIJsonUtilities.DefaultJsonSchema;

		public virtual JsonElement? ReturnJsonSchema => null;
	}
	public static class AIFunctionFactory
	{
		private sealed class DefaultAIFunctionDeclaration : AIFunctionDeclaration
		{
			[CompilerGenerated]
			private string <name>P;

			[CompilerGenerated]
			private string <description>P;

			[CompilerGenerated]
			private JsonElement <jsonSchema>P;

			[CompilerGenerated]
			private JsonElement? <returnJsonSchema>P;

			public override string Name => <name>P;

			public override string Description => <description>P;

			public override JsonElement JsonSchema => <jsonSchema>P;

			public override JsonElement? ReturnJsonSchema => <returnJsonSchema>P;

			public DefaultAIFunctionDeclaration(string name, string description, JsonElement jsonSchema, JsonElement? returnJsonSchema)
			{
				<name>P = name;
				<description>P = description;
				<jsonSchema>P = jsonSchema;
				<returnJsonSchema>P = returnJsonSchema;
				base..ctor();
			}
		}

		private sealed class ReflectionAIFunction : AIFunction
		{
			public ReflectionAIFunctionDescriptor FunctionDescriptor { get; }

			public object? Target { get; }

			public Func<AIFunctionArguments, object>? CreateInstanceFunc { get; }

			public override IReadOnlyDictionary<string, object?> AdditionalProperties { get; }

			public override string Name => FunctionDescriptor.Name;

			public override string Description => FunctionDescriptor.Description;

			public override MethodInfo UnderlyingMethod => FunctionDescriptor.Method;

			public override JsonElement JsonSchema => FunctionDescriptor.JsonSchema;

			public override JsonElement? ReturnJsonSchema => FunctionDescriptor.ReturnJsonSchema;

			public override JsonSerializerOptions JsonSerializerOptions => FunctionDescriptor.JsonSerializerOptions;

			public static ReflectionAIFunction Build(MethodInfo method, object? target, AIFunctionFactoryOptions options)
			{
				Throw.IfNull(method, "method");
				if (method.ContainsGenericParameters)
				{
					Throw.ArgumentException("method", "Open generic methods are not supported");
				}
				if (!method.IsStatic && target == null)
				{
					Throw.ArgumentNullException("target", "Target must not be null for an instance method.");
				}
				ReflectionAIFunctionDescriptor orCreate = ReflectionAIFunctionDescriptor.GetOrCreate(method, options);
				if (target == null && options.AdditionalProperties == null)
				{
					ReflectionAIFunctionDescriptor reflectionAIFunctionDescriptor = orCreate;
					return reflectionAIFunctionDescriptor.CachedDefaultInstance ?? (reflectionAIFunctionDescriptor.CachedDefaultInstance = new ReflectionAIFunction(orCreate, target, options));
				}
				return new ReflectionAIFunction(orCreate, target, options);
			}

			public static ReflectionAIFunction Build(MethodInfo method, Func<AIFunctionArguments, object> createInstanceFunc, AIFunctionFactoryOptions options)
			{
				Throw.IfNull(method, "method");
				Throw.IfNull(createInstanceFunc, "createInstanceFunc");
				if (method.ContainsGenericParameters)
				{
					Throw.ArgumentException("method", "Open generic methods are not supported");
				}
				if (method.IsStatic)
				{
					Throw.ArgumentException("method", "The method must be an instance method.");
				}
				return new ReflectionAIFunction(ReflectionAIFunctionDescriptor.GetOrCreate(method, options), createInstanceFunc, options);
			}

			private ReflectionAIFunction(ReflectionAIFunctionDescriptor functionDescriptor, object? target, AIFunctionFactoryOptions options)
			{
				FunctionDescriptor = functionDescriptor;
				Target = target;
				AdditionalProperties = options.AdditionalProperties ?? EmptyReadOnlyDictionary<string, object>.Instance;
			}

			private ReflectionAIFunction(ReflectionAIFunctionDescriptor functionDescriptor, Func<AIFunctionArguments, object> createInstanceFunc, AIFunctionFactoryOptions options)
			{
				FunctionDescriptor = functionDescriptor;
				CreateInstanceFunc = createInstanceFunc;
				AdditionalProperties = options.AdditionalProperties ?? EmptyReadOnlyDictionary<string, object>.Instance;
			}

			protected override async ValueTask<object?> InvokeCoreAsync(AIFunctionArguments arguments, CancellationToken cancellationToken)
			{
				bool disposeTarget = false;
				object target = Target;
				object result;
				try
				{
					Func<AIFunctionArguments, object> createInstanceFunc = CreateInstanceFunc;
					if (createInstanceFunc != null)
					{
						target = createInstanceFunc(arguments);
						if (target == null)
						{
							Throw.InvalidOperationException("Unable to create an instance of the target type.");
						}
						disposeTarget = true;
					}
					Func<AIFunctionArguments, CancellationToken, object>[] parameterMarshallers = FunctionDescriptor.ParameterMarshallers;
					object[] array = ((parameterMarshallers.Length != 0) ? new object[parameterMarshallers.Length] : Array.Empty<object>());
					for (int i = 0; i < array.Length; i++)
					{
						array[i] = parameterMarshallers[i](arguments, cancellationToken);
					}
					result = await FunctionDescriptor.ReturnParameterMarshaller(ReflectionInvoke(FunctionDescriptor.Method, target, array), cancellationToken).ConfigureAwait(continueOnCapturedContext: true);
				}
				finally
				{
					if (disposeTarget)
					{
						if (target is IAsyncDisposable asyncDisposable)
						{
							await asyncDisposable.DisposeAsync().ConfigureAwait(continueOnCapturedContext: true);
						}
						else if (target is IDisposable disposable)
						{
							disposable.Dispose();
						}
					}
				}
				return result;
			}
		}

		private sealed class ReflectionAIFunctionDescriptor
		{
			private record struct DescriptorKey(MethodInfo Method, string? Name, string? Description, Func<ParameterInfo, AIFunctionFactoryOptions.ParameterBindingOptions>? GetBindParameterOptions, Func<object?, Type?, CancellationToken, ValueTask<object?>>? MarshalResult, bool ExcludeResultSchema, AIJsonSchemaCreateOptions SchemaOptions);

			private const int InnerCacheSoftLimit = 512;

			private static readonly ConditionalWeakTable<JsonSerializerOptions, ConcurrentDictionary<DescriptorKey, ReflectionAIFunctionDescriptor>> _descriptorCache = new ConditionalWeakTable<JsonSerializerOptions, ConcurrentDictionary<DescriptorKey, ReflectionAIFunctionDescriptor>>();

			private static readonly object? _boxedDefaultCancellationToken = default(CancellationToken);

			private static readonly MethodInfo _taskGetResult = typeof(Task<>).GetProperty("Result", BindingFlags.Instance | BindingFlags.Public).GetMethod;

			private static readonly MethodInfo _valueTaskAsTask = typeof(ValueTask<>).GetMethod("AsTask", BindingFlags.Instance | BindingFlags.Public);

			public string Name { get; }

			public string Description { get; }

			public MethodInfo Method { get; }

			public JsonSerializerOptions JsonSerializerOptions { get; }

			public JsonElement JsonSchema { get; }

			public JsonElement? ReturnJsonSchema { get; }

			public Func<AIFunctionArguments, CancellationToken, object?>[] ParameterMarshallers { get; }

			public Func<object?, CancellationToken, ValueTask<object?>> ReturnParameterMarshaller { get; }

			public ReflectionAIFunction? CachedDefaultInstance { get; set; }

			public static ReflectionAIFunctionDescriptor GetOrCreate(MethodInfo method, AIFunctionFactoryOptions options)
			{
				JsonSerializerOptions jsonSerializerOptions = options.SerializerOptions ?? AIJsonUtilities.DefaultOptions;
				AIJsonSchemaCreateOptions schemaOptions = options.JsonSchemaCreateOptions ?? AIJsonSchemaCreateOptions.Default;
				jsonSerializerOptions.MakeReadOnly();
				ConcurrentDictionary<DescriptorKey, ReflectionAIFunctionDescriptor> orCreateValue = _descriptorCache.GetOrCreateValue(jsonSerializerOptions);
				DescriptorKey key = new DescriptorKey(method, options.Name, options.Description, options.ConfigureParameterBinding, options.MarshalResult, options.ExcludeResultSchema, schemaOptions);
				if (orCreateValue.TryGetValue(key, out var value))
				{
					return value;
				}
				value = new ReflectionAIFunctionDescriptor(key, jsonSerializerOptions);
				if (orCreateValue.Count >= 512)
				{
					return value;
				}
				return orCreateValue.GetOrAdd(key, value);
			}

			private ReflectionAIFunctionDescriptor(DescriptorKey key, JsonSerializerOptions serializerOptions)
			{
				ParameterInfo[] parameters = key.Method.GetParameters();
				Dictionary<ParameterInfo, AIFunctionFactoryOptions.ParameterBindingOptions> boundParameters = null;
				if (parameters.Length != 0 && key.GetBindParameterOptions != null)
				{
					boundParameters = new Dictionary<ParameterInfo, AIFunctionFactoryOptions.ParameterBindingOptions>(parameters.Length);
					for (int i = 0; i < parameters.Length; i++)
					{
						boundParameters[parameters[i]] = key.GetBindParameterOptions(parameters[i]);
					}
				}
				AIJsonSchemaCreateOptions inferenceOptions = key.SchemaOptions with
				{
					IncludeParameter = delegate(ParameterInfo parameterInfo)
					{
						if (parameterInfo.ParameterType == typeof(AIFunctionArguments) || parameterInfo.ParameterType == typeof(IServiceProvider))
						{
							return false;
						}
						AIFunctionFactoryOptions.ParameterBindingOptions value2 = default(AIFunctionFactoryOptions.ParameterBindingOptions);
						bool? flag = boundParameters?.TryGetValue(parameterInfo, out value2);
						return (!flag.HasValue || !flag.GetValueOrDefault() || !value2.ExcludeFromSchema) && (key.SchemaOptions.IncludeParameter?.Invoke(parameterInfo) ?? true);
					}
				};
				ParameterMarshallers = ((parameters.Length != 0) ? new Func<AIFunctionArguments, CancellationToken, object>[parameters.Length] : Array.Empty<Func<AIFunctionArguments, CancellationToken, object>>());
				AIFunctionFactoryOptions.ParameterBindingOptions value = default(AIFunctionFactoryOptions.ParameterBindingOptions);
				for (int j = 0; j < parameters.Length; j++)
				{
					if ((!(boundParameters?.TryGetValue(parameters[j], out value))) ?? true)
					{
						value = default(AIFunctionFactoryOptions.ParameterBindingOptions);
					}
					ParameterMarshallers[j] = GetParameterMarshaller(serializerOptions, value, parameters[j]);
				}
				ReturnParameterMarshaller = GetReturnParameterMarshaller(key, serializerOptions, out Type returnType);
				Method = key.Method;
				Name = key.Name ?? key.Method.GetCustomAttribute<DisplayNameAttribute>(inherit: true)?.DisplayName ?? GetFunctionName(key.Method);
				Description = key.Description ?? key.Method.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description ?? string.Empty;
				JsonSerializerOptions = serializerOptions;
				ReturnJsonSchema = (((object)returnType == null || key.ExcludeResultSchema) ? null : new JsonElement?(AIJsonUtilities.CreateJsonSchema(NormalizeReturnType(returnType, serializerOptions), key.Method.ReturnParameter.GetCustomAttribute<DescriptionAttribute>(inherit: true)?.Description, hasDefaultValue: false, null, serializerOptions, inferenceOptions)));
				JsonSchema = AIJsonUtilities.CreateFunctionJsonSchema(key.Method, string.Empty, string.Empty, serializerOptions, inferenceOptions);
			}

			private static string GetFunctionName(MethodInfo method)
			{
				string text = SanitizeMemberName(method.Name);
				if (IsAsyncMethod(method))
				{
					int num = text.LastIndexOf("Async", StringComparison.Ordinal);
					if (num > 0 && (num + "Async".Length == text.Length || (num + "Async".Length < text.Length && text[num + "Async".Length] == '_')))
					{
						text = text.Substring(0, num) + text.Substring(num + "Async".Length);
					}
				}
				return text;
				static bool IsAsyncMethod(MethodInfo method)
				{
					Type returnType = method.ReturnType;
					if (returnType == typeof(T

BepInEx/core/Microsoft.Extensions.AI.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Metrics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Numerics.Tensors;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Shared.Collections;
using Microsoft.Shared.Diagnostics;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Utilities for working with generative AI components.")]
[assembly: AssemblyFileVersion("10.100.125.61202")]
[assembly: AssemblyInformationalVersion("10.1.1+8a57aae6b42651573f06fd3904b9a0d1023f9aeb")]
[assembly: AssemblyProduct("Microsoft.Extensions.AI")]
[assembly: AssemblyTitle("Microsoft.Extensions.AI")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/extensions")]
[assembly: AssemblyVersion("10.1.0.0")]
[assembly: TypeForwardedTo(typeof(IChatReducer))]
[module: RefSafetyRules(11)]
[CompilerGenerated]
internal delegate TResult <>f__AnonymousDelegate0<T1, T2, TResult>(T1 arg1, T2 arg2 = default(T2));
[CompilerGenerated]
internal delegate TResult <>f__AnonymousDelegate1<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3 = default(T3));
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 ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection
{
	public static class ChatClientBuilderServiceCollectionExtensions
	{
		public static ChatClientBuilder AddChatClient(this IServiceCollection serviceCollection, IChatClient innerClient, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			IChatClient innerClient2 = innerClient;
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull<IChatClient>(innerClient2, "innerClient");
			return serviceCollection.AddChatClient((Func<IServiceProvider, IChatClient>)((IServiceProvider _) => innerClient2), lifetime);
		}

		public static ChatClientBuilder AddChatClient(this IServiceCollection serviceCollection, Func<IServiceProvider, IChatClient> innerClientFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull(innerClientFactory, "innerClientFactory");
			ChatClientBuilder chatClientBuilder = new ChatClientBuilder(innerClientFactory);
			serviceCollection.Add(new ServiceDescriptor(typeof(IChatClient), chatClientBuilder.Build, lifetime));
			return chatClientBuilder;
		}

		public static ChatClientBuilder AddKeyedChatClient(this IServiceCollection serviceCollection, object? serviceKey, IChatClient innerClient, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			IChatClient innerClient2 = innerClient;
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull<IChatClient>(innerClient2, "innerClient");
			return serviceCollection.AddKeyedChatClient(serviceKey, (Func<IServiceProvider, IChatClient>)((IServiceProvider _) => innerClient2), lifetime);
		}

		public static ChatClientBuilder AddKeyedChatClient(this IServiceCollection serviceCollection, object? serviceKey, Func<IServiceProvider, IChatClient> innerClientFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull(innerClientFactory, "innerClientFactory");
			ChatClientBuilder builder = new ChatClientBuilder(innerClientFactory);
			serviceCollection.Add(new ServiceDescriptor(typeof(IChatClient), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => builder.Build(services)), lifetime));
			return builder;
		}
	}
	public static class EmbeddingGeneratorBuilderServiceCollectionExtensions
	{
		public static EmbeddingGeneratorBuilder<TInput, TEmbedding> AddEmbeddingGenerator<TInput, TEmbedding>(this IServiceCollection serviceCollection, IEmbeddingGenerator<TInput, TEmbedding> innerGenerator, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TEmbedding : Embedding
		{
			IEmbeddingGenerator<TInput, TEmbedding> innerGenerator2 = innerGenerator;
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull<IEmbeddingGenerator<TInput, TEmbedding>>(innerGenerator2, "innerGenerator");
			return serviceCollection.AddEmbeddingGenerator((IServiceProvider _) => innerGenerator2, lifetime);
		}

		public static EmbeddingGeneratorBuilder<TInput, TEmbedding> AddEmbeddingGenerator<TInput, TEmbedding>(this IServiceCollection serviceCollection, Func<IServiceProvider, IEmbeddingGenerator<TInput, TEmbedding>> innerGeneratorFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TEmbedding : Embedding
		{
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull(innerGeneratorFactory, "innerGeneratorFactory");
			EmbeddingGeneratorBuilder<TInput, TEmbedding> embeddingGeneratorBuilder = new EmbeddingGeneratorBuilder<TInput, TEmbedding>(innerGeneratorFactory);
			serviceCollection.Add(new ServiceDescriptor(typeof(IEmbeddingGenerator<TInput, TEmbedding>), embeddingGeneratorBuilder.Build, lifetime));
			serviceCollection.Add(new ServiceDescriptor(typeof(IEmbeddingGenerator), (IServiceProvider services) => services.GetRequiredService<IEmbeddingGenerator<TInput, TEmbedding>>(), lifetime));
			return embeddingGeneratorBuilder;
		}

		public static EmbeddingGeneratorBuilder<TInput, TEmbedding> AddKeyedEmbeddingGenerator<TInput, TEmbedding>(this IServiceCollection serviceCollection, object? serviceKey, IEmbeddingGenerator<TInput, TEmbedding> innerGenerator, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TEmbedding : Embedding
		{
			IEmbeddingGenerator<TInput, TEmbedding> innerGenerator2 = innerGenerator;
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull<IEmbeddingGenerator<TInput, TEmbedding>>(innerGenerator2, "innerGenerator");
			return serviceCollection.AddKeyedEmbeddingGenerator(serviceKey, (IServiceProvider _) => innerGenerator2, lifetime);
		}

		public static EmbeddingGeneratorBuilder<TInput, TEmbedding> AddKeyedEmbeddingGenerator<TInput, TEmbedding>(this IServiceCollection serviceCollection, object? serviceKey, Func<IServiceProvider, IEmbeddingGenerator<TInput, TEmbedding>> innerGeneratorFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton) where TEmbedding : Embedding
		{
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull(innerGeneratorFactory, "innerGeneratorFactory");
			EmbeddingGeneratorBuilder<TInput, TEmbedding> builder = new EmbeddingGeneratorBuilder<TInput, TEmbedding>(innerGeneratorFactory);
			serviceCollection.Add(new ServiceDescriptor(typeof(IEmbeddingGenerator<TInput, TEmbedding>), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => builder.Build(services)), lifetime));
			serviceCollection.Add(new ServiceDescriptor(typeof(IEmbeddingGenerator), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => ServiceProviderKeyedServiceExtensions.GetRequiredKeyedService<IEmbeddingGenerator<TInput, TEmbedding>>(services, serviceKey)), lifetime));
			return builder;
		}
	}
	[Experimental("MEAI001")]
	public static class ImageGeneratorBuilderServiceCollectionExtensions
	{
		public static ImageGeneratorBuilder AddImageGenerator(this IServiceCollection serviceCollection, IImageGenerator innerGenerator, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			IImageGenerator innerGenerator2 = innerGenerator;
			return serviceCollection.AddImageGenerator((Func<IServiceProvider, IImageGenerator>)((IServiceProvider _) => innerGenerator2), lifetime);
		}

		public static ImageGeneratorBuilder AddImageGenerator(this IServiceCollection serviceCollection, Func<IServiceProvider, IImageGenerator> innerGeneratorFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull(innerGeneratorFactory, "innerGeneratorFactory");
			ImageGeneratorBuilder imageGeneratorBuilder = new ImageGeneratorBuilder(innerGeneratorFactory);
			serviceCollection.Add(new ServiceDescriptor(typeof(IImageGenerator), imageGeneratorBuilder.Build, lifetime));
			return imageGeneratorBuilder;
		}

		public static ImageGeneratorBuilder AddKeyedImageGenerator(this IServiceCollection serviceCollection, object? serviceKey, IImageGenerator innerGenerator, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			IImageGenerator innerGenerator2 = innerGenerator;
			return serviceCollection.AddKeyedImageGenerator(serviceKey, (Func<IServiceProvider, IImageGenerator>)((IServiceProvider _) => innerGenerator2), lifetime);
		}

		public static ImageGeneratorBuilder AddKeyedImageGenerator(this IServiceCollection serviceCollection, object? serviceKey, Func<IServiceProvider, IImageGenerator> innerGeneratorFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull(innerGeneratorFactory, "innerGeneratorFactory");
			ImageGeneratorBuilder builder = new ImageGeneratorBuilder(innerGeneratorFactory);
			serviceCollection.Add(new ServiceDescriptor(typeof(IImageGenerator), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => builder.Build(services)), lifetime));
			return builder;
		}
	}
	[Experimental("MEAI001")]
	public static class SpeechToTextClientBuilderServiceCollectionExtensions
	{
		public static SpeechToTextClientBuilder AddSpeechToTextClient(this IServiceCollection serviceCollection, ISpeechToTextClient innerClient, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			ISpeechToTextClient innerClient2 = innerClient;
			return serviceCollection.AddSpeechToTextClient((Func<IServiceProvider, ISpeechToTextClient>)((IServiceProvider _) => innerClient2), lifetime);
		}

		public static SpeechToTextClientBuilder AddSpeechToTextClient(this IServiceCollection serviceCollection, Func<IServiceProvider, ISpeechToTextClient> innerClientFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull(innerClientFactory, "innerClientFactory");
			SpeechToTextClientBuilder speechToTextClientBuilder = new SpeechToTextClientBuilder(innerClientFactory);
			serviceCollection.Add(new ServiceDescriptor(typeof(ISpeechToTextClient), speechToTextClientBuilder.Build, lifetime));
			return speechToTextClientBuilder;
		}

		public static SpeechToTextClientBuilder AddKeyedSpeechToTextClient(this IServiceCollection serviceCollection, object? serviceKey, ISpeechToTextClient innerClient, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			ISpeechToTextClient innerClient2 = innerClient;
			return serviceCollection.AddKeyedSpeechToTextClient(serviceKey, (Func<IServiceProvider, ISpeechToTextClient>)((IServiceProvider _) => innerClient2), lifetime);
		}

		public static SpeechToTextClientBuilder AddKeyedSpeechToTextClient(this IServiceCollection serviceCollection, object? serviceKey, Func<IServiceProvider, ISpeechToTextClient> innerClientFactory, ServiceLifetime lifetime = ServiceLifetime.Singleton)
		{
			Throw.IfNull(serviceCollection, "serviceCollection");
			Throw.IfNull(innerClientFactory, "innerClientFactory");
			SpeechToTextClientBuilder builder = new SpeechToTextClientBuilder(innerClientFactory);
			serviceCollection.Add(new ServiceDescriptor(typeof(ISpeechToTextClient), serviceKey, (Func<IServiceProvider, object, object>)((IServiceProvider services, object? serviceKey) => builder.Build(services)), lifetime));
			return builder;
		}
	}
}
namespace Microsoft.Extensions.AI
{
	internal sealed class AnonymousDelegatingChatClient : DelegatingChatClient
	{
		private readonly Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, Task<ChatResponse>>? _getResponseFunc;

		private readonly Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, IAsyncEnumerable<ChatResponseUpdate>>? _getStreamingResponseFunc;

		private readonly Func<IEnumerable<ChatMessage>, ChatOptions?, Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, Task>, CancellationToken, Task>? _sharedFunc;

		public AnonymousDelegatingChatClient(IChatClient innerClient, Func<IEnumerable<ChatMessage>, ChatOptions?, Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, Task>, CancellationToken, Task> sharedFunc)
			: base(innerClient)
		{
			Throw.IfNull(sharedFunc, "sharedFunc");
			_sharedFunc = sharedFunc;
		}

		public AnonymousDelegatingChatClient(IChatClient innerClient, Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, Task<ChatResponse>>? getResponseFunc, Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, IAsyncEnumerable<ChatResponseUpdate>>? getStreamingResponseFunc)
			: base(innerClient)
		{
			ThrowIfBothDelegatesNull(getResponseFunc, getStreamingResponseFunc);
			_getResponseFunc = getResponseFunc;
			_getStreamingResponseFunc = getStreamingResponseFunc;
		}

		public override Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(messages, "messages");
			if (_sharedFunc != null)
			{
				return GetResponseViaSharedAsync(messages, options, cancellationToken);
			}
			if (_getResponseFunc != null)
			{
				return _getResponseFunc(messages, options, ((DelegatingChatClient)this).InnerClient, cancellationToken);
			}
			return ChatResponseExtensions.ToChatResponseAsync(_getStreamingResponseFunc(messages, options, ((DelegatingChatClient)this).InnerClient, cancellationToken), cancellationToken);
			async Task<ChatResponse> GetResponseViaSharedAsync(IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken)
			{
				ChatResponse response = null;
				await _sharedFunc(messages, options, async delegate(IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken)
				{
					response = await ((DelegatingChatClient)this).InnerClient.GetResponseAsync(messages, options, cancellationToken);
				}, cancellationToken);
				if (response == null)
				{
					Throw.InvalidOperationException("The wrapper completed successfully without producing a ChatResponse.");
				}
				return response;
			}
		}

		public override IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			IEnumerable<ChatMessage> messages2 = messages;
			ChatOptions options2 = options;
			Throw.IfNull(messages2, "messages");
			Channel<ChatResponseUpdate> updates;
			if (_sharedFunc != null)
			{
				updates = Channel.CreateBounded<ChatResponseUpdate>(1);
				ProcessAsync();
				return ReadAllAsync((Channel<ChatResponseUpdate, ChatResponseUpdate>)updates, cancellationToken);
			}
			if (_getStreamingResponseFunc != null)
			{
				return _getStreamingResponseFunc(messages2, options2, ((DelegatingChatClient)this).InnerClient, cancellationToken);
			}
			return GetStreamingResponseAsyncViaGetResponseAsync(_getResponseFunc(messages2, options2, ((DelegatingChatClient)this).InnerClient, cancellationToken));
			static async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsyncViaGetResponseAsync(Task<ChatResponse> task)
			{
				ChatResponseUpdate[] array = (await task).ToChatResponseUpdates();
				for (int i = 0; i < array.Length; i++)
				{
					yield return array[i];
				}
			}
			async Task ProcessAsync()
			{
				Exception error = null;
				try
				{
					await _sharedFunc(messages2, options2, async delegate(IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken)
					{
						await foreach (ChatResponseUpdate item2 in ((DelegatingChatClient)this).InnerClient.GetStreamingResponseAsync(messages, options, cancellationToken))
						{
							await updates.Writer.WriteAsync(item2, cancellationToken);
						}
					}, cancellationToken);
				}
				catch (Exception ex)
				{
					error = ex;
					throw;
				}
				finally
				{
					updates.Writer.TryComplete(error);
				}
			}
			static async IAsyncEnumerable<ChatResponseUpdate> ReadAllAsync(ChannelReader<ChatResponseUpdate> channel, [EnumeratorCancellation] CancellationToken cancellationToken)
			{
				while (await channel.WaitToReadAsync(cancellationToken))
				{
					ChatResponseUpdate item;
					while (channel.TryRead(out item))
					{
						yield return item;
					}
				}
			}
		}

		internal static void ThrowIfBothDelegatesNull(object? getResponseFunc, object? getStreamingResponseFunc)
		{
			if (getResponseFunc == null && getStreamingResponseFunc == null)
			{
				Throw.ArgumentNullException("getResponseFunc", "At least one of the getResponseFunc or getStreamingResponseFunc delegates must be non-null.");
			}
		}
	}
	public abstract class CachingChatClient : DelegatingChatClient
	{
		[CompilerGenerated]
		private sealed class <GetCachedStreamingResponseAsync>d__10 : IAsyncEnumerable<ChatResponseUpdate>, IAsyncEnumerator<ChatResponseUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private ChatResponseUpdate <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			public CachingChatClient <>4__this;

			private IEnumerable<ChatMessage> messages;

			public IEnumerable<ChatMessage> <>3__messages;

			private ChatOptions options;

			public ChatOptions <>3__options;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private string <cacheKey>5__2;

			private TaskAwaiter<ChatResponse?> <>u__1;

			private ChatResponseUpdate[] <>7__wrap2;

			private int <>7__wrap3;

			private List<ChatResponseUpdate> <capturedItems>5__5;

			private IAsyncEnumerator<ChatResponseUpdate> <>7__wrap5;

			private object <>7__wrap6;

			private ValueTaskAwaiter<bool> <>u__2;

			private ValueTaskAwaiter <>u__3;

			private TaskAwaiter <>u__4;

			private TaskAwaiter<IReadOnlyList<ChatResponseUpdate>?> <>u__5;

			private string <conversationId>5__8;

			private IEnumerator<ChatResponseUpdate> <>7__wrap8;

			ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetCachedStreamingResponseAsync>d__10(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				CachingChatClient cachingChatClient = <>4__this;
				try
				{
					TaskAwaiter<ChatResponse> awaiter6;
					TaskAwaiter<IReadOnlyList<ChatResponseUpdate>> awaiter3;
					ValueTaskAwaiter awaiter5;
					TaskAwaiter awaiter4;
					ValueTaskAwaiter awaiter2;
					TaskAwaiter awaiter;
					object obj;
					ChatResponse result;
					ChatResponse val;
					IReadOnlyList<ChatResponseUpdate> result2;
					IReadOnlyList<ChatResponseUpdate> readOnlyList;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							if (cachingChatClient.CoalesceStreamingUpdates)
							{
								<cacheKey>5__2 = cachingChatClient.GetCacheKey(messages, options, new ReadOnlySpan<object>(new object[1] { _boxedTrue }));
								<>2__current = null;
								awaiter6 = cachingChatClient.ReadCacheAsync(<cacheKey>5__2, cancellationToken).GetAwaiter();
								if (!awaiter6.IsCompleted)
								{
									num = (<>1__state = 0);
									<>u__1 = awaiter6;
									<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter6, ref stateMachine);
									return;
								}
								goto IL_010d;
							}
							<cacheKey>5__2 = cachingChatClient.GetCacheKey(messages, options, new ReadOnlySpan<object>(new object[1] { _boxedTrue }));
							<>2__current = null;
							awaiter3 = cachingChatClient.ReadCacheStreamingAsync(<cacheKey>5__2, cancellationToken).GetAwaiter();
							if (!awaiter3.IsCompleted)
							{
								num = (<>1__state = 4);
								<>u__5 = awaiter3;
								<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine);
								return;
							}
							goto IL_04aa;
						}
						goto end_IL_000e;
					case 0:
						awaiter6 = <>u__1;
						<>u__1 = default(TaskAwaiter<ChatResponse>);
						num = (<>1__state = -1);
						goto IL_010d;
					case -4:
						num = (<>1__state = -1);
						if (!<>w__disposeMode)
						{
							<>7__wrap3++;
							goto IL_0179;
						}
						goto end_IL_000e;
					case -5:
					case 1:
						try
						{
							ValueTaskAwaiter<bool> awaiter7;
							if (num != -5)
							{
								if (num != 1)
								{
									goto IL_0231;
								}
								awaiter7 = <>u__2;
								<>u__2 = default(ValueTaskAwaiter<bool>);
								num = (<>1__state = -1);
								goto IL_029c;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_0231;
							}
							goto end_IL_01dc;
							IL_0231:
							<>2__current = null;
							awaiter7 = <>7__wrap5.MoveNextAsync().GetAwaiter();
							if (!awaiter7.IsCompleted)
							{
								num = (<>1__state = 1);
								<>u__2 = awaiter7;
								<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter7, ref stateMachine);
								return;
							}
							goto IL_029c;
							IL_029c:
							if (awaiter7.GetResult())
							{
								ChatResponseUpdate current2 = <>7__wrap5.Current;
								<capturedItems>5__5.Add(current2);
								<>2__current = current2;
								num = (<>1__state = -5);
								goto IL_08c7;
							}
							end_IL_01dc:;
						}
						catch (object obj2)
						{
							<>7__wrap6 = obj2;
						}
						if (<>7__wrap5 != null)
						{
							<>2__current = null;
							awaiter5 = <>7__wrap5.DisposeAsync().GetAwaiter();
							if (!awaiter5.IsCompleted)
							{
								num = (<>1__state = 2);
								<>u__3 = awaiter5;
								<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter5, ref stateMachine);
								return;
							}
							goto IL_032d;
						}
						goto IL_0334;
					case 2:
						awaiter5 = <>u__3;
						<>u__3 = default(ValueTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_032d;
					case 3:
						awaiter4 = <>u__4;
						<>u__4 = default(TaskAwaiter);
						num = (<>1__state = -1);
						goto IL_03f7;
					case 4:
						awaiter3 = <>u__5;
						<>u__5 = default(TaskAwaiter<IReadOnlyList<ChatResponseUpdate>>);
						num = (<>1__state = -1);
						goto IL_04aa;
					case -6:
						try
						{
							if (num != -6)
							{
								goto IL_0524;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_0524;
							}
							goto end_IL_04d3;
							IL_0524:
							if (<>7__wrap8.MoveNext())
							{
								ChatResponseUpdate current = <>7__wrap8.Current;
								if (<conversationId>5__8 == null)
								{
									<conversationId>5__8 = current.ConversationId;
								}
								<>2__current = current;
								num = (<>1__state = -6);
								goto IL_08c7;
							}
							end_IL_04d3:;
						}
						finally
						{
							if (num == -1 && <>7__wrap8 != null)
							{
								<>7__wrap8.Dispose();
							}
						}
						if (!<>w__disposeMode)
						{
							<>7__wrap8 = null;
							<conversationId>5__8 = null;
							break;
						}
						goto end_IL_000e;
					case -7:
					case 5:
						try
						{
							ValueTaskAwaiter<bool> awaiter8;
							if (num != -7)
							{
								if (num != 5)
								{
									goto IL_0607;
								}
								awaiter8 = <>u__2;
								<>u__2 = default(ValueTaskAwaiter<bool>);
								num = (<>1__state = -1);
								goto IL_0672;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_0607;
							}
							goto end_IL_05b2;
							IL_0607:
							<>2__current = null;
							awaiter8 = <>7__wrap5.MoveNextAsync().GetAwaiter();
							if (!awaiter8.IsCompleted)
							{
								num = (<>1__state = 5);
								<>u__2 = awaiter8;
								<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter8, ref stateMachine);
								return;
							}
							goto IL_0672;
							IL_0672:
							if (awaiter8.GetResult())
							{
								ChatResponseUpdate current3 = <>7__wrap5.Current;
								<capturedItems>5__5.Add(current3);
								<>2__current = current3;
								num = (<>1__state = -7);
								goto IL_08c7;
							}
							end_IL_05b2:;
						}
						catch (object obj2)
						{
							<>7__wrap6 = obj2;
						}
						if (<>7__wrap5 != null)
						{
							<>2__current = null;
							awaiter2 = <>7__wrap5.DisposeAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 6);
								<>u__3 = awaiter2;
								<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_0703;
						}
						goto IL_070a;
					case 6:
						awaiter2 = <>u__3;
						<>u__3 = default(ValueTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_0703;
					case 7:
						{
							awaiter = <>u__4;
							<>u__4 = default(TaskAwaiter);
							num = (<>1__state = -1);
							goto IL_07c8;
						}
						IL_070a:
						obj = <>7__wrap6;
						if (obj != null)
						{
							if (!(obj is Exception source))
							{
								throw obj;
							}
							ExceptionDispatchInfo.Capture(source).Throw();
						}
						_ = <>7__wrap3;
						if (!<>w__disposeMode)
						{
							<>7__wrap6 = null;
							<>7__wrap5 = null;
							<>2__current = null;
							awaiter = cachingChatClient.WriteCacheStreamingAsync(<cacheKey>5__2, <capturedItems>5__5, cancellationToken).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 7);
								<>u__4 = awaiter;
								<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
								return;
							}
							goto IL_07c8;
						}
						goto end_IL_000e;
						IL_032d:
						awaiter5.GetResult();
						goto IL_0334;
						IL_0334:
						obj = <>7__wrap6;
						if (obj != null)
						{
							if (!(obj is Exception source2))
							{
								throw obj;
							}
							ExceptionDispatchInfo.Capture(source2).Throw();
						}
						_ = <>7__wrap3;
						if (!<>w__disposeMode)
						{
							<>7__wrap6 = null;
							<>7__wrap5 = null;
							<>2__current = null;
							awaiter4 = cachingChatClient.WriteCacheAsync(<cacheKey>5__2, ChatResponseExtensions.ToChatResponse((IEnumerable<ChatResponseUpdate>)<capturedItems>5__5), cancellationToken).GetAwaiter();
							if (!awaiter4.IsCompleted)
							{
								num = (<>1__state = 3);
								<>u__4 = awaiter4;
								<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter4, ref stateMachine);
								return;
							}
							goto IL_03f7;
						}
						goto end_IL_000e;
						IL_010d:
						result = awaiter6.GetResult();
						val = result;
						if (val != null)
						{
							<>7__wrap2 = val.ToChatResponseUpdates();
							<>7__wrap3 = 0;
							goto IL_0179;
						}
						<capturedItems>5__5 = new List<ChatResponseUpdate>();
						<>7__wrap5 = cachingChatClient.<>n__1(messages, options, cancellationToken).GetAsyncEnumerator();
						<>7__wrap6 = null;
						<>7__wrap3 = 0;
						goto case -5;
						IL_04aa:
						result2 = awaiter3.GetResult();
						readOnlyList = result2;
						if (readOnlyList != null)
						{
							<conversationId>5__8 = null;
							<>7__wrap8 = readOnlyList.GetEnumerator();
							goto case -6;
						}
						<capturedItems>5__5 = new List<ChatResponseUpdate>();
						<>7__wrap5 = cachingChatClient.<>n__1(messages, options, cancellationToken).GetAsyncEnumerator();
						<>7__wrap6 = null;
						<>7__wrap3 = 0;
						goto case -7;
						IL_0179:
						if (<>7__wrap3 < <>7__wrap2.Length)
						{
							ChatResponseUpdate val2 = <>7__wrap2[<>7__wrap3];
							<>2__current = val2;
							num = (<>1__state = -4);
							goto IL_08c7;
						}
						<>7__wrap2 = null;
						goto IL_0405;
						IL_0703:
						awaiter2.GetResult();
						goto IL_070a;
						IL_03f7:
						awaiter4.GetResult();
						<capturedItems>5__5 = null;
						goto IL_0405;
						IL_07c8:
						awaiter.GetResult();
						<capturedItems>5__5 = null;
						break;
						IL_0405:
						<cacheKey>5__2 = null;
						goto end_IL_000e;
					}
					<cacheKey>5__2 = null;
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<cacheKey>5__2 = null;
					<>7__wrap2 = null;
					<capturedItems>5__5 = null;
					<>7__wrap5 = null;
					<>7__wrap6 = null;
					<conversationId>5__8 = null;
					<>7__wrap8 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<cacheKey>5__2 = null;
				<>7__wrap2 = null;
				<capturedItems>5__5 = null;
				<>7__wrap5 = null;
				<>7__wrap6 = null;
				<conversationId>5__8 = null;
				<>7__wrap8 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_08c7:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<ChatResponseUpdate> IAsyncEnumerable<ChatResponseUpdate>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<GetCachedStreamingResponseAsync>d__10 <GetCachedStreamingResponseAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<GetCachedStreamingResponseAsync>d__ = this;
				}
				else
				{
					<GetCachedStreamingResponseAsync>d__ = new <GetCachedStreamingResponseAsync>d__10(-3)
					{
						<>4__this = <>4__this
					};
				}
				<GetCachedStreamingResponseAsync>d__.messages = <>3__messages;
				<GetCachedStreamingResponseAsync>d__.options = <>3__options;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<GetCachedStreamingResponseAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<GetCachedStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<GetCachedStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <GetCachedStreamingResponseAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<GetCachedStreamingResponseAsync>d__10 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		private static readonly object _boxedTrue = true;

		private static readonly object _boxedFalse = false;

		public bool CoalesceStreamingUpdates { get; set; } = true;


		protected CachingChatClient(IChatClient innerClient)
			: base(innerClient)
		{
		}

		public override Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(messages, "messages");
			if (!EnableCaching(messages, options))
			{
				return ((DelegatingChatClient)this).GetResponseAsync(messages, options, cancellationToken);
			}
			return GetCachedResponseAsync(messages, options, cancellationToken);
		}

		private async Task<ChatResponse> GetCachedResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			string cacheKey = GetCacheKey(messages, options, new ReadOnlySpan<object>(new object[1] { _boxedFalse }));
			ChatResponse result = await ReadCacheAsync(cacheKey, cancellationToken);
			if (result == null)
			{
				result = await <>n__0(messages, options, cancellationToken);
				await WriteCacheAsync(cacheKey, result, cancellationToken);
			}
			return result;
		}

		public override IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(messages, "messages");
			if (!EnableCaching(messages, options))
			{
				return ((DelegatingChatClient)this).GetStreamingResponseAsync(messages, options, cancellationToken);
			}
			return GetCachedStreamingResponseAsync(messages, options, cancellationToken);
		}

		[AsyncIteratorStateMachine(typeof(<GetCachedStreamingResponseAsync>d__10))]
		private IAsyncEnumerable<ChatResponseUpdate> GetCachedStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			return new <GetCachedStreamingResponseAsync>d__10(-2)
			{
				<>4__this = this,
				<>3__messages = messages,
				<>3__options = options,
				<>3__cancellationToken = cancellationToken
			};
		}

		protected abstract string GetCacheKey(IEnumerable<ChatMessage> messages, ChatOptions? options, [ParamCollection] scoped ReadOnlySpan<object?> additionalValues);

		protected abstract Task<ChatResponse?> ReadCacheAsync(string key, CancellationToken cancellationToken);

		protected abstract Task<IReadOnlyList<ChatResponseUpdate>?> ReadCacheStreamingAsync(string key, CancellationToken cancellationToken);

		protected abstract Task WriteCacheAsync(string key, ChatResponse value, CancellationToken cancellationToken);

		protected abstract Task WriteCacheStreamingAsync(string key, IReadOnlyList<ChatResponseUpdate> value, CancellationToken cancellationToken);

		protected virtual bool EnableCaching(IEnumerable<ChatMessage> messages, ChatOptions? options)
		{
			return ((options != null) ? options.ConversationId : null) == null;
		}

		[CompilerGenerated]
		[DebuggerHidden]
		private Task<ChatResponse> <>n__0(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ((DelegatingChatClient)this).GetResponseAsync(messages, options, cancellationToken);
		}

		[CompilerGenerated]
		[DebuggerHidden]
		private IAsyncEnumerable<ChatResponseUpdate> <>n__1(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ((DelegatingChatClient)this).GetStreamingResponseAsync(messages, options, cancellationToken);
		}
	}
	public sealed class ChatClientBuilder
	{
		private readonly Func<IServiceProvider, IChatClient> _innerClientFactory;

		private List<Func<IChatClient, IServiceProvider, IChatClient>>? _clientFactories;

		public ChatClientBuilder(IChatClient innerClient)
		{
			IChatClient innerClient2 = innerClient;
			base..ctor();
			Throw.IfNull<IChatClient>(innerClient2, "innerClient");
			_innerClientFactory = (IServiceProvider _) => innerClient2;
		}

		public ChatClientBuilder(Func<IServiceProvider, IChatClient> innerClientFactory)
		{
			_innerClientFactory = Throw.IfNull(innerClientFactory, "innerClientFactory");
		}

		public IChatClient Build(IServiceProvider? services = null)
		{
			if (services == null)
			{
				services = EmptyServiceProvider.Instance;
			}
			IChatClient val = _innerClientFactory(services);
			if (_clientFactories != null)
			{
				for (int num = _clientFactories.Count - 1; num >= 0; num--)
				{
					val = _clientFactories[num](val, services);
					if (val == null)
					{
						Throw.InvalidOperationException(string.Format("The {0} entry at index {1} returned null. ", "ChatClientBuilder", num) + "Ensure that the callbacks passed to Use return non-null IChatClient instances.");
					}
				}
			}
			return val;
		}

		public ChatClientBuilder Use(Func<IChatClient, IChatClient> clientFactory)
		{
			Func<IChatClient, IChatClient> clientFactory2 = clientFactory;
			Throw.IfNull(clientFactory2, "clientFactory");
			return Use((IChatClient innerClient, IServiceProvider _) => clientFactory2(innerClient));
		}

		public ChatClientBuilder Use(Func<IChatClient, IServiceProvider, IChatClient> clientFactory)
		{
			Throw.IfNull(clientFactory, "clientFactory");
			(_clientFactories ?? (_clientFactories = new List<Func<IChatClient, IServiceProvider, IChatClient>>())).Add(clientFactory);
			return this;
		}

		public ChatClientBuilder Use(Func<IEnumerable<ChatMessage>, ChatOptions?, Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, Task>, CancellationToken, Task> sharedFunc)
		{
			Func<IEnumerable<ChatMessage>, ChatOptions?, Func<IEnumerable<ChatMessage>, ChatOptions?, CancellationToken, Task>, CancellationToken, Task> sharedFunc2 = sharedFunc;
			Throw.IfNull(sharedFunc2, "sharedFunc");
			return Use((IChatClient innerClient, IServiceProvider _) => (IChatClient)(object)new AnonymousDelegatingChatClient(innerClient, sharedFunc2));
		}

		public ChatClientBuilder Use(Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, Task<ChatResponse>>? getResponseFunc, Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, IAsyncEnumerable<ChatResponseUpdate>>? getStreamingResponseFunc)
		{
			Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, Task<ChatResponse>> getResponseFunc2 = getResponseFunc;
			Func<IEnumerable<ChatMessage>, ChatOptions?, IChatClient, CancellationToken, IAsyncEnumerable<ChatResponseUpdate>> getStreamingResponseFunc2 = getStreamingResponseFunc;
			AnonymousDelegatingChatClient.ThrowIfBothDelegatesNull(getResponseFunc2, getStreamingResponseFunc2);
			return Use((IChatClient innerClient, IServiceProvider _) => (IChatClient)(object)new AnonymousDelegatingChatClient(innerClient, getResponseFunc2, getStreamingResponseFunc2));
		}
	}
	public static class ChatClientBuilderChatClientExtensions
	{
		public static ChatClientBuilder AsBuilder(this IChatClient innerClient)
		{
			Throw.IfNull<IChatClient>(innerClient, "innerClient");
			return new ChatClientBuilder(innerClient);
		}
	}
	public static class ChatClientStructuredOutputExtensions
	{
		public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, IEnumerable<ChatMessage> messages, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return chatClient.GetResponseAsync<T>(messages, AIJsonUtilities.DefaultOptions, options, useJsonSchemaResponseFormat, cancellationToken);
		}

		public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, string chatMessage, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			//IL_0001: 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_0015: Expected O, but got Unknown
			return chatClient.GetResponseAsync<T>(new ChatMessage(ChatRole.User, chatMessage), options, useJsonSchemaResponseFormat, cancellationToken);
		}

		public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, ChatMessage chatMessage, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return chatClient.GetResponseAsync<T>((IEnumerable<ChatMessage>)new <>z__ReadOnlySingleElementList<ChatMessage>(chatMessage), options, useJsonSchemaResponseFormat, cancellationToken);
		}

		public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, string chatMessage, JsonSerializerOptions serializerOptions, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			//IL_0001: 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_0017: Expected O, but got Unknown
			return chatClient.GetResponseAsync<T>(new ChatMessage(ChatRole.User, chatMessage), serializerOptions, options, useJsonSchemaResponseFormat, cancellationToken);
		}

		public static Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, ChatMessage chatMessage, JsonSerializerOptions serializerOptions, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return chatClient.GetResponseAsync<T>((IEnumerable<ChatMessage>)new <>z__ReadOnlySingleElementList<ChatMessage>(chatMessage), serializerOptions, options, useJsonSchemaResponseFormat, cancellationToken);
		}

		public static async Task<ChatResponse<T>> GetResponseAsync<T>(this IChatClient chatClient, IEnumerable<ChatMessage> messages, JsonSerializerOptions serializerOptions, ChatOptions? options = null, bool? useJsonSchemaResponseFormat = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull<IChatClient>(chatClient, "chatClient");
			Throw.IfNull(messages, "messages");
			Throw.IfNull(serializerOptions, "serializerOptions");
			serializerOptions.MakeReadOnly();
			ChatResponseFormatJson val = ChatResponseFormat.ForJsonSchema<T>(serializerOptions, (string)null, (string)null);
			JsonElement value = val.Schema.Value;
			bool isWrappedInObject = false;
			if (!SchemaRepresentsObject(value))
			{
				isWrappedInObject = true;
				JsonObject jsonObject = new JsonObject();
				jsonObject.Add("$schema", "https://json-schema.org/draft/2020-12/schema");
				jsonObject.Add("type", "object");
				jsonObject.Add("properties", new JsonObject { 
				{
					"data",
					JsonElementToJsonNode(value)
				} });
				jsonObject.Add("additionalProperties", (JsonNode)false);
				jsonObject.Add("required", new JsonArray(new ReadOnlySpan<JsonNode>(new JsonNode[1] { "data" })));
				value = JsonSerializer.SerializeToElement((object)jsonObject, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonObject)));
				val = ChatResponseFormat.ForJsonSchema(value, val.SchemaName, val.SchemaDescription);
			}
			options = (ChatOptions?)((options != null) ? ((object)options.Clone()) : ((object)new ChatOptions()));
			if (useJsonSchemaResponseFormat.GetValueOrDefault(true))
			{
				options.ResponseFormat = (ChatResponseFormat)(object)val;
			}
			else
			{
				options.ResponseFormat = (ChatResponseFormat)(object)ChatResponseFormat.Json;
				ChatMessage item = new ChatMessage(ChatRole.User, $"Respond with a JSON value conforming to the following schema:\r\n```\r\n{val.Schema}\r\n```");
				List<ChatMessage> list = new List<ChatMessage>();
				list.AddRange(messages);
				list.Add(item);
				messages = new <>z__ReadOnlyList<ChatMessage>(list);
			}
			return new ChatResponse<T>(await chatClient.GetResponseAsync(messages, options, cancellationToken), serializerOptions)
			{
				IsWrappedInObject = isWrappedInObject
			};
			static JsonNode? JsonElementToJsonNode(JsonElement element)
			{
				return element.ValueKind switch
				{
					JsonValueKind.Null => null, 
					JsonValueKind.Array => JsonArray.Create(element), 
					JsonValueKind.Object => JsonObject.Create(element), 
					_ => JsonValue.Create(element), 
				};
			}
			static bool SchemaRepresentsObject(JsonElement schemaElement)
			{
				if (schemaElement.ValueKind == JsonValueKind.Object)
				{
					foreach (JsonProperty item2 in schemaElement.EnumerateObject())
					{
						if (item2.NameEquals("type"u8))
						{
							return item2.Value.ValueKind == JsonValueKind.String && item2.Value.ValueEquals("object"u8);
						}
					}
				}
				return false;
			}
		}
	}
	public class ChatResponse<T> : ChatResponse
	{
		private enum FailureReason
		{
			ResultDidNotContainJson,
			DeserializationProducedNull,
			ResultDidNotContainDataProperty
		}

		private static readonly JsonReaderOptions _allowMultipleValuesJsonReaderOptions = new JsonReaderOptions
		{
			AllowMultipleValues = true
		};

		private readonly JsonSerializerOptions _serializerOptions;

		private T? _deserializedResult;

		private bool _hasDeserializedResult;

		public T Result
		{
			get
			{
				FailureReason? failureReason;
				T resultCore = GetResultCore(out failureReason);
				return failureReason switch
				{
					FailureReason.ResultDidNotContainJson => throw new InvalidOperationException("The response did not contain JSON to be deserialized."), 
					FailureReason.DeserializationProducedNull => throw new InvalidOperationException("The deserialized response is null."), 
					FailureReason.ResultDidNotContainDataProperty => throw new InvalidOperationException("The response did not contain the expected 'data' property."), 
					_ => resultCore, 
				};
			}
		}

		internal bool IsWrappedInObject { get; set; }

		public ChatResponse(ChatResponse response, JsonSerializerOptions serializerOptions)
			: base(Throw.IfNull<ChatResponse>(response, "response").Messages)
		{
			_serializerOptions = Throw.IfNull(serializerOptions, "serializerOptions");
			((ChatResponse)this).AdditionalProperties = response.AdditionalProperties;
			((ChatResponse)this).ConversationId = response.ConversationId;
			((ChatResponse)this).CreatedAt = response.CreatedAt;
			((ChatResponse)this).FinishReason = response.FinishReason;
			((ChatResponse)this).ModelId = response.ModelId;
			((ChatResponse)this).RawRepresentation = response.RawRepresentation;
			((ChatResponse)this).ResponseId = response.ResponseId;
			((ChatResponse)this).Usage = response.Usage;
		}

		public bool TryGetResult([NotNullWhen(true)] out T? result)
		{
			try
			{
				result = GetResultCore(out var failureReason);
				return !failureReason.HasValue;
			}
			catch
			{
				result = default(T);
				return false;
			}
		}

		private static T? DeserializeFirstTopLevelObject(string json, JsonTypeInfo<T> typeInfo)
		{
			int byteCount = Encoding.UTF8.GetByteCount(json);
			byte[] array = ArrayPool<byte>.Shared.Rent(byteCount);
			try
			{
				int bytes = Encoding.UTF8.GetBytes(json, 0, json.Length, array, 0);
				ReadOnlySpan<byte> jsonData = new ReadOnlySpan<byte>(array, 0, bytes);
				Utf8JsonReader reader = new Utf8JsonReader(jsonData, _allowMultipleValuesJsonReaderOptions);
				return JsonSerializer.Deserialize(ref reader, typeInfo);
			}
			finally
			{
				ArrayPool<byte>.Shared.Return(array);
			}
		}

		private T? GetResultCore(out FailureReason? failureReason)
		{
			if (_hasDeserializedResult)
			{
				failureReason = null;
				return _deserializedResult;
			}
			string text = ((((ChatResponse)this).Messages.Count > 0) ? ((ChatResponse)this).Messages[((ChatResponse)this).Messages.Count - 1].Text : string.Empty);
			if (string.IsNullOrEmpty(text))
			{
				failureReason = FailureReason.ResultDidNotContainJson;
				return default(T);
			}
			T val = default(T);
			if (IsWrappedInObject)
			{
				if (!JsonDocument.Parse(text).RootElement.TryGetProperty("data", out var value))
				{
					failureReason = FailureReason.ResultDidNotContainDataProperty;
					return default(T);
				}
				text = value.GetRawText();
			}
			val = DeserializeFirstTopLevelObject(text, (JsonTypeInfo<T>)_serializerOptions.GetTypeInfo(typeof(T)));
			if (val == null)
			{
				failureReason = FailureReason.DeserializationProducedNull;
				return default(T);
			}
			_deserializedResult = val;
			_hasDeserializedResult = true;
			failureReason = null;
			return val;
		}
	}
	public sealed class ConfigureOptionsChatClient : DelegatingChatClient
	{
		[CompilerGenerated]
		private sealed class <GetStreamingResponseAsync>d__3 : IAsyncEnumerable<ChatResponseUpdate>, IAsyncEnumerator<ChatResponseUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private ChatResponseUpdate <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			public ConfigureOptionsChatClient <>4__this;

			private IEnumerable<ChatMessage> messages;

			public IEnumerable<ChatMessage> <>3__messages;

			private ChatOptions options;

			public ChatOptions <>3__options;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private IAsyncEnumerator<ChatResponseUpdate> <>7__wrap1;

			private object <>7__wrap2;

			private int <>7__wrap3;

			private ValueTaskAwaiter<bool> <>u__1;

			private ValueTaskAwaiter <>u__2;

			ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetStreamingResponseAsync>d__3(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				ConfigureOptionsChatClient configureOptionsChatClient = <>4__this;
				try
				{
					ValueTaskAwaiter awaiter;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							<>7__wrap1 = configureOptionsChatClient.<>n__1(messages, configureOptionsChatClient.Configure(options), cancellationToken).GetAsyncEnumerator();
							<>7__wrap2 = null;
							<>7__wrap3 = 0;
							goto case -4;
						}
						goto end_IL_000e;
					case -4:
					case 0:
						try
						{
							ValueTaskAwaiter<bool> awaiter2;
							if (num != -4)
							{
								if (num != 0)
								{
									goto IL_00cb;
								}
								awaiter2 = <>u__1;
								<>u__1 = default(ValueTaskAwaiter<bool>);
								num = (<>1__state = -1);
								goto IL_0136;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_00cb;
							}
							goto end_IL_0086;
							IL_00cb:
							<>2__current = null;
							awaiter2 = <>7__wrap1.MoveNextAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter2;
								<GetStreamingResponseAsync>d__3 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_0136;
							IL_0136:
							if (awaiter2.GetResult())
							{
								ChatResponseUpdate current = <>7__wrap1.Current;
								<>2__current = current;
								num = (<>1__state = -4);
								goto IL_02b9;
							}
							end_IL_0086:;
						}
						catch (object obj)
						{
							<>7__wrap2 = obj;
						}
						if (<>7__wrap1 == null)
						{
							break;
						}
						<>2__current = null;
						awaiter = <>7__wrap1.DisposeAsync().GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__2 = awaiter;
							<GetStreamingResponseAsync>d__3 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
							return;
						}
						goto IL_01c7;
					case 1:
						{
							awaiter = <>u__2;
							<>u__2 = default(ValueTaskAwaiter);
							num = (<>1__state = -1);
							goto IL_01c7;
						}
						IL_01c7:
						awaiter.GetResult();
						break;
					}
					object obj2 = <>7__wrap2;
					if (obj2 != null)
					{
						if (!(obj2 is Exception source))
						{
							throw obj2;
						}
						ExceptionDispatchInfo.Capture(source).Throw();
					}
					_ = <>7__wrap3;
					if (!<>w__disposeMode)
					{
						<>7__wrap2 = null;
						<>7__wrap1 = null;
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>7__wrap1 = null;
					<>7__wrap2 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>7__wrap1 = null;
				<>7__wrap2 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_02b9:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<ChatResponseUpdate> IAsyncEnumerable<ChatResponseUpdate>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<GetStreamingResponseAsync>d__3 <GetStreamingResponseAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<GetStreamingResponseAsync>d__ = this;
				}
				else
				{
					<GetStreamingResponseAsync>d__ = new <GetStreamingResponseAsync>d__3(-3)
					{
						<>4__this = <>4__this
					};
				}
				<GetStreamingResponseAsync>d__.messages = <>3__messages;
				<GetStreamingResponseAsync>d__.options = <>3__options;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<GetStreamingResponseAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<GetStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<GetStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <GetStreamingResponseAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<GetStreamingResponseAsync>d__3 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<GetStreamingResponseAsync>d__3 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		private readonly Action<ChatOptions> _configureOptions;

		public ConfigureOptionsChatClient(IChatClient innerClient, Action<ChatOptions> configure)
			: base(innerClient)
		{
			_configureOptions = Throw.IfNull(configure, "configure");
		}

		public override async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return await <>n__0(messages, Configure(options), cancellationToken);
		}

		[AsyncIteratorStateMachine(typeof(<GetStreamingResponseAsync>d__3))]
		public override IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			return new <GetStreamingResponseAsync>d__3(-2)
			{
				<>4__this = this,
				<>3__messages = messages,
				<>3__options = options,
				<>3__cancellationToken = cancellationToken
			};
		}

		private ChatOptions Configure(ChatOptions? options)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			options = (ChatOptions?)(((object)((options != null) ? options.Clone() : null)) ?? ((object)new ChatOptions()));
			_configureOptions(options);
			return options;
		}

		[CompilerGenerated]
		[DebuggerHidden]
		private Task<ChatResponse> <>n__0(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ((DelegatingChatClient)this).GetResponseAsync(messages, options, cancellationToken);
		}

		[CompilerGenerated]
		[DebuggerHidden]
		private IAsyncEnumerable<ChatResponseUpdate> <>n__1(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ((DelegatingChatClient)this).GetStreamingResponseAsync(messages, options, cancellationToken);
		}
	}
	public static class ConfigureOptionsChatClientBuilderExtensions
	{
		public static ChatClientBuilder ConfigureOptions(this ChatClientBuilder builder, Action<ChatOptions> configure)
		{
			Action<ChatOptions> configure2 = configure;
			Throw.IfNull(builder, "builder");
			Throw.IfNull(configure2, "configure");
			return builder.Use((IChatClient innerClient) => (IChatClient)(object)new ConfigureOptionsChatClient(innerClient, configure2));
		}
	}
	public class DistributedCachingChatClient : CachingChatClient
	{
		private static readonly object _cacheVersion = 2;

		private readonly IDistributedCache _storage;

		private object[]? _cacheKeyAdditionalValues;

		[CompilerGenerated]
		private JsonSerializerOptions <JsonSerializerOptions>k__BackingField = AIJsonUtilities.DefaultOptions;

		public JsonSerializerOptions JsonSerializerOptions
		{
			[CompilerGenerated]
			get
			{
				return <JsonSerializerOptions>k__BackingField;
			}
			set
			{
				<JsonSerializerOptions>k__BackingField = Throw.IfNull(value, "value");
			}
		}

		public IReadOnlyList<object>? CacheKeyAdditionalValues
		{
			get
			{
				return _cacheKeyAdditionalValues;
			}
			set
			{
				_cacheKeyAdditionalValues = value?.ToArray();
			}
		}

		public DistributedCachingChatClient(IChatClient innerClient, IDistributedCache storage)
			: base(innerClient)
		{
			_storage = Throw.IfNull(storage, "storage");
		}

		protected override async Task<ChatResponse?> ReadCacheAsync(string key, CancellationToken cancellationToken)
		{
			Throw.IfNull(key, "key");
			JsonSerializerOptions.MakeReadOnly();
			byte[] array = await _storage.GetAsync(key, cancellationToken);
			if (array != null)
			{
				return (ChatResponse)JsonSerializer.Deserialize((ReadOnlySpan<byte>)array, JsonSerializerOptions.GetTypeInfo(typeof(ChatResponse)));
			}
			return null;
		}

		protected override async Task<IReadOnlyList<ChatResponseUpdate>?> ReadCacheStreamingAsync(string key, CancellationToken cancellationToken)
		{
			Throw.IfNull(key, "key");
			JsonSerializerOptions.MakeReadOnly();
			byte[] array = await _storage.GetAsync(key, cancellationToken);
			if (array != null)
			{
				return (IReadOnlyList<ChatResponseUpdate>)JsonSerializer.Deserialize((ReadOnlySpan<byte>)array, JsonSerializerOptions.GetTypeInfo(typeof(IReadOnlyList<ChatResponseUpdate>)));
			}
			return null;
		}

		protected override async Task WriteCacheAsync(string key, ChatResponse value, CancellationToken cancellationToken)
		{
			Throw.IfNull(key, "key");
			Throw.IfNull<ChatResponse>(value, "value");
			JsonSerializerOptions.MakeReadOnly();
			byte[] value2 = JsonSerializer.SerializeToUtf8Bytes((object)value, JsonSerializerOptions.GetTypeInfo(typeof(ChatResponse)));
			await _storage.SetAsync(key, value2, cancellationToken);
		}

		protected override async Task WriteCacheStreamingAsync(string key, IReadOnlyList<ChatResponseUpdate> value, CancellationToken cancellationToken)
		{
			Throw.IfNull(key, "key");
			Throw.IfNull(value, "value");
			JsonSerializerOptions.MakeReadOnly();
			byte[] value2 = JsonSerializer.SerializeToUtf8Bytes((object)value, JsonSerializerOptions.GetTypeInfo(typeof(IReadOnlyList<ChatResponseUpdate>)));
			await _storage.SetAsync(key, value2, cancellationToken);
		}

		protected override string GetCacheKey(IEnumerable<ChatMessage> messages, ChatOptions? options, [ParamCollection] scoped ReadOnlySpan<object?> additionalValues)
		{
			object[] array = _cacheKeyAdditionalValues ?? Array.Empty<object>();
			int num = 3 + additionalValues.Length + array.Length;
			object[] array2 = ArrayPool<object>.Shared.Rent(num);
			try
			{
				array2[0] = _cacheVersion;
				array2[1] = messages;
				array2[2] = options;
				additionalValues.CopyTo(array2.AsSpan(3));
				array.CopyTo(array2, 3 + additionalValues.Length);
				return AIJsonUtilities.HashDataToString((ReadOnlySpan<object>)array2.AsSpan(0, num), JsonSerializerOptions);
			}
			finally
			{
				Array.Clear(array2, 0, num);
				ArrayPool<object>.Shared.Return(array2);
			}
		}
	}
	public static class DistributedCachingChatClientBuilderExtensions
	{
		public static ChatClientBuilder UseDistributedCache(this ChatClientBuilder builder, IDistributedCache? storage = null, Action<DistributedCachingChatClient>? configure = null)
		{
			IDistributedCache storage2 = storage;
			Action<DistributedCachingChatClient> configure2 = configure;
			Throw.IfNull(builder, "builder");
			return builder.Use(delegate(IChatClient innerClient, IServiceProvider services)
			{
				if (storage2 == null)
				{
					storage2 = services.GetRequiredService<IDistributedCache>();
				}
				DistributedCachingChatClient distributedCachingChatClient = new DistributedCachingChatClient(innerClient, storage2);
				configure2?.Invoke(distributedCachingChatClient);
				return (IChatClient)(object)distributedCachingChatClient;
			});
		}
	}
	public class FunctionInvocationContext
	{
		private static readonly AIFunction _nopFunction = AIFunctionFactory.Create((Delegate)(Action)delegate
		{
		}, "FunctionInvocationContext", (string)null, (JsonSerializerOptions)null);

		[CompilerGenerated]
		private AIFunction <Function>k__BackingField = _nopFunction;

		[CompilerGenerated]
		private AIFunctionArguments <Arguments>k__BackingField;

		[CompilerGenerated]
		private FunctionCallContent <CallContent>k__BackingField;

		[CompilerGenerated]
		private IList<ChatMessage> <Messages>k__BackingField = Array.Empty<ChatMessage>();

		public AIFunction Function
		{
			[CompilerGenerated]
			get
			{
				return <Function>k__BackingField;
			}
			set
			{
				<Function>k__BackingField = Throw.IfNull<AIFunction>(value, "value");
			}
		}

		public AIFunctionArguments Arguments
		{
			get
			{
				//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: Expected O, but got Unknown
				//IL_0017: Expected O, but got Unknown
				AIFunctionArguments obj = <Arguments>k__BackingField;
				if (obj == null)
				{
					AIFunctionArguments val = new AIFunctionArguments();
					AIFunctionArguments val2 = val;
					<Arguments>k__BackingField = val;
					obj = val2;
				}
				return obj;
			}
			set
			{
				<Arguments>k__BackingField = Throw.IfNull<AIFunctionArguments>(value, "value");
			}
		}

		public FunctionCallContent CallContent
		{
			get
			{
				//IL_001f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0024: Unknown result type (might be due to invalid IL or missing references)
				//IL_0026: Expected O, but got Unknown
				//IL_002b: Expected O, but got Unknown
				FunctionCallContent obj = <CallContent>k__BackingField;
				if (obj == null)
				{
					FunctionCallContent val = new FunctionCallContent(string.Empty, ((AITool)_nopFunction).Name, (IDictionary<string, object>)EmptyReadOnlyDictionary<string, object>.Instance);
					FunctionCallContent val2 = val;
					<CallContent>k__BackingField = val;
					obj = val2;
				}
				return obj;
			}
			set
			{
				<CallContent>k__BackingField = Throw.IfNull<FunctionCallContent>(value, "value");
			}
		}

		public IList<ChatMessage> Messages
		{
			[CompilerGenerated]
			get
			{
				return <Messages>k__BackingField;
			}
			set
			{
				<Messages>k__BackingField = Throw.IfNull(value, "value");
			}
		}

		public ChatOptions? Options { get; set; }

		public int Iteration { get; set; }

		public int FunctionCallIndex { get; set; }

		public int FunctionCount { get; set; }

		public bool Terminate { get; set; }

		public bool IsStreaming { get; set; }
	}
	public class FunctionInvokingChatClient : DelegatingChatClient
	{
		public sealed class FunctionInvocationResult
		{
			public FunctionInvocationStatus Status { get; }

			public FunctionCallContent CallContent { get; }

			public object? Result { get; }

			public Exception? Exception { get; }

			public bool Terminate { get; }

			internal FunctionInvocationResult(bool terminate, FunctionInvocationStatus status, FunctionCallContent callContent, object? result, Exception? exception)
			{
				Terminate = terminate;
				Status = status;
				CallContent = callContent;
				Result = result;
				Exception = exception;
			}
		}

		public enum FunctionInvocationStatus
		{
			RanToCompletion,
			NotFound,
			Exception
		}

		private struct ApprovalResultWithRequestMessage
		{
			public FunctionApprovalResponseContent Response { get; set; }

			public ChatMessage? RequestMessage { get; set; }
		}

		[CompilerGenerated]
		private sealed class <GetStreamingResponseAsync>d__39 : IAsyncEnumerable<ChatResponseUpdate>, IAsyncEnumerator<ChatResponseUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private ChatResponseUpdate <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private IEnumerable<ChatMessage> messages;

			public IEnumerable<ChatMessage> <>3__messages;

			public FunctionInvokingChatClient <>4__this;

			private ChatOptions options;

			public ChatOptions <>3__options;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private Activity <activity>5__2;

			private UsageDetails <totalUsage>5__3;

			private List<ChatMessage> <originalMessages>5__4;

			private AITool[] <approvalRequiredFunctions>5__5;

			private List<ChatMessage> <augmentedHistory>5__6;

			private List<FunctionCallContent> <functionCallContents>5__7;

			private List<ChatMessage> <responseMessages>5__8;

			private bool <lastIterationHadConversationId>5__9;

			private List<ChatResponseUpdate> <updates>5__10;

			private int <consecutiveErrorCount>5__11;

			private Dictionary<string, AITool> <toolMap>5__12;

			private bool <anyToolsRequireApproval>5__13;

			private string <toolMessageId>5__14;

			private List<ApprovalResultWithRequestMessage> <notInvokedApprovals>5__15;

			private bool <shouldTerminate>5__16;

			private List<ChatMessage>.Enumerator <>7__wrap16;

			private TaskAwaiter<(IList<ChatMessage>? FunctionResultContentMessages, bool ShouldTerminate, int ConsecutiveErrorCount)> <>u__1;

			private IEnumerator<ChatMessage> <>7__wrap17;

			private int <iteration>5__19;

			private int <lastApprovalCheckedFCCIndex>5__20;

			private int <lastYieldedUpdateIndex>5__21;

			private ChatResponse <response>5__22;

			private (bool ShouldTerminate, int NewConsecutiveErrorCount, IList<ChatMessage> MessagesAdded) <modeAndMessages>5__23;

			private IAsyncEnumerator<ChatResponseUpdate> <>7__wrap23;

			private object <>7__wrap24;

			private int <>7__wrap25;

			private ValueTaskAwaiter<bool> <>u__2;

			private ValueTaskAwaiter <>u__3;

			private TaskAwaiter<(bool ShouldTerminate, int NewConsecutiveErrorCount, IList<ChatMessage> MessagesAdded)> <>u__4;

			ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetStreamingResponseAsync>d__39(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
				int num = <>1__state;
				FunctionInvokingChatClient functionInvokingChatClient = <>4__this;
				try
				{
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							Throw.IfNull(messages, "messages");
							<activity>5__2 = (CurrentActivityIsInvokeAgent ? null : functionInvokingChatClient._activitySource?.StartActivity("orchestrate_tools"));
							break;
						}
						goto end_IL_000e;
					case -9:
					case -8:
					case -7:
					case -6:
					case -5:
					case -4:
					case 0:
					case 1:
					case 2:
					case 3:
						break;
					}
					try
					{
						TaskAwaiter<(IList<ChatMessage>, bool, int)> awaiter3;
						ValueTaskAwaiter awaiter2;
						TaskAwaiter<(bool, int, IList<ChatMessage>)> awaiter;
						IList<ChatMessage> list2;
						object obj5;
						(bool, int, IList<ChatMessage>) result;
						ChatResponseUpdate val3;
						switch (num)
						{
						default:
						{
							<totalUsage>5__3 = ((<activity>5__2 == null || !<activity>5__2.IsAllDataRequested) ? ((UsageDetails)null) : new UsageDetails());
							<originalMessages>5__4 = messages.ToList();
							messages = <originalMessages>5__4;
							<approvalRequiredFunctions>5__5 = null;
							<augmentedHistory>5__6 = null;
							<functionCallContents>5__7 = null;
							<responseMessages>5__8 = null;
							<lastIterationHadConversationId>5__9 = false;
							<updates>5__10 = new List<ChatResponseUpdate>();
							<consecutiveErrorCount>5__11 = 0;
							IList<AITool>[] obj2 = new IList<AITool>[2] { functionInvokingChatClient.AdditionalTools, null };
							ChatOptions obj3 = options;
							obj2[1] = ((obj3 != null) ? obj3.Tools : null);
							(Dictionary<string, AITool>, bool) tuple = CreateToolsMap(new ReadOnlySpan<IList<AITool>>(obj2));
							<toolMap>5__12 = tuple.Item1;
							<anyToolsRequireApproval>5__13 = tuple.Item2;
							<toolMessageId>5__14 = Guid.NewGuid().ToString("N");
							if (HasAnyApprovalContent(<originalMessages>5__4))
							{
								string functionCallContentFallbackMessageId = Guid.NewGuid().ToString("N");
								List<ChatMessage> originalMessages = <originalMessages>5__4;
								ChatOptions obj4 = options;
								List<ChatMessage> list;
								(list, <notInvokedApprovals>5__15) = ProcessFunctionApprovalResponses(originalMessages, !string.IsNullOrWhiteSpace((obj4 != null) ? obj4.ConversationId : null), <toolMessageId>5__14, functionCallContentFallbackMessageId);
								if (list != null)
								{
									<>7__wrap16 = list.GetEnumerator();
									goto case -4;
								}
								goto IL_02bf;
							}
							goto IL_0451;
						}
						case -4:
							try
							{
								if (num != -4)
								{
									goto IL_028f;
								}
								num = (<>1__state = -1);
								if (!<>w__disposeMode)
								{
									Activity.Current = <activity>5__2;
									goto IL_028f;
								}
								goto end_IL_022a;
								IL_028f:
								if (!<>7__wrap16.MoveNext())
								{
									goto end_IL_022a;
								}
								ChatMessage current = <>7__wrap16.Current;
								ChatOptions obj = options;
								<>2__current = ConvertToolResultMessageToUpdate(current, (obj != null) ? obj.ConversationId : null, current.MessageId);
								num = (<>1__state = -4);
								goto end_IL_009b;
								end_IL_022a:;
							}
							finally
							{
								if (num == -1)
								{
									((IDisposable)<>7__wrap16).Dispose();
								}
							}
							if (!<>w__disposeMode)
							{
								goto IL_02bf;
							}
							goto IL_0b85;
						case 0:
							awaiter3 = <>u__1;
							<>u__1 = default(TaskAwaiter<(IList<ChatMessage>, bool, int)>);
							num = (<>1__state = -1);
							goto IL_0346;
						case -5:
							try
							{
								if (num != -5)
								{
									goto IL_03fd;
								}
								num = (<>1__state = -1);
								if (!<>w__disposeMode)
								{
									Activity.Current = <activity>5__2;
									goto IL_03fd;
								}
								goto end_IL_038b;
								IL_03fd:
								if (!<>7__wrap17.MoveNext())
								{
									goto end_IL_038b;
								}
								ChatMessage current2 = <>7__wrap17.Current;
								current2.MessageId = <toolMessageId>5__14;
								ChatOptions obj6 = options;
								<>2__current = ConvertToolResultMessageToUpdate(current2, (obj6 != null) ? obj6.ConversationId : null, current2.MessageId);
								num = (<>1__state = -5);
								goto end_IL_009b;
								end_IL_038b:;
							}
							finally
							{
								if (num == -1 && <>7__wrap17 != null)
								{
									<>7__wrap17.Dispose();
								}
							}
							if (!<>w__disposeMode)
							{
								<>7__wrap17 = null;
								if (!<shouldTerminate>5__16)
								{
									goto IL_044a;
								}
								<>w__disposeMode = true;
							}
							goto IL_0b85;
						case -7:
						case -6:
						case 1:
							try
							{
								ValueTaskAwaiter<bool> awaiter4;
								if (num != -7)
								{
									if (num != -6)
									{
										if (num != 1)
										{
											goto IL_0746;
										}
										awaiter4 = <>u__2;
										<>u__2 = default(ValueTaskAwaiter<bool>);
										num = (<>1__state = -1);
										goto IL_07b1;
									}
									num = (<>1__state = -1);
									if (!<>w__disposeMode)
									{
										Activity.Current = <activity>5__2;
										goto IL_0746;
									}
								}
								else
								{
									num = (<>1__state = -1);
									if (!<>w__disposeMode)
									{
										Activity.Current = <activity>5__2;
										<lastYieldedUpdateIndex>5__21++;
										goto IL_0730;
									}
								}
								goto end_IL_04c5;
								IL_07b1:
								if (!awaiter4.GetResult())
								{
									goto end_IL_04c5;
								}
								ChatResponseUpdate current3 = <>7__wrap23.Current;
								if (current3 == null)
								{
									Throw.InvalidOperationException("The inner IChatClient streamed a null ChatResponseUpdate.");
								}
								<updates>5__10.Add(current3);
								CopyFunctionCalls(current3.Contents, ref <functionCallContents>5__7);
								if (<totalUsage>5__3 != null)
								{
									IList<AIContent> contents = current3.Contents;
									int count = contents.Count;
									for (int i = 0; i < count; i++)
									{
										AIContent obj7 = contents[i];
										UsageContent val = (UsageContent)(object)((obj7 is UsageContent) ? obj7 : null);
										if (val != null)
										{
											<totalUsage>5__3.Add(val.Details);
										}
									}
								}
								if (<anyToolsRequireApproval>5__13 && <approvalRequiredFunctions>5__5 == null && <functionCallContents>5__7 != null && <functionCallContents>5__7.Count > 0)
								{
									ChatOptions obj8 = options;
									IEnumerable<AITool> enumerable = ((obj8 != null) ? obj8.Tools : null);
									IEnumerable<AITool> first = enumerable ?? Enumerable.Empty<AITool>();
									enumerable = functionInvokingChatClient.AdditionalTools;
									<approvalRequiredFunctions>5__5 = (from t in first.Concat(enumerable ?? Enumerable.Empty<AITool>())
										where t.GetService<ApprovalRequiredAIFunction>((object)null) != null
										select t).ToArray();
								}
								if (<approvalRequiredFunctions>5__5 != null && <approvalRequiredFunctions>5__5.Length > 0 && <functionCallContents>5__7 != null && <functionCallContents>5__7.Count > 0)
								{
									(<shouldTerminate>5__16, <lastApprovalCheckedFCCIndex>5__20) = CheckForApprovalRequiringFCC(<functionCallContents>5__7, <approvalRequiredFunctions>5__5, <shouldTerminate>5__16, <lastApprovalCheckedFCCIndex>5__20);
									if (<shouldTerminate>5__16)
									{
										goto IL_0730;
									}
									goto IL_0746;
								}
								<lastYieldedUpdateIndex>5__21++;
								<>2__current = current3;
								num = (<>1__state = -6);
								goto end_IL_009b;
								IL_0746:
								<>2__current = null;
								awaiter4 = <>7__wrap23.MoveNextAsync().GetAwaiter();
								if (!awaiter4.IsCompleted)
								{
									num = (<>1__state = 1);
									<>u__2 = awaiter4;
									<GetStreamingResponseAsync>d__39 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter4, ref stateMachine);
									return;
								}
								goto IL_07b1;
								IL_0730:
								if (<lastYieldedUpdateIndex>5__21 >= <updates>5__10.Count)
								{
									goto IL_0746;
								}
								ChatResponseUpdate val2 = <updates>5__10[<lastYieldedUpdateIndex>5__21];
								if (TryReplaceFunctionCallsWithApprovalRequests(val2.Contents, out List<AIContent> updatedContent))
								{
									val2.Contents = updatedContent;
								}
								<>2__current = val2;
								num = (<>1__state = -7);
								goto end_IL_009b;
								end_IL_04c5:;
							}
							catch (object obj9)
							{
								<>7__wrap24 = obj9;
							}
							if (<>7__wrap23 != null)
							{
								<>2__current = null;
								awaiter2 = <>7__wrap23.DisposeAsync().GetAwaiter();
								if (!awaiter2.IsCompleted)
								{
									num = (<>1__state = 2);
									<>u__3 = awaiter2;
									<GetStreamingResponseAsync>d__39 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
									return;
								}
								goto IL_0842;
							}
							goto IL_0849;
						case 2:
							awaiter2 = <>u__3;
							<>u__3 = default(ValueTaskAwaiter);
							num = (<>1__state = -1);
							goto IL_0842;
						case -8:
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								Activity.Current = <activity>5__2;
								<lastYieldedUpdateIndex>5__21++;
								goto IL_08ee;
							}
							goto IL_0b85;
						case 3:
							awaiter = <>u__4;
							<>u__4 = default(TaskAwaiter<(bool, int, IList<ChatMessage>)>);
							num = (<>1__state = -1);
							goto IL_0a26;
						case -9:
							{
								try
								{
									if (num != -9)
									{
										goto IL_0ad2;
									}
									num = (<>1__state = -1);
									if (!<>w__disposeMode)
									{
										Activity.Current = <activity>5__2;
										goto IL_0ad2;
									}
									goto end_IL_0a75;
									IL_0ad2:
									if (!<>7__wrap17.MoveNext())
									{
										goto end_IL_0a75;
									}
									ChatMessage current4 = <>7__wrap17.Current;
									<>2__current = ConvertToolResultMessageToUpdate(current4, <response>5__22.ConversationId, <toolMessageId>5__14);
									num = (<>1__state = -9);
									goto end_IL_009b;
									end_IL_0a75:;
								}
								finally
								{
									if (num == -1 && <>7__wrap17 != null)
									{
										<>7__wrap17.Dispose();
									}
								}
								if (!<>w__disposeMode)
								{
									<>7__wrap17 = null;
									if (<modeAndMessages>5__23.ShouldTerminate)
									{
										break;
									}
									UpdateOptionsForNextIteration(ref options, <response>5__22.ConversationId);
									<response>5__22 = null;
									<modeAndMessages>5__23 = default((bool, int, IList<ChatMessage>));
									<iteration>5__19++;
									goto IL_0458;
								}
								goto IL_0b85;
							}
							IL_0842:
							awaiter2.GetResult();
							goto IL_0849;
							IL_0346:
							(list2, <shouldTerminate>5__16, <consecutiveErrorCount>5__11) = awaiter3.GetResult();
							if (list2 != null)
							{
								<>7__wrap17 = list2.GetEnumerator();
								goto case -5;
							}
							goto IL_044a;
							IL_02bf:
							<>2__current = null;
							awaiter3 = functionInvokingChatClient.InvokeApprovedFunctionApprovalResponsesAsync(<notInvokedApprovals>5__15, <toolMap>5__12, <originalMessages>5__4, options, <consecutiveErrorCount>5__11, isStreaming: true, cancellationToken).GetAwaiter();
							if (!awaiter3.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter3;
								<GetStreamingResponseAsync>d__39 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine);
								return;
							}
							goto IL_0346;
							IL_0849:
							obj5 = <>7__wrap24;
							if (obj5 != null)
							{
								if (!(obj5 is Exception source))
								{
									throw obj5;
								}
								ExceptionDispatchInfo.Capture(source).Throw();
							}
							_ = <>7__wrap25;
							if (!<>w__disposeMode)
							{
								<>7__wrap24 = null;
								<>7__wrap23 = null;
								goto IL_08ee;
							}
							goto IL_0b85;
							IL_0a26:
							result = awaiter.GetResult();
							<modeAndMessages>5__23 = result;
							<responseMessages>5__8.AddRange(<modeAndMessages>5__23.MessagesAdded);
							<consecutiveErrorCount>5__11 = <modeAndMessages>5__23.NewConsecutiveErrorCount;
							<>7__wrap17 = <modeAndMessages>5__23.MessagesAdded.GetEnumerator();
							goto case -9;
							IL_08ee:
							if (<lastYieldedUpdateIndex>5__21 >= <updates>5__10.Count)
							{
								if (((<iteration>5__19 >= functionInvokingChatClient.MaximumIterationsPerRequest) | <shouldTerminate>5__16) || functionInvokingChatClient.ShouldTerminateLoopBasedOnHandleableFunctions(<functionCallContents>5__7, <toolMap>5__12))
								{
									break;
								}
								<response>5__22 = ChatResponseExtensions.ToChatResponse((IEnumerable<ChatResponseUpdate>)<updates>5__10);
								(<responseMessages>5__8 ?? (<responseMessages>5__8 = new List<ChatMessage>())).AddRange(<response>5__22.Messages);
								FixupHistories(<originalMessages>5__4, ref messages, ref <augmentedHistory>5__6, <response>5__22, <responseMessages>5__8, ref <lastIterationHadConversationId>5__9);
								<>2__current = null;
								awaiter = functionInvokingChatClient.ProcessFunctionCallsAsync(<augmentedHistory>5__6, options, <toolMap>5__12, <functionCallContents>5__7, <iteration>5__19, <consecutiveErrorCount>5__11, isStreaming: true, cancellationToken).GetAwaiter();
								if (!awaiter.IsCompleted)
								{
									num = (<>1__state = 3);
									<>u__4 = awaiter;
									<GetStreamingResponseAsync>d__39 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
									return;
								}
								goto IL_0a26;
							}
							val3 = <updates>5__10[<lastYieldedUpdateIndex>5__21];
							<>2__current = val3;
							num = (<>1__state = -8);
							goto end_IL_009b;
							IL_044a:
							<notInvokedApprovals>5__15 = null;
							goto IL_0451;
							IL_0451:
							<iteration>5__19 = 0;
							goto IL_0458;
							IL_0458:
							<updates>5__10.Clear();
							<functionCallContents>5__7?.Clear();
							<shouldTerminate>5__16 = false;
							<lastApprovalCheckedFCCIndex>5__20 = 0;
							<lastYieldedUpdateIndex>5__21 = 0;
							<>7__wrap23 = functionInvokingChatClient.<>n__1(messages, options, cancellationToken).GetAsyncEnumerator();
							<>7__wrap24 = null;
							<>7__wrap25 = 0;
							goto case -7;
						}
						AddUsageTags(<activity>5__2, <totalUsage>5__3);
						goto end_IL_000e;
						end_IL_009b:;
					}
					finally
					{
						if (num == -1 && <activity>5__2 != null)
						{
							((IDisposable)<activity>5__2).Dispose();
						}
					}
					goto IL_0d4d;
					IL_0b85:
					if (!<>w__disposeMode)
					{
						<activity>5__2 = null;
						<totalUsage>5__3 = null;
						<originalMessages>5__4 = null;
						<approvalRequiredFunctions>5__5 = null;
						<augmentedHistory>5__6 = null;
						<functionCallContents>5__7 = null;
						<responseMessages>5__8 = null;
						<updates>5__10 = null;
						<toolMap>5__12 = null;
						<toolMessageId>5__14 = null;
						throw null;
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<activity>5__2 = null;
					<totalUsage>5__3 = null;
					<originalMessages>5__4 = null;
					<approvalRequiredFunctions>5__5 = null;
					<augmentedHistory>5__6 = null;
					<functionCallContents>5__7 = null;
					<responseMessages>5__8 = null;
					<updates>5__10 = null;
					<toolMap>5__12 = null;
					<toolMessageId>5__14 = null;
					<notInvokedApprovals>5__15 = null;
					<>7__wrap17 = null;
					<response>5__22 = null;
					<modeAndMessages>5__23 = default((bool, int, IList<ChatMessage>));
					<>7__wrap23 = null;
					<>7__wrap24 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<activity>5__2 = null;
				<totalUsage>5__3 = null;
				<originalMessages>5__4 = null;
				<approvalRequiredFunctions>5__5 = null;
				<augmentedHistory>5__6 = null;
				<functionCallContents>5__7 = null;
				<responseMessages>5__8 = null;
				<updates>5__10 = null;
				<toolMap>5__12 = null;
				<toolMessageId>5__14 = null;
				<notInvokedApprovals>5__15 = null;
				<>7__wrap17 = null;
				<response>5__22 = null;
				<modeAndMessages>5__23 = default((bool, int, IList<ChatMessage>));
				<>7__wrap23 = null;
				<>7__wrap24 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_0d4d:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<ChatResponseUpdate> IAsyncEnumerable<ChatResponseUpdate>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<GetStreamingResponseAsync>d__39 <GetStreamingResponseAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<GetStreamingResponseAsync>d__ = this;
				}
				else
				{
					<GetStreamingResponseAsync>d__ = new <GetStreamingResponseAsync>d__39(-3)
					{
						<>4__this = <>4__this
					};
				}
				<GetStreamingResponseAsync>d__.messages = <>3__messages;
				<GetStreamingResponseAsync>d__.options = <>3__options;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<GetStreamingResponseAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<GetStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<GetStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <GetStreamingResponseAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<GetStreamingResponseAsync>d__39 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<GetStreamingResponseAsync>d__39 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		private static readonly AsyncLocal<FunctionInvocationContext?> _currentContext = new AsyncLocal<FunctionInvocationContext>();

		private readonly ILogger _logger;

		private readonly ActivitySource? _activitySource;

		[CompilerGenerated]
		private int <MaximumIterationsPerRequest>k__BackingField = 40;

		[CompilerGenerated]
		private int <MaximumConsecutiveErrorsPerRequest>k__BackingField = 3;

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")]
		private static readonly Action<ILogger, string, Exception?> __LogInvokingCallback = LoggerMessage.Define<string>(LogLevel.Debug, new EventId(807273242, "LogInvoking"), "Invoking {MethodName}.", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")]
		private static readonly Action<ILogger, string, string, Exception?> __LogInvokingSensitiveCallback = LoggerMessage.Define<string, string>(LogLevel.Trace, new EventId(1953841678, "LogInvokingSensitive"), "Invoking {MethodName}({Arguments}).", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")]
		private static readonly Action<ILogger, string, TimeSpan, Exception?> __LogInvocationCompletedCallback = LoggerMessage.Define<string, TimeSpan>(LogLevel.Debug, new EventId(1098781176, "LogInvocationCompleted"), "{MethodName} invocation completed. Duration: {Duration}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")]
		private static readonly Action<ILogger, string, TimeSpan, string, Exception?> __LogInvocationCompletedSensitiveCallback = LoggerMessage.Define<string, TimeSpan, string>(LogLevel.Trace, new EventId(700532736, "LogInvocationCompletedSensitive"), "{MethodName} invocation completed. Duration: {Duration}. Result: {Result}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")]
		private static readonly Action<ILogger, string, Exception?> __LogInvocationCanceledCallback = LoggerMessage.Define<string>(LogLevel.Debug, new EventId(1891493904, "LogInvocationCanceled"), "{MethodName} invocation canceled.", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "10.0.13.7005")]
		private static readonly Action<ILogger, string, Exception?> __LogInvocationFailedCallback = LoggerMessage.Define<string>(LogLevel.Error, new EventId(1784604714, "LogInvocationFailed"), "{MethodName} invocation failed.", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		protected IServiceProvider? FunctionInvocationServices { get; }

		public static FunctionInvocationContext? CurrentContext
		{
			get
			{
				return _currentContext.Value;
			}
			protected set
			{
				_currentContext.Value = value;
			}
		}

		public bool IncludeDetailedErrors { get; set; }

		public bool AllowConcurrentInvocation { get; set; }

		public int MaximumIterationsPerRequest
		{
			[CompilerGenerated]
			get
			{
				return <MaximumIterationsPerRequest>k__BackingField;
			}
			set
			{
				if (value < 1)
				{
					Throw.ArgumentOutOfRangeException("value");
				}
				<MaximumIterationsPerRequest>k__BackingField = value;
			}
		}

		public int MaximumConsecutiveErrorsPerRequest
		{
			[CompilerGenerated]
			get
			{
				return <MaximumConsecutiveErrorsPerRequest>k__BackingField;
			}
			set
			{
				<MaximumConsecutiveErrorsPerRequest>k__BackingField = Throw.IfLessThan(value, 0, "value");
			}
		}

		public IList<AITool>? AdditionalTools { get; set; }

		public bool TerminateOnUnknownCalls { get; set; }

		public Func<FunctionInvocationContext, CancellationToken, ValueTask<object?>>? FunctionInvoker { get; set; }

		private static bool CurrentActivityIsInvokeAgent => Activity.Current?.DisplayName == "invoke_agent";

		public FunctionInvokingChatClient(IChatClient innerClient, ILoggerFactory? loggerFactory = null, IServiceProvider? functionInvocationServices = null)
			: base(innerClient)
		{
			ILogger logger = loggerFactory?.CreateLogger<FunctionInvokingChatClient>();
			_logger = logger ?? NullLogger.Instance;
			_activitySource = ChatClientExtensions.GetService<ActivitySource>(innerClient, (object)null);
			FunctionInvocationServices = functionInvocationServices;
		}

		public override async Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			Throw.IfNull(messages, "messages");
			using Activity activity = (CurrentActivityIsInvokeAgent ? null : _activitySource?.StartActivity("orchestrate_tools"));
	

BepInEx/core/Microsoft.Extensions.AI.OpenAI.dll

Decompiled 2 weeks ago
using System;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.AI;
using Microsoft.Shared.Diagnostics;
using OpenAI.Assistants;
using OpenAI.Audio;
using OpenAI.Chat;
using OpenAI.Embeddings;
using OpenAI.Images;
using OpenAI.Realtime;
using OpenAI.Responses;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Implementation of generative AI abstractions for OpenAI-compatible endpoints.")]
[assembly: AssemblyFileVersion("10.100.125.61202")]
[assembly: AssemblyInformationalVersion("10.1.1-preview.1.25612.2+8a57aae6b42651573f06fd3904b9a0d1023f9aeb")]
[assembly: AssemblyProduct("Microsoft.Extensions.AI.OpenAI")]
[assembly: AssemblyTitle("Microsoft.Extensions.AI.OpenAI")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/extensions")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("10.1.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;
		}
	}
}
namespace OpenAI.Responses
{
	public static class MicrosoftExtensionsAIResponsesExtensions
	{
		public static FunctionTool AsOpenAIResponseTool(this AIFunctionDeclaration function)
		{
			return OpenAIResponsesChatClient.ToResponseTool(Throw.IfNull<AIFunctionDeclaration>(function, "function"));
		}

		public static ResponseTool? AsOpenAIResponseTool(this AITool tool)
		{
			return OpenAIResponsesChatClient.ToResponseTool(Throw.IfNull<AITool>(tool, "tool"));
		}

		public static ResponseTextFormat? AsOpenAIResponseTextFormat(this ChatResponseFormat? format, ChatOptions? options = null)
		{
			return OpenAIResponsesChatClient.ToOpenAIResponseTextFormat(format, options);
		}

		public static IEnumerable<ResponseItem> AsOpenAIResponseItems(this IEnumerable<ChatMessage> messages, ChatOptions? options = null)
		{
			return OpenAIResponsesChatClient.ToOpenAIResponseItems(Throw.IfNull(messages, "messages"), options);
		}

		public static IEnumerable<ChatMessage> AsChatMessages(this IEnumerable<ResponseItem> items)
		{
			return OpenAIResponsesChatClient.ToChatMessages(Throw.IfNull(items, "items"));
		}

		public static ChatResponse AsChatResponse(this ResponseResult response, CreateResponseOptions? options = null)
		{
			return OpenAIResponsesChatClient.FromOpenAIResponse(Throw.IfNull<ResponseResult>(response, "response"), options, null);
		}

		public static IAsyncEnumerable<ChatResponseUpdate> AsChatResponseUpdatesAsync(this IAsyncEnumerable<StreamingResponseUpdate> responseUpdates, CreateResponseOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return OpenAIResponsesChatClient.FromOpenAIStreamingResponseUpdatesAsync(Throw.IfNull(responseUpdates, "responseUpdates"), options, null, null, cancellationToken);
		}

		public static ResponseResult AsOpenAIResponseResult(this ChatResponse response, ChatOptions? options = null)
		{
			//IL_001d: 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_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Expected O, but got Unknown
			Throw.IfNull<ChatResponse>(response, "response");
			object rawRepresentation = response.RawRepresentation;
			ResponseResult val = (ResponseResult)((rawRepresentation is ResponseResult) ? rawRepresentation : null);
			if (val != null)
			{
				return val;
			}
			? val2 = new ResponseResult();
			? val3 = val2;
			object obj;
			if (!OpenAIClientExtensions.IsConversationId(response.ConversationId))
			{
				obj = null;
				val2 = obj;
				obj = (object)val2;
			}
			else
			{
				val2 = new ResponseConversationOptions(response.ConversationId);
				obj = (object)val2;
			}
			((ResponseResult)val3).ConversationOptions = (ResponseConversationOptions)val2;
			((ResponseResult)obj).CreatedAt = response.CreatedAt.GetValueOrDefault();
			((ResponseResult)obj).Id = response.ResponseId;
			((ResponseResult)obj).Instructions = ((options != null) ? options.Instructions : null);
			((ResponseResult)obj).MaxOutputTokenCount = ((options != null) ? options.MaxOutputTokens : null);
			((ResponseResult)obj).Model = response.ModelId ?? ((options != null) ? options.ModelId : null);
			((ResponseResult)obj).ParallelToolCallsEnabled = ((options != null) ? options.AllowMultipleToolCalls : null).GetValueOrDefault(true);
			((ResponseResult)obj).Status = (ResponseStatus)1;
			((ResponseResult)obj).Temperature = ((options != null) ? options.Temperature : null);
			((ResponseResult)obj).TopP = ((options != null) ? options.TopP : null);
			((ResponseResult)obj).Usage = OpenAIResponsesChatClient.ToResponseTokenUsage(response.Usage);
			ResponseResult val4 = (ResponseResult)obj;
			foreach (ResponseItem item in OpenAIResponsesChatClient.ToOpenAIResponseItems(response.Messages, options))
			{
				val4.OutputItems.Add(item);
			}
			return val4;
		}

		public static void Add(this IList<AITool> tools, ResponseTool tool)
		{
			Throw.IfNull(tools, "tools");
			tools.Add(tool.AsAITool());
		}

		public static AITool AsAITool(this ResponseTool tool)
		{
			Throw.IfNull<ResponseTool>(tool, "tool");
			return (AITool)(object)new OpenAIResponsesChatClient.ResponseToolAITool(tool);
		}
	}
}
namespace OpenAI.Realtime
{
	public static class MicrosoftExtensionsAIRealtimeExtensions
	{
		public static ConversationFunctionTool AsOpenAIConversationFunctionTool(this AIFunctionDeclaration function)
		{
			return OpenAIRealtimeConversationClient.ToOpenAIConversationFunctionTool(Throw.IfNull<AIFunctionDeclaration>(function, "function"));
		}
	}
}
namespace OpenAI.Chat
{
	public static class MicrosoftExtensionsAIChatExtensions
	{
		[CompilerGenerated]
		private sealed class <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d : IEnumerable<ChatMessageAnnotation>, IEnumerable, IEnumerator<ChatMessageAnnotation>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private ChatMessageAnnotation <>2__current;

			private int <>l__initialThreadId;

			private IEnumerable<AIContent> contents;

			public IEnumerable<AIContent> <>3__contents;

			private IEnumerator<AIContent> <>7__wrap1;

			private IEnumerator<AIAnnotation> <>7__wrap2;

			private CitationAnnotation <citation>5__4;

			private TextSpanAnnotatedRegion[] <>7__wrap4;

			private int <>7__wrap5;

			ChatMessageAnnotation IEnumerator<ChatMessageAnnotation>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

			[DebuggerHidden]
			public <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if ((uint)(num - -4) <= 1u || (uint)(num - 1) <= 1u)
				{
					try
					{
						if (num == -4 || (uint)(num - 1) <= 1u)
						{
							try
							{
							}
							finally
							{
								<>m__Finally2();
							}
						}
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<>7__wrap1 = null;
				<>7__wrap2 = null;
				<citation>5__4 = null;
				<>7__wrap4 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				try
				{
					TextSpanAnnotatedRegion[] array;
					AIContent current;
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						if (contents == null)
						{
							return false;
						}
						<>7__wrap1 = contents.GetEnumerator();
						<>1__state = -3;
						goto IL_01d6;
					case 1:
						<>1__state = -4;
						<>7__wrap5++;
						goto IL_0160;
					case 2:
						{
							<>1__state = -4;
							goto IL_01b2;
						}
						IL_00ac:
						array = ((AIAnnotation)<citation>5__4).AnnotatedRegions?.OfType<TextSpanAnnotatedRegion>().ToArray();
						if (array == null || array.Length <= 0)
						{
							break;
						}
						<>7__wrap4 = array;
						<>7__wrap5 = 0;
						goto IL_0160;
						IL_01b2:
						<citation>5__4 = null;
						goto IL_01b9;
						IL_01d6:
						do
						{
							if (<>7__wrap1.MoveNext())
							{
								current = <>7__wrap1.Current;
								continue;
							}
							<>m__Finally1();
							<>7__wrap1 = null;
							return false;
						}
						while (current.Annotations == null);
						<>7__wrap2 = current.Annotations.GetEnumerator();
						<>1__state = -4;
						goto IL_01b9;
						IL_0160:
						if (<>7__wrap5 < <>7__wrap4.Length)
						{
							TextSpanAnnotatedRegion val = <>7__wrap4[<>7__wrap5];
							<>2__current = OpenAIChatModelFactory.ChatMessageAnnotation(val.StartIndex.GetValueOrDefault(), val.EndIndex.GetValueOrDefault(), <citation>5__4.Url, <citation>5__4.Title);
							<>1__state = 1;
							return true;
						}
						<>7__wrap4 = null;
						goto IL_01b2;
						IL_01b9:
						while (<>7__wrap2.MoveNext())
						{
							AIAnnotation current2 = <>7__wrap2.Current;
							<citation>5__4 = (CitationAnnotation)(object)((current2 is CitationAnnotation) ? current2 : null);
							if (<citation>5__4 == null)
							{
								continue;
							}
							goto IL_00ac;
						}
						<>m__Finally2();
						<>7__wrap2 = null;
						goto IL_01d6;
					}
					<>2__current = OpenAIChatModelFactory.ChatMessageAnnotation(0, 0, <citation>5__4.Url, <citation>5__4.Title);
					<>1__state = 2;
					return true;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

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

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

			private void <>m__Finally2()
			{
				<>1__state = -3;
				if (<>7__wrap2 != null)
				{
					<>7__wrap2.Dispose();
				}
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<ChatMessageAnnotation> IEnumerable<ChatMessageAnnotation>.GetEnumerator()
			{
				<<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d = this;
				}
				else
				{
					<<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d = new <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d(0);
				}
				<<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d.contents = <>3__contents;
				return <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<ChatMessageAnnotation>)this).GetEnumerator();
			}
		}

		[CompilerGenerated]
		private sealed class <AsChatMessages>d__5 : IEnumerable<ChatMessage>, IEnumerable, IEnumerator<ChatMessage>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private ChatMessage <>2__current;

			private int <>l__initialThreadId;

			private IEnumerable<ChatMessage> messages;

			public IEnumerable<ChatMessage> <>3__messages;

			private IEnumerator<ChatMessage> <>7__wrap1;

			ChatMessage IEnumerator<ChatMessage>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

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

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if (num == -3 || num == 1)
				{
					try
					{
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<>7__wrap1 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				//IL_005a: Unknown result type (might be due to invalid IL or missing references)
				//IL_005f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0067: Expected O, but got Unknown
				//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
				//IL_0144: Unknown result type (might be due to invalid IL or missing references)
				//IL_0173: Unknown result type (might be due to invalid IL or missing references)
				//IL_019f: 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_01ee: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0200: Expected O, but got Unknown
				try
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						Throw.IfNull(messages, "messages");
						<>7__wrap1 = messages.GetEnumerator();
						<>1__state = -3;
						break;
					case 1:
						<>1__state = -3;
						break;
					}
					if (<>7__wrap1.MoveNext())
					{
						ChatMessage current = <>7__wrap1.Current;
						ChatMessage val = new ChatMessage
						{
							RawRepresentation = current
						};
						AssistantChatMessage val2 = (AssistantChatMessage)(object)((current is AssistantChatMessage) ? current : null);
						if (val2 == null)
						{
							UserChatMessage val3 = (UserChatMessage)(object)((current is UserChatMessage) ? current : null);
							if (val3 == null)
							{
								DeveloperChatMessage val4 = (DeveloperChatMessage)(object)((current is DeveloperChatMessage) ? current : null);
								if (val4 == null)
								{
									SystemChatMessage val5 = (SystemChatMessage)(object)((current is SystemChatMessage) ? current : null);
									if (val5 == null)
									{
										ToolChatMessage val6 = (ToolChatMessage)(object)((current is ToolChatMessage) ? current : null);
										if (val6 != null)
										{
											val.Role = ChatRole.Tool;
											val.Contents.Add((AIContent)new FunctionResultContent(val6.ToolCallId, <AsChatMessages>g__ToToolResult|5_0(((ChatMessage)val6).Content))
											{
												RawRepresentation = val6
											});
										}
									}
									else
									{
										val.Role = ChatRole.System;
										val.AuthorName = val5.ParticipantName;
										OpenAIChatClient.ConvertContentParts(((ChatMessage)val5).Content, val.Contents);
									}
								}
								else
								{
									val.Role = ChatRole.System;
									val.AuthorName = val4.ParticipantName;
									OpenAIChatClient.ConvertContentParts(((ChatMessage)val4).Content, val.Contents);
								}
							}
							else
							{
								val.Role = ChatRole.User;
								val.AuthorName = val3.ParticipantName;
								OpenAIChatClient.ConvertContentParts(((ChatMessage)val3).Content, val.Contents);
							}
						}
						else
						{
							val.Role = ChatRole.Assistant;
							val.AuthorName = val2.ParticipantName;
							OpenAIChatClient.ConvertContentParts(((ChatMessage)val2).Content, val.Contents);
							foreach (ChatToolCall toolCall in val2.ToolCalls)
							{
								FunctionCallContent val7 = OpenAIClientExtensions.ParseCallContent(toolCall.FunctionArguments, toolCall.Id, toolCall.FunctionName);
								((AIContent)val7).RawRepresentation = toolCall;
								val.Contents.Add((AIContent)(object)val7);
							}
						}
						<>2__current = val;
						<>1__state = 1;
						return true;
					}
					<>m__Finally1();
					<>7__wrap1 = null;
					return false;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

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

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

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<ChatMessage> IEnumerable<ChatMessage>.GetEnumerator()
			{
				<AsChatMessages>d__5 <AsChatMessages>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<AsChatMessages>d__ = this;
				}
				else
				{
					<AsChatMessages>d__ = new <AsChatMessages>d__5(0);
				}
				<AsChatMessages>d__.messages = <>3__messages;
				return <AsChatMessages>d__;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<ChatMessage>)this).GetEnumerator();
			}
		}

		[CompilerGenerated]
		private sealed class <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 : IAsyncEnumerable<StreamingChatCompletionUpdate>, IAsyncEnumerator<StreamingChatCompletionUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private StreamingChatCompletionUpdate <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private IAsyncEnumerable<ChatResponseUpdate> responseUpdates;

			public IAsyncEnumerable<ChatResponseUpdate> <>3__responseUpdates;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private ConfiguredCancelableAsyncEnumerable<ChatResponseUpdate>.Enumerator <>7__wrap1;

			private object <>7__wrap2;

			private int <>7__wrap3;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2;

			StreamingChatCompletionUpdate IAsyncEnumerator<StreamingChatCompletionUpdate>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

			private void MoveNext()
			{
				//IL_0223: Unknown result type (might be due to invalid IL or missing references)
				//IL_0231: Unknown result type (might be due to invalid IL or missing references)
				//IL_0244: Unknown result type (might be due to invalid IL or missing references)
				//IL_027a: Expected O, but got Unknown
				int num = <>1__state;
				try
				{
					ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							Throw.IfNull(responseUpdates, "responseUpdates");
							<>7__wrap1 = responseUpdates.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
							<>7__wrap2 = null;
							<>7__wrap3 = 0;
							goto case -5;
						}
						goto end_IL_0007;
					case -5:
					case -4:
					case 0:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -5)
							{
								if (num != -4)
								{
									if (num != 0)
									{
										goto IL_02a4;
									}
									awaiter2 = <>u__1;
									<>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
									num = (<>1__state = -1);
									goto IL_030f;
								}
								num = (<>1__state = -1);
								if (!<>w__disposeMode)
								{
									goto IL_02a4;
								}
							}
							else
							{
								num = (<>1__state = -1);
								if (!<>w__disposeMode)
								{
									goto IL_02a4;
								}
							}
							goto end_IL_008a;
							IL_030f:
							if (awaiter2.GetResult())
							{
								ChatResponseUpdate current = <>7__wrap1.Current;
								object rawRepresentation = current.RawRepresentation;
								StreamingChatCompletionUpdate val = (StreamingChatCompletionUpdate)((rawRepresentation is StreamingChatCompletionUpdate) ? rawRepresentation : null);
								if (val != null)
								{
									<>2__current = val;
									num = (<>1__state = -4);
								}
								else
								{
									AIContent? obj = ((IEnumerable<AIContent>)current.Contents).FirstOrDefault((Func<AIContent, bool>)((AIContent c) => c is UsageContent));
									UsageContent val2 = (UsageContent)(object)((obj is UsageContent) ? obj : null);
									ChatTokenUsage val3 = ((val2 != null) ? OpenAIChatModelFactory.ChatTokenUsage(((int?)val2.Details.OutputTokenCount).GetValueOrDefault(), ((int?)val2.Details.InputTokenCount).GetValueOrDefault(), ((int?)val2.Details.TotalTokenCount).GetValueOrDefault(), (ChatOutputTokenUsageDetails)null, (ChatInputTokenUsageDetails)null) : null);
									List<StreamingChatToolCallUpdate> list = current.Contents.OfType<FunctionCallContent>().Select((FunctionCallContent fcc, int index) => OpenAIChatModelFactory.StreamingChatToolCallUpdate(index, fcc.CallId, (ChatToolCallKind)0, fcc.Name, new BinaryData(JsonSerializer.SerializeToUtf8Bytes((object)fcc.Arguments, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(IDictionary<string, object>)))))).ToList();
									string responseId = current.ResponseId;
									ChatMessageContent val4 = new ChatMessageContent((IEnumerable<ChatMessageContentPart>)OpenAIChatClient.ToOpenAIChatContent(current.Contents));
									ChatMessageRole? val5 = ToChatMessageRole(current.Role);
									ChatFinishReason? val6 = ToChatFinishReason(current.FinishReason);
									DateTimeOffset valueOrDefault = current.CreatedAt.GetValueOrDefault();
									string modelId = current.ModelId;
									ChatTokenUsage val7 = val3;
									<>2__current = OpenAIChatModelFactory.StreamingChatCompletionUpdate(responseId, val4, (StreamingChatFunctionCallUpdate)null, (IEnumerable<StreamingChatToolCallUpdate>)list, val5, (string)null, (IEnumerable<ChatTokenLogProbabilityDetails>)null, (IEnumerable<ChatTokenLogProbabilityDetails>)null, val6, valueOrDefault, modelId, (ChatServiceTier?)null, (string)null, val7, (StreamingChatOutputAudioUpdate)null);
									num = (<>1__state = -5);
								}
								goto IL_0499;
							}
							goto end_IL_008a;
							IL_02a4:
							<>2__current = null;
							awaiter2 = <>7__wrap1.MoveNextAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter2;
								<AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_030f;
							end_IL_008a:;
						}
						catch (object obj2)
						{
							<>7__wrap2 = obj2;
						}
						<>2__current = null;
						awaiter = <>7__wrap1.DisposeAsync().GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__2 = awaiter;
							<AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
							return;
						}
						break;
					case 1:
						awaiter = <>u__2;
						<>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
						num = (<>1__state = -1);
						break;
					}
					awaiter.GetResult();
					object obj3 = <>7__wrap2;
					if (obj3 != null)
					{
						if (!(obj3 is Exception source))
						{
							throw obj3;
						}
						ExceptionDispatchInfo.Capture(source).Throw();
					}
					_ = <>7__wrap3;
					if (!<>w__disposeMode)
					{
						<>7__wrap2 = null;
						<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseUpdate>.Enumerator);
					}
					end_IL_0007:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseUpdate>.Enumerator);
					<>7__wrap2 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseUpdate>.Enumerator);
				<>7__wrap2 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_0499:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<StreamingChatCompletionUpdate> IAsyncEnumerable<StreamingChatCompletionUpdate>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 <AsOpenAIStreamingChatCompletionUpdatesAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<AsOpenAIStreamingChatCompletionUpdatesAsync>d__ = this;
				}
				else
				{
					<AsOpenAIStreamingChatCompletionUpdatesAsync>d__ = new <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4(-3);
				}
				<AsOpenAIStreamingChatCompletionUpdatesAsync>d__.responseUpdates = <>3__responseUpdates;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<AsOpenAIStreamingChatCompletionUpdatesAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<AsOpenAIStreamingChatCompletionUpdatesAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<AsOpenAIStreamingChatCompletionUpdatesAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <AsOpenAIStreamingChatCompletionUpdatesAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<StreamingChatCompletionUpdate>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<AsOpenAIStreamingChatCompletionUpdatesAsync>d__4 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		public static ChatTool AsOpenAIChatTool(this AIFunctionDeclaration function)
		{
			return OpenAIChatClient.ToOpenAIChatTool(Throw.IfNull<AIFunctionDeclaration>(function, "function"));
		}

		public static ChatResponseFormat? AsOpenAIChatResponseFormat(this ChatResponseFormat? format, ChatOptions? options = null)
		{
			return OpenAIChatClient.ToOpenAIChatResponseFormat(format, options);
		}

		public static IEnumerable<ChatMessage> AsOpenAIChatMessages(this IEnumerable<ChatMessage> messages, ChatOptions? options = null)
		{
			return OpenAIChatClient.ToOpenAIChatMessages(Throw.IfNull(messages, "messages"), options);
		}

		public static ChatCompletion AsOpenAIChatCompletion(this ChatResponse response)
		{
			//IL_0039: 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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_023c: Expected O, but got Unknown
			Throw.IfNull<ChatResponse>(response, "response");
			object rawRepresentation = response.RawRepresentation;
			ChatCompletion val = (ChatCompletion)((rawRepresentation is ChatCompletion) ? rawRepresentation : null);
			if (val != null)
			{
				return val;
			}
			ChatMessage val2 = response.Messages.LastOrDefault();
			ChatMessageRole val3 = ToChatMessageRole((val2 != null) ? new ChatRole?(val2.Role) : null);
			ChatFinishReason val4 = ToChatFinishReason(response.FinishReason);
			UsageDetails usage = response.Usage;
			int valueOrDefault = ((int?)((usage != null) ? usage.OutputTokenCount : null)).GetValueOrDefault();
			UsageDetails usage2 = response.Usage;
			int valueOrDefault2 = ((int?)((usage2 != null) ? usage2.InputTokenCount : null)).GetValueOrDefault();
			UsageDetails usage3 = response.Usage;
			ChatTokenUsage val5 = OpenAIChatModelFactory.ChatTokenUsage(valueOrDefault, valueOrDefault2, ((int?)((usage3 != null) ? usage3.TotalTokenCount : null)).GetValueOrDefault(), (ChatOutputTokenUsageDetails)null, (ChatInputTokenUsageDetails)null);
			IEnumerable<ChatToolCall> enumerable = ((val2 != null) ? (from c in val2.Contents.OfType<FunctionCallContent>()
				select ChatToolCall.CreateFunctionToolCall(c.CallId, c.Name, new BinaryData(JsonSerializer.SerializeToUtf8Bytes((object)c.Arguments, AIJsonUtilities.DefaultOptions.GetTypeInfo(typeof(IDictionary<string, object>)))))) : null);
			string responseId = response.ResponseId;
			ChatMessageContent val6 = new ChatMessageContent((IEnumerable<ChatMessageContentPart>)OpenAIChatClient.ToOpenAIChatContent(((val2 != null) ? val2.Contents : null) ?? new List<AIContent>()));
			DateTimeOffset valueOrDefault3 = response.CreatedAt.GetValueOrDefault();
			string modelId = response.ModelId;
			ChatTokenUsage val7 = val5;
			ChatOutputAudio val8 = ((val2 != null) ? (from dc in val2.Contents.OfType<DataContent>()
				where dc.HasTopLevelMediaType("audio")
				select dc into a
				select OpenAIChatModelFactory.ChatOutputAudio(new BinaryData(a.Data), (string)null, (string)null, default(DateTimeOffset))).FirstOrDefault() : null);
			IEnumerable<ChatMessageAnnotation> enumerable2 = ConvertAnnotations((val2 != null) ? val2.Contents : null);
			return OpenAIChatModelFactory.ChatCompletion(responseId, val4, val6, (string)null, enumerable, val3, (ChatFunctionCall)null, (IEnumerable<ChatTokenLogProbabilityDetails>)null, (IEnumerable<ChatTokenLogProbabilityDetails>)null, valueOrDefault3, modelId, (ChatServiceTier?)null, (string)null, val7, val8, enumerable2);
			[IteratorStateMachine(typeof(<<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d))]
			static IEnumerable<ChatMessageAnnotation> ConvertAnnotations(IEnumerable<AIContent>? contents)
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <<AsOpenAIChatCompletion>g__ConvertAnnotations|3_1>d(-2)
				{
					<>3__contents = contents
				};
			}
		}

		[AsyncIteratorStateMachine(typeof(<AsOpenAIStreamingChatCompletionUpdatesAsync>d__4))]
		public static IAsyncEnumerable<StreamingChatCompletionUpdate> AsOpenAIStreamingChatCompletionUpdatesAsync(this IAsyncEnumerable<ChatResponseUpdate> responseUpdates, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			return new <AsOpenAIStreamingChatCompletionUpdatesAsync>d__4(-2)
			{
				<>3__responseUpdates = responseUpdates,
				<>3__cancellationToken = cancellationToken
			};
		}

		[IteratorStateMachine(typeof(<AsChatMessages>d__5))]
		public static IEnumerable<ChatMessage> AsChatMessages(this IEnumerable<ChatMessage> messages)
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <AsChatMessages>d__5(-2)
			{
				<>3__messages = messages
			};
		}

		public static ChatResponse AsChatResponse(this ChatCompletion chatCompletion, ChatCompletionOptions? options = null)
		{
			return OpenAIChatClient.FromOpenAIChatCompletion(Throw.IfNull<ChatCompletion>(chatCompletion, "chatCompletion"), options);
		}

		public static IAsyncEnumerable<ChatResponseUpdate> AsChatResponseUpdatesAsync(this IAsyncEnumerable<StreamingChatCompletionUpdate> chatCompletionUpdates, ChatCompletionOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return OpenAIChatClient.FromOpenAIStreamingChatCompletionAsync(Throw.IfNull(chatCompletionUpdates, "chatCompletionUpdates"), options, cancellationToken);
		}

		private static ChatMessageRole ToChatMessageRole(ChatRole? role)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: 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_0074: Unknown result type (might be due to invalid IL or missing references)
			object obj;
			if (!role.HasValue)
			{
				obj = null;
			}
			else
			{
				ChatRole valueOrDefault = role.GetValueOrDefault();
				obj = ((ChatRole)(ref valueOrDefault)).Value;
			}
			return (ChatMessageRole)((string)obj switch
			{
				"user" => 1, 
				"function" => 4, 
				"tool" => 3, 
				"developer" => 5, 
				"system" => 0, 
				_ => 2, 
			});
		}

		private static ChatFinishReason ToChatFinishReason(ChatFinishReason? finishReason)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			object obj;
			if (!finishReason.HasValue)
			{
				obj = null;
			}
			else
			{
				ChatFinishReason valueOrDefault = finishReason.GetValueOrDefault();
				obj = ((ChatFinishReason)(ref valueOrDefault)).Value;
			}
			return (ChatFinishReason)((string)obj switch
			{
				"length" => 1, 
				"content_filter" => 2, 
				"tool_calls" => 3, 
				"function_call" => 4, 
				_ => 0, 
			});
		}

		[CompilerGenerated]
		internal static object <AsChatMessages>g__ToToolResult|5_0(ChatMessageContent content)
		{
			if (((Collection<ChatMessageContentPart>)(object)content).Count == 1)
			{
				ChatMessageContentPart val = ((Collection<ChatMessageContentPart>)(object)content)[0];
				if (val != null)
				{
					string text = val.Text;
					if (text != null)
					{
						return text;
					}
				}
			}
			MemoryStream memoryStream = new MemoryStream();
			using Utf8JsonWriter utf8JsonWriter = new Utf8JsonWriter(memoryStream, new JsonWriterOptions
			{
				Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
			});
			foreach (ChatMessageContentPart item in (Collection<ChatMessageContentPart>)(object)content)
			{
				((IJsonModel<ChatMessageContentPart>)(object)item).Write(utf8JsonWriter, ModelReaderWriterOptions.Json);
			}
			return JsonElement.Parse((ReadOnlySpan<byte>)memoryStream.GetBuffer().AsSpan(0, (int)memoryStream.Position), default(JsonDocumentOptions));
		}
	}
}
namespace OpenAI.Assistants
{
	public static class MicrosoftExtensionsAIAssistantsExtensions
	{
		public static FunctionToolDefinition AsOpenAIAssistantsFunctionToolDefinition(this AIFunctionDeclaration function)
		{
			return OpenAIAssistantsChatClient.ToOpenAIAssistantsFunctionToolDefinition(Throw.IfNull<AIFunctionDeclaration>(function, "function"));
		}
	}
}
namespace Microsoft.Extensions.AI
{
	internal sealed class OpenAIAssistantsChatClient : IChatClient, IDisposable
	{
		private sealed class ToolDefinitionNameEqualityComparer : IEqualityComparer<ToolDefinition>
		{
			public static ToolDefinitionNameEqualityComparer Instance { get; } = new ToolDefinitionNameEqualityComparer();


			public bool Equals(ToolDefinition? x, ToolDefinition? y)
			{
				FunctionToolDefinition val = (FunctionToolDefinition)(object)((x is FunctionToolDefinition) ? x : null);
				if (val != null)
				{
					FunctionToolDefinition val2 = (FunctionToolDefinition)(object)((y is FunctionToolDefinition) ? y : null);
					if (val2 != null)
					{
						return val.FunctionName.Equals(val2.FunctionName, StringComparison.Ordinal);
					}
				}
				return EqualityComparer<ToolDefinition>.Default.Equals(x, y);
			}

			public int GetHashCode(ToolDefinition obj)
			{
				FunctionToolDefinition val = (FunctionToolDefinition)(object)((obj is FunctionToolDefinition) ? obj : null);
				if (val == null)
				{
					return EqualityComparer<ToolDefinition>.Default.GetHashCode(obj);
				}
				return StringHash.GetHashCode(val.FunctionName, StringComparison.Ordinal);
			}
		}

		[CompilerGenerated]
		private sealed class <GetStreamingResponseAsync>d__9 : IAsyncEnumerable<ChatResponseUpdate>, IAsyncEnumerator<ChatResponseUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private ChatResponseUpdate <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private IEnumerable<ChatMessage> messages;

			public IEnumerable<ChatMessage> <>3__messages;

			public OpenAIAssistantsChatClient <>4__this;

			private ChatOptions options;

			public ChatOptions <>3__options;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private RunCreationOptions <runOptions>5__2;

			private ToolResources <toolResources>5__3;

			private List<FunctionResultContent> <toolResults>5__4;

			private string <threadId>5__5;

			private ThreadRun <threadRun>5__6;

			private string <responseId>5__7;

			private ConfiguredValueTaskAwaitable<(RunCreationOptions RunOptions, ToolResources? Resources, List<FunctionResultContent>? ToolResults)>.ConfiguredValueTaskAwaiter <>u__1;

			private ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator <>7__wrap7;

			private object <>7__wrap8;

			private int <>7__wrap9;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__2;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__3;

			private ConfiguredTaskAwaitable<ClientResult<AssistantThread>>.ConfiguredTaskAwaiter <>u__4;

			private ConfiguredTaskAwaitable<ClientResult<ThreadRun>>.ConfiguredTaskAwaiter <>u__5;

			private ConfiguredCancelableAsyncEnumerable<StreamingUpdate>.Enumerator <>7__wrap10;

			private StreamingUpdate <update>5__12;

			private RunStepDetailsUpdate <details>5__13;

			ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GetStreamingResponseAsync>d__9(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
				//IL_096b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0970: Unknown result type (might be due to invalid IL or missing references)
				//IL_0981: Unknown result type (might be due to invalid IL or missing references)
				//IL_098f: Expected O, but got Unknown
				//IL_0171: 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_0177: Unknown result type (might be due to invalid IL or missing references)
				//IL_0186: Unknown result type (might be due to invalid IL or missing references)
				//IL_019d: Expected O, but got Unknown
				//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
				//IL_03ea: Unknown result type (might be due to invalid IL or missing references)
				//IL_03ef: Unknown result type (might be due to invalid IL or missing references)
				//IL_03fd: Expected O, but got Unknown
				//IL_0204: Unknown result type (might be due to invalid IL or missing references)
				//IL_0209: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c8a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c8f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c9b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0ca7: Unknown result type (might be due to invalid IL or missing references)
				//IL_0cb3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0cbf: Unknown result type (might be due to invalid IL or missing references)
				//IL_0ccb: Unknown result type (might be due to invalid IL or missing references)
				//IL_0ccc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0ce0: Expected O, but got Unknown
				//IL_021a: Unknown result type (might be due to invalid IL or missing references)
				//IL_021f: Unknown result type (might be due to invalid IL or missing references)
				//IL_06d7: Unknown result type (might be due to invalid IL or missing references)
				//IL_06dc: Unknown result type (might be due to invalid IL or missing references)
				//IL_06e8: Unknown result type (might be due to invalid IL or missing references)
				//IL_06f4: Unknown result type (might be due to invalid IL or missing references)
				//IL_070b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0717: Unknown result type (might be due to invalid IL or missing references)
				//IL_0729: Unknown result type (might be due to invalid IL or missing references)
				//IL_0731: Unknown result type (might be due to invalid IL or missing references)
				//IL_073d: Unknown result type (might be due to invalid IL or missing references)
				//IL_073e: Unknown result type (might be due to invalid IL or missing references)
				//IL_074f: Expected O, but got Unknown
				//IL_086c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0871: Unknown result type (might be due to invalid IL or missing references)
				//IL_0882: Unknown result type (might be due to invalid IL or missing references)
				//IL_08a9: Unknown result type (might be due to invalid IL or missing references)
				//IL_08b3: Expected O, but got Unknown
				//IL_08b8: Unknown result type (might be due to invalid IL or missing references)
				//IL_08c6: Expected O, but got Unknown
				//IL_08c7: Unknown result type (might be due to invalid IL or missing references)
				//IL_08df: Unknown result type (might be due to invalid IL or missing references)
				//IL_08e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_08f0: Unknown result type (might be due to invalid IL or missing references)
				//IL_08fc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0908: Unknown result type (might be due to invalid IL or missing references)
				//IL_0914: Unknown result type (might be due to invalid IL or missing references)
				//IL_0925: Expected O, but got Unknown
				//IL_0ae9: Unknown result type (might be due to invalid IL or missing references)
				//IL_0aed: Unknown result type (might be due to invalid IL or missing references)
				//IL_0af2: Unknown result type (might be due to invalid IL or missing references)
				//IL_09df: Unknown result type (might be due to invalid IL or missing references)
				//IL_09e4: Unknown result type (might be due to invalid IL or missing references)
				//IL_09f4: Expected O, but got Unknown
				//IL_0a59: Unknown result type (might be due to invalid IL or missing references)
				//IL_0a71: Unknown result type (might be due to invalid IL or missing references)
				//IL_0a76: Unknown result type (might be due to invalid IL or missing references)
				//IL_0a82: Unknown result type (might be due to invalid IL or missing references)
				//IL_0a8e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0a9a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0aa6: Unknown result type (might be due to invalid IL or missing references)
				//IL_0ab7: Expected O, but got Unknown
				//IL_0768: Unknown result type (might be due to invalid IL or missing references)
				//IL_076d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0780: Unknown result type (might be due to invalid IL or missing references)
				//IL_0793: Unknown result type (might be due to invalid IL or missing references)
				//IL_07ab: Expected O, but got Unknown
				//IL_07a6: Unknown result type (might be due to invalid IL or missing references)
				//IL_07b0: Expected O, but got Unknown
				//IL_0b07: Unknown result type (might be due to invalid IL or missing references)
				//IL_0b00: Unknown result type (might be due to invalid IL or missing references)
				//IL_0a23: Unknown result type (might be due to invalid IL or missing references)
				//IL_0a2d: Expected O, but got Unknown
				//IL_0b18: Unknown result type (might be due to invalid IL or missing references)
				//IL_0b1d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0b29: Unknown result type (might be due to invalid IL or missing references)
				//IL_0b35: Unknown result type (might be due to invalid IL or missing references)
				//IL_0b41: Unknown result type (might be due to invalid IL or missing references)
				//IL_0b49: Unknown result type (might be due to invalid IL or missing references)
				//IL_0b57: Expected O, but got Unknown
				//IL_0be3: Unknown result type (might be due to invalid IL or missing references)
				//IL_0bea: Expected O, but got Unknown
				//IL_0bcc: Unknown result type (might be due to invalid IL or missing references)
				//IL_0bd6: Expected O, but got Unknown
				//IL_0c06: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c0b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c13: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c1b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c20: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c2d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c3f: Expected O, but got Unknown
				//IL_0c44: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c4c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0c59: Expected O, but got Unknown
				int num = <>1__state;
				OpenAIAssistantsChatClient openAIAssistantsChatClient = <>4__this;
				try
				{
					ConfiguredValueTaskAwaitable<(RunCreationOptions, ToolResources, List<FunctionResultContent>)>.ConfiguredValueTaskAwaiter awaiter5;
					ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter4;
					ConfiguredTaskAwaitable<ClientResult<AssistantThread>>.ConfiguredTaskAwaiter awaiter3;
					ConfiguredTaskAwaitable<ClientResult<ThreadRun>>.ConfiguredTaskAwaiter awaiter2;
					ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter;
					IAsyncEnumerable<StreamingUpdate> source;
					(RunCreationOptions, ToolResources, List<FunctionResultContent>) result;
					(RunCreationOptions, ToolResources, List<FunctionResultContent>) tuple;
					ChatOptions obj2;
					ThreadCreationOptions val;
					IEnumerator<ThreadInitializationMessage> enumerator;
					ClientResult<AssistantThread> result2;
					ClientResult<AssistantThread> val12;
					ClientResult<ThreadRun> result3;
					object obj3;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							Throw.IfNull(messages, "messages");
							<>2__current = null;
							awaiter5 = openAIAssistantsChatClient.CreateRunOptionsAsync(messages, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter5.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter5;
								<GetStreamingResponseAsync>d__9 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter5, ref stateMachine);
								return;
							}
							goto IL_00fc;
						}
						goto end_IL_000e;
					case 0:
						awaiter5 = <>u__1;
						<>u__1 = default(ConfiguredValueTaskAwaitable<(RunCreationOptions, ToolResources, List<FunctionResultContent>)>.ConfiguredValueTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_00fc;
					case 1:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter6;
							if (num != 1)
							{
								<>2__current = null;
								awaiter6 = <>7__wrap7.MoveNextAsync().GetAwaiter();
								if (!awaiter6.IsCompleted)
								{
									num = (<>1__state = 1);
									<>u__2 = awaiter6;
									<GetStreamingResponseAsync>d__9 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter6, ref stateMachine);
									return;
								}
							}
							else
							{
								awaiter6 = <>u__2;
								<>u__2 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
								num = (<>1__state = -1);
							}
							if (awaiter6.GetResult())
							{
								ThreadRun current = <>7__wrap7.Current;
								if (current.Status != RunStatus.Completed && current.Status != RunStatus.Cancelled && current.Status != RunStatus.Failed && current.Status != RunStatus.Expired)
								{
									<threadRun>5__6 = current;
								}
							}
						}
						catch (object obj)
						{
							<>7__wrap8 = obj;
						}
						<>2__current = null;
						awaiter4 = <>7__wrap7.DisposeAsync().GetAwaiter();
						if (!awaiter4.IsCompleted)
						{
							num = (<>1__state = 2);
							<>u__3 = awaiter4;
							<GetStreamingResponseAsync>d__9 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter4, ref stateMachine);
							return;
						}
						goto IL_032c;
					case 2:
						awaiter4 = <>u__3;
						<>u__3 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_032c;
					case 3:
						awaiter3 = <>u__4;
						<>u__4 = default(ConfiguredTaskAwaitable<ClientResult<AssistantThread>>.ConfiguredTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_04d9;
					case 4:
						awaiter2 = <>u__5;
						<>u__5 = default(ConfiguredTaskAwaitable<ClientResult<ThreadRun>>.ConfiguredTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_0590;
					case -8:
					case -7:
					case -6:
					case -5:
					case -4:
					case 5:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter7;
							StreamingUpdate obj4;
							ThreadUpdate val2;
							StreamingUpdate obj5;
							RunUpdate val3;
							IReadOnlyList<RunStepUpdateCodeInterpreterOutput> codeInterpreterOutputs;
							CodeInterpreterToolResultContent val10;
							IEnumerator<RunStepUpdateCodeInterpreterOutput> enumerator2;
							switch (num)
							{
							case -4:
								num = (<>1__state = -1);
								if (<>w__disposeMode)
								{
									break;
								}
								goto IL_0d05;
							case -5:
								num = (<>1__state = -1);
								if (<>w__disposeMode)
								{
									break;
								}
								goto IL_094a;
							case -6:
								num = (<>1__state = -1);
								if (<>w__disposeMode)
								{
									break;
								}
								goto IL_0d05;
							case -7:
								num = (<>1__state = -1);
								if (<>w__disposeMode)
								{
									break;
								}
								goto IL_0d05;
							case -8:
								num = (<>1__state = -1);
								if (<>w__disposeMode)
								{
									break;
								}
								goto IL_0d05;
							default:
								<>2__current = null;
								awaiter7 = <>7__wrap10.MoveNextAsync().GetAwaiter();
								if (!awaiter7.IsCompleted)
								{
									num = (<>1__state = 5);
									<>u__2 = awaiter7;
									<GetStreamingResponseAsync>d__9 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter7, ref stateMachine);
									return;
								}
								goto IL_0d7e;
							case 5:
								{
									awaiter7 = <>u__2;
									<>u__2 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
									num = (<>1__state = -1);
									goto IL_0d7e;
								}
								IL_0d05:
								<details>5__13 = null;
								<update>5__12 = null;
								goto default;
								IL_0c89:
								<>2__current = new ChatResponseUpdate
								{
									AuthorName = openAIAssistantsChatClient._assistantId,
									ConversationId = <threadId>5__5,
									MessageId = <responseId>5__7,
									RawRepresentation = <update>5__12,
									ResponseId = <responseId>5__7,
									Role = ChatRole.Assistant
								};
								num = (<>1__state = -8);
								goto IL_0f99;
								IL_0d7e:
								if (!awaiter7.GetResult())
								{
									break;
								}
								<update>5__12 = <>7__wrap10.Current;
								obj4 = <update>5__12;
								val2 = (ThreadUpdate)(object)((obj4 is ThreadUpdate) ? obj4 : null);
								if (val2 != null)
								{
									if (<threadId>5__5 == null)
									{
										<threadId>5__5 = ((StreamingUpdate<AssistantThread>)(object)val2).Value.Id;
									}
									goto IL_0c89;
								}
								obj5 = <update>5__12;
								val3 = (RunUpdate)(object)((obj5 is RunUpdate) ? obj5 : null);
								if (val3 == null)
								{
									ref RunStepDetailsUpdate reference = ref <details>5__13;
									StreamingUpdate obj6 = <update>5__12;
									reference = (RunStepDetailsUpdate)(object)((obj6 is RunStepDetailsUpdate) ? obj6 : null);
									if (<details>5__13 == null)
									{
										StreamingUpdate obj7 = <update>5__12;
										MessageContentUpdate val4 = (MessageContentUpdate)(object)((obj7 is MessageContentUpdate) ? obj7 : null);
										if (val4 == null)
										{
											goto IL_0c89;
										}
										ChatResponseUpdate val5 = new ChatResponseUpdate((ChatRole?)((val4.Role == (MessageRole?)0) ? ChatRole.User : ChatRole.Assistant), val4.Text)
										{
											AuthorName = openAIAssistantsChatClient._assistantId,
											ConversationId = <threadId>5__5,
											MessageId = <responseId>5__7,
											RawRepresentation = val4,
											ResponseId = <responseId>5__7
										};
										TextAnnotationUpdate textAnnotation = val4.TextAnnotation;
										if (textAnnotation != null)
										{
											string text2 = null;
											string toolName = null;
											if (!string.IsNullOrWhiteSpace(textAnnotation.InputFileId))
											{
												text2 = textAnnotation.InputFileId;
												toolName = "file_search";
											}
											else if (!string.IsNullOrWhiteSpace(textAnnotation.OutputFileId))
											{
												text2 = textAnnotation.OutputFileId;
												toolName = "code_interpreter";
											}
											if (text2 != null)
											{
												if (val5.Contents.Count == 0)
												{
													val5.Contents.Add((AIContent)new TextContent(string.Empty));
												}
												TextContent val6 = (TextContent)val5.Contents[0];
												(((AIContent)val6).Annotations ?? (((AIContent)val6).Annotations = new List<AIAnnotation>())).Add((AIAnnotation)new CitationAnnotation
												{
													RawRepresentation = textAnnotation,
													AnnotatedRegions = new List<AnnotatedRegion>(1) { (AnnotatedRegion)new TextSpanAnnotatedRegion
													{
														StartIndex = textAnnotation.StartIndex,
														EndIndex = textAnnotation.EndIndex
													} },
													FileId = text2,
													ToolName = toolName
												});
											}
										}
										<>2__current = val5;
										num = (<>1__state = -7);
									}
									else
									{
										if (string.IsNullOrEmpty(<details>5__13.CodeInterpreterInput))
										{
											goto IL_094a;
										}
										CodeInterpreterToolCallContent item = new CodeInterpreterToolCallContent
										{
											CallId = <details>5__13.ToolCallId,
											Inputs = new List<AIContent>(1) { (AIContent)new DataContent((ReadOnlyMemory<byte>)Encoding.UTF8.GetBytes(<details>5__13.CodeInterpreterInput), "text/x-python") },
											RawRepresentation = <details>5__13
										};
										<>2__current = new ChatResponseUpdate((ChatRole?)ChatRole.Assistant, (IList<AIContent>)new List<AIContent>(1) { (AIContent)(object)item })
										{
											AuthorName = openAIAssistantsChatClient._assistantId,
											ConversationId = <threadId>5__5,
											MessageId = <responseId>5__7,
											RawRepresentation = <update>5__12,
											ResponseId = <responseId>5__7
										};
										num = (<>1__state = -5);
									}
								}
								else
								{
									if (<threadId>5__5 == null)
									{
										<threadId>5__5 = ((StreamingUpdate<ThreadRun>)(object)val3).Value.ThreadId;
									}
									if (<responseId>5__7 == null)
									{
										<responseId>5__7 = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Id;
									}
									ChatResponseUpdate val7 = new ChatResponseUpdate
									{
										AuthorName = openAIAssistantsChatClient._assistantId,
										ConversationId = <threadId>5__5,
										CreatedAt = ((StreamingUpdate<ThreadRun>)(object)val3).Value.CreatedAt,
										MessageId = <responseId>5__7,
										ModelId = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Model,
										RawRepresentation = val3,
										ResponseId = <responseId>5__7,
										Role = ChatRole.Assistant
									};
									RunTokenUsage usage = ((StreamingUpdate<ThreadRun>)(object)val3).Value.Usage;
									if (usage != null)
									{
										val7.Contents.Add((AIContent)new UsageContent(new UsageDetails
										{
											InputTokenCount = usage.InputTokenCount,
											OutputTokenCount = usage.OutputTokenCount,
											TotalTokenCount = usage.TotalTokenCount
										}));
									}
									RequiredActionUpdate val8 = (RequiredActionUpdate)(object)((val3 is RequiredActionUpdate) ? val3 : null);
									if (val8 != null)
									{
										string toolCallId = val8.ToolCallId;
										if (toolCallId != null)
										{
											string functionName = val8.FunctionName;
											if (functionName != null)
											{
												FunctionCallContent val9 = OpenAIClientExtensions.ParseCallContent(val8.FunctionArguments, JsonSerializer.Serialize(new string[2]
												{
													((StreamingUpdate<ThreadRun>)(object)val3).Value.Id,
													toolCallId
												}, OpenAIJsonContext.Default.StringArray), functionName);
												((AIContent)val9).RawRepresentation = val3;
												val7.Contents.Add((AIContent)(object)val9);
											}
										}
									}
									<>2__current = val7;
									num = (<>1__state = -4);
								}
								goto IL_0f99;
								IL_094a:
								codeInterpreterOutputs = <details>5__13.CodeInterpreterOutputs;
								if (codeInterpreterOutputs == null || codeInterpreterOutputs.Count <= 0)
								{
									goto IL_0d05;
								}
								val10 = new CodeInterpreterToolResultContent
								{
									CallId = <details>5__13.ToolCallId,
									RawRepresentation = <details>5__13
								};
								enumerator2 = <details>5__13.CodeInterpreterOutputs.GetEnumerator();
								try
								{
									while (enumerator2.MoveNext())
									{
										RunStepUpdateCodeInterpreterOutput current3 = enumerator2.Current;
										if (current3.ImageFileId != null)
										{
											CodeInterpreterToolResultContent val11 = val10;
											(val11.Outputs ?? (val11.Outputs = new List<AIContent>())).Add((AIContent)new HostedFileContent(current3.ImageFileId)
											{
												MediaType = "image/*"
											});
										}
										string logs = current3.Logs;
										if (logs != null)
										{
											CodeInterpreterToolResultContent val11 = val10;
											(val11.Outputs ?? (val11.Outputs = new List<AIContent>())).Add((AIContent)new TextContent(logs));
										}
									}
								}
								finally
								{
									if (num == -1)
									{
										enumerator2?.Dispose();
									}
								}
								if (<>w__disposeMode)
								{
									break;
								}
								<>2__current = new ChatResponseUpdate((ChatRole?)ChatRole.Assistant, (IList<AIContent>)new List<AIContent>(1) { (AIContent)(object)val10 })
								{
									AuthorName = openAIAssistantsChatClient._assistantId,
									ConversationId = <threadId>5__5,
									MessageId = <responseId>5__7,
									RawRepresentation = <update>5__12,
									ResponseId = <responseId>5__7
								};
								num = (<>1__state = -6);
								goto IL_0f99;
							}
						}
						catch (object obj)
						{
							<>7__wrap8 = obj;
						}
						<>2__current = null;
						awaiter = <>7__wrap10.DisposeAsync().GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 6);
							<>u__3 = awaiter;
							<GetStreamingResponseAsync>d__9 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
							return;
						}
						break;
					case 6:
						{
							awaiter = <>u__3;
							<>u__3 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
							num = (<>1__state = -1);
							break;
						}
						IL_05c4:
						<responseId>5__7 = null;
						<>7__wrap10 = source.ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
						<>7__wrap8 = null;
						<>7__wrap9 = 0;
						goto case -8;
						IL_00fc:
						result = awaiter5.GetResult();
						tuple = result;
						<runOptions>5__2 = tuple.Item1;
						<toolResources>5__3 = tuple.Item2;
						<toolResults>5__4 = tuple.Item3;
						obj2 = options;
						<threadId>5__5 = ((obj2 != null) ? obj2.ConversationId : null) ?? openAIAssistantsChatClient._defaultThreadId;
						<threadRun>5__6 = null;
						if (<threadId>5__5 != null)
						{
							<>7__wrap7 = ((IAsyncEnumerable<ThreadRun>)openAIAssistantsChatClient._client.GetRunsAsync(<threadId>5__5, new RunCollectionOptions
							{
								Order = RunCollectionOrder.Descending,
								PageSizeLimit = 1
							}, cancellationToken)).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
							<>7__wrap8 = null;
							<>7__wrap9 = 0;
							goto case 1;
						}
						goto IL_0382;
						IL_032c:
						awaiter4.GetResult();
						obj3 = <>7__wrap8;
						if (obj3 != null)
						{
							if (!(obj3 is Exception source2))
							{
								throw obj3;
							}
							ExceptionDispatchInfo.Capture(source2).Throw();
						}
						_ = <>7__wrap9;
						if (!<>w__disposeMode)
						{
							<>7__wrap8 = null;
							<>7__wrap7 = default(ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator);
							goto IL_0382;
						}
						goto end_IL_000e;
						IL_05a0:
						source = (IAsyncEnumerable<StreamingUpdate>)openAIAssistantsChatClient._client.CreateRunStreamingAsync(<threadId>5__5, openAIAssistantsChatClient._assistantId, <runOptions>5__2, cancellationToken);
						goto IL_05c4;
						IL_0382:
						if (<threadRun>5__6 != null)
						{
							List<ToolOutput> toolOutputs;
							string text = ConvertFunctionResultsToToolOutput(<toolResults>5__4, out toolOutputs);
							if (text != null && text == <threadRun>5__6.Id)
							{
								source = (IAsyncEnumerable<StreamingUpdate>)openAIAssistantsChatClient._client.SubmitToolOutputsToRunStreamingAsync(<threadRun>5__6.ThreadId, <threadRun>5__6.Id, (IEnumerable<ToolOutput>)toolOutputs, cancellationToken);
								goto IL_05c4;
							}
						}
						if (<threadId>5__5 != null)
						{
							if (<threadRun>5__6 != null)
							{
								<>2__current = null;
								awaiter2 = openAIAssistantsChatClient._client.CancelRunAsync(<threadId>5__5, <threadRun>5__6.Id, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
								if (!awaiter2.IsCompleted)
								{
									num = (<>1__state = 4);
									<>u__5 = awaiter2;
									<GetStreamingResponseAsync>d__9 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
									return;
								}
								goto IL_0590;
							}
							goto IL_05a0;
						}
						val = new ThreadCreationOptions
						{
							ToolResources = <toolResources>5__3
						};
						enumerator = <runOptions>5__2.AdditionalMessages.GetEnumerator();
						try
						{
							while (enumerator.MoveNext())
							{
								ThreadInitializationMessage current2 = enumerator.Current;
								val.InitialMessages.Add(current2);
							}
						}
						finally
						{
							if (num == -1)
							{
								enumerator?.Dispose();
							}
						}
						if (!<>w__disposeMode)
						{
							<runOptions>5__2.AdditionalMessages.Clear();
							<>2__current = null;
							awaiter3 = openAIAssistantsChatClient._client.CreateThreadAsync(val, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter3.IsCompleted)
							{
								num = (<>1__state = 3);
								<>u__4 = awaiter3;
								<GetStreamingResponseAsync>d__9 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine);
								return;
							}
							goto IL_04d9;
						}
						goto end_IL_000e;
						IL_04d9:
						result2 = awaiter3.GetResult();
						val12 = result2;
						<threadId>5__5 = val12.Value.Id;
						goto IL_05a0;
						IL_0590:
						result3 = awaiter2.GetResult();
						<threadRun>5__6 = null;
						goto IL_05a0;
					}
					awaiter.GetResult();
					obj3 = <>7__wrap8;
					if (obj3 != null)
					{
						if (!(obj3 is Exception source3))
						{
							throw obj3;
						}
						ExceptionDispatchInfo.Capture(source3).Throw();
					}
					_ = <>7__wrap9;
					if (!<>w__disposeMode)
					{
						<>7__wrap8 = null;
						<>7__wrap10 = default(ConfiguredCancelableAsyncEnumerable<StreamingUpdate>.Enumerator);
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<runOptions>5__2 = null;
					<toolResources>5__3 = null;
					<toolResults>5__4 = null;
					<threadId>5__5 = null;
					<threadRun>5__6 = null;
					<responseId>5__7 = null;
					<>7__wrap7 = default(ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator);
					<>7__wrap8 = null;
					<>7__wrap10 = default(ConfiguredCancelableAsyncEnumerable<StreamingUpdate>.Enumerator);
					<update>5__12 = null;
					<details>5__13 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<runOptions>5__2 = null;
				<toolResources>5__3 = null;
				<toolResults>5__4 = null;
				<threadId>5__5 = null;
				<threadRun>5__6 = null;
				<responseId>5__7 = null;
				<>7__wrap7 = default(ConfiguredCancelableAsyncEnumerable<ThreadRun>.Enumerator);
				<>7__wrap8 = null;
				<>7__wrap10 = default(ConfiguredCancelableAsyncEnumerable<StreamingUpdate>.Enumerator);
				<update>5__12 = null;
				<details>5__13 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_0f99:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<ChatResponseUpdate> IAsyncEnumerable<ChatResponseUpdate>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<GetStreamingResponseAsync>d__9 <GetStreamingResponseAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<GetStreamingResponseAsync>d__ = this;
				}
				else
				{
					<GetStreamingResponseAsync>d__ = new <GetStreamingResponseAsync>d__9(-3)
					{
						<>4__this = <>4__this
					};
				}
				<GetStreamingResponseAsync>d__.messages = <>3__messages;
				<GetStreamingResponseAsync>d__.options = <>3__options;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<GetStreamingResponseAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<GetStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<GetStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <GetStreamingResponseAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<GetStreamingResponseAsync>d__9 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<GetStreamingResponseAsync>d__9 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		private readonly AssistantClient _client;

		private readonly ChatClientMetadata _metadata;

		private readonly string _assistantId;

		private readonly string? _defaultThreadId;

		private IReadOnlyList<ToolDefinition>? _assistantTools;

		public OpenAIAssistantsChatClient(AssistantClient assistantClient, string assistantId, string? defaultThreadId)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Expected O, but got Unknown
			_client = Throw.IfNull<AssistantClient>(assistantClient, "assistantClient");
			_assistantId = Throw.IfNullOrWhitespace(assistantId, "assistantId");
			_defaultThreadId = defaultThreadId;
			_metadata = new ChatClientMetadata("openai", assistantClient.Endpoint, (string)null);
		}

		public OpenAIAssistantsChatClient(AssistantClient assistantClient, Assistant assistant, string? defaultThreadId)
			: this(assistantClient, Throw.IfNull<Assistant>(assistant, "assistant").Id, defaultThreadId)
		{
			_assistantTools = assistant.Tools;
		}

		public object? GetService(Type serviceType, object? serviceKey = null)
		{
			if ((object)serviceType != null)
			{
				if (serviceKey == null)
				{
					if (!(serviceType == typeof(ChatClientMetadata)))
					{
						if (!(serviceType == typeof(AssistantClient)))
						{
							if (!serviceType.IsInstanceOfType(this))
							{
								return null;
							}
							return this;
						}
						return _client;
					}
					return _metadata;
				}
				return null;
			}
			throw new ArgumentNullException("serviceType");
		}

		public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return ChatResponseExtensions.ToChatResponseAsync(GetStreamingResponseAsync(messages, options, cancellationToken), cancellationToken);
		}

		[AsyncIteratorStateMachine(typeof(<GetStreamingResponseAsync>d__9))]
		public IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			return new <GetStreamingResponseAsync>d__9(-2)
			{
				<>4__this = this,
				<>3__messages = messages,
				<>3__options = options,
				<>3__cancellationToken = cancellationToken
			};
		}

		void IDisposable.Dispose()
		{
		}

		internal static FunctionToolDefinition ToOpenAIAssistantsFunctionToolDefinition(AIFunctionDeclaration aiFunction, ChatOptions? options = null)
		{
			//IL_0030: 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_0041: 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_0056: Expected O, but got Unknown
			bool? flag = OpenAIClientExtensions.HasStrict(((AITool)aiFunction).AdditionalProperties) ?? OpenAIClientExtensions.HasStrict((IReadOnlyDictionary<string, object?>?)((options != null) ? options.AdditionalProperties : null));
			return new FunctionToolDefinition(((AITool)aiFunction).Name)
			{
				Description = ((AITool)aiFunction).Description,
				Parameters = OpenAIClientExtensions.ToOpenAIFunctionParameters(aiFunction, flag),
				StrictParameterSchemaEnabled = flag
			};
		}

		private async ValueTask<(RunCreationOptions RunOptions, ToolResources? Resources, List<FunctionResultContent>? ToolResults)> CreateRunOptionsAsync(IEnumerable<ChatMessage> messages, ChatOptions? options, CancellationToken cancellationToken)
		{
			object obj = ((options == null) ? null : options.RawRepresentationFactory?.Invoke((IChatClient)(object)this));
			RunCreationOptions runOptions = (RunCreationOptions)(((obj is RunCreationOptions) ? obj : null) ?? ((object)new RunCreationOptions()));
			ToolResources resources = null;
			if (options != null)
			{
				RunCreationOptions val = runOptions;
				if (!val.MaxOutputTokenCount.HasValue)
				{
					val.MaxOutputTokenCount = options.MaxOutputTokens;
				}
				val = runOptions;
				if (val.ModelOverride == null)
				{
					val.ModelOverride = options.ModelId;
				}
				val = runOptions;
				if (!val.NucleusSamplingFactor.HasValue)
				{
					val.NucleusSamplingFactor = options.TopP;
				}
				val = runOptions;
				if (!val.Temperature.HasValue)
				{
					val.Temperature = options.Temperature;
				}
				val = runOptions;
				if (!val.AllowParallelToolCalls.HasValue)
				{
					val.AllowParallelToolCalls = options.AllowMultipleToolCalls;
				}
				IList<AITool> tools = options.Tools;
				if (tools != null && tools.Count > 0)
				{
					HashSet<ToolDefinition> toolsOverride = new HashSet<ToolDefinition>(ToolDefinitionNameEqualityComparer.Instance);
					if (runOptions.ToolsOverride.Count == 0)
					{
						if (_assistantTools == null)
						{
							_assistantTools = (await _client.GetAssistantAsync(_assistantId, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Value.Tools;
						}
						toolsOverride.UnionWith(_assistantTools);
					}
					foreach (AITool item2 in tools)
					{
						AIFunctionDeclaration val2 = (AIFunctionDeclaration)(object)((item2 is AIFunctionDeclaration) ? item2 : null);
						if (val2 == null)
						{
							HostedCodeInterpreterTool val3 = (HostedCodeInterpreterTool)(object)((item2 is HostedCodeInterpreterTool) ? item2 : null);
							if (val3 == null)
							{
								HostedFileSearchTool val4 = (HostedFileSearchTool)(object)((item2 is HostedFileSearchTool) ? item2 : null);
								if (val4 == null)
								{
									continue;
								}
								FileSearchToolDefinition val5 = ToolDefinition.CreateFileSearch(val4.MaximumResultCount);
								val5.RankingOptions = ((AITool)(object)val4).GetProperty<FileSearchRankingOptions>("RankingOptions");
								toolsOverride.Add((ToolDefinition)(object)val5);
								IList<AIContent> inputs = val4.Inputs;
								if (inputs == null || inputs.Count <= 0)
								{
									continue;
								}
								foreach (AIContent item3 in inputs)
								{
									HostedVectorStoreContent val6 = (HostedVectorStoreContent)(object)((item3 is HostedVectorStoreContent) ? item3 : null);
									if (val6 != null)
									{
										ToolResources obj2 = resources;
										if (obj2 == null)
										{
											ToolResources val7 = new ToolResources();
											ToolResources val8 = val7;
											resources = val7;
											obj2 = val8;
										}
										ToolResources val9 = obj2;
										if (val9.FileSearch == null)
										{
											val9.FileSearch = new FileSearchToolResources();
										}
										resources.FileSearch.VectorStoreIds.Add(val6.VectorStoreId);
									}
								}
								continue;
							}
							CodeInterpreterToolDefinition item = ToolDefinition.CreateCodeInterpreter();
							toolsOverride.Add((ToolDefinition)(object)item);
							int? num = val3.Inputs?.Count;
							if (!num.HasValue || num.GetValueOrDefault() <= 0)
							{
								continue;
							}
							ThreadInitializationMessage val10 = null;
							foreach (AIContent input in val3.Inputs)
							{
								HostedFileContent val11 = (HostedFileContent)(object)((input is HostedFileContent) ? input : null);
								if (val11 != null)
								{
									if (val10 == null)
									{
										val10 = new ThreadInitializationMessage((MessageRole)0, (IEnumerable<MessageContent>)new <>z__ReadOnlySingleElementList<MessageContent>(MessageContent.FromText("attachments")));
									}
									((MessageCreationOptions)val10).Attachments.Add(new MessageCreationAttachment(val11.FileId, (IEnumerable<ToolDefinition>)new <>z__ReadOnlySingleElementList<ToolDefinition>((ToolDefinition)(object)item)));
								}
							}
							if (val10 != null)
							{
								runOptions.AdditionalMessages.Add(val10);
							}
						}
						else
						{
							toolsOverride.Add((ToolDefinition)(object)ToOpenAIAssistantsFunctionToolDefinition(val2, options));
						}
					}
					foreach (ToolDefinition item4 in toolsOverride)
					{
						runOptions.ToolsOverride.Add(item4);
					}
				}
				if (runOptions.ToolConstraint == null)
				{
					ChatToolMode toolMode = options.ToolMode;
					if (!(toolMode is NoneChatToolMode))
					{
						if (!(toolMode is AutoChatToolMode))
						{
							RequiredChatToolMode val12 = (RequiredChatToolMode)(object)((toolMode is RequiredChatToolMode) ? toolMode : null);
							if (val12 != null)
							{
								string requiredFunctionName = val12.RequiredFunctionName;
								if (requiredFunctionName != null)
								{
									runOptions.ToolConstraint = new ToolConstraint((ToolDefinition)(object)ToolDefinition.CreateFunction(requiredFunctionName, (string)null, (BinaryData)null, (bool?)null));
								}
								else
								{
									runOptions.ToolConstraint = ToolConstraint.Required;
								}
							}
						}
						else
						{
							runOptions.ToolConstraint = ToolConstraint.Auto;
						}
					}
					else
					{
						runOptions.ToolConstraint = ToolConstraint.None;
					}
				}
				if (runOptions.ResponseFormat == null)
				{
					ChatResponseFormat responseFormat = options.ResponseFormat;
					if (!(responseFormat is ChatResponseFormatText))
					{
						ChatResponseFormatJson val13 = (ChatResponseFormatJson)(object)((responseFormat is ChatResponseFormatJson) ? responseFormat : null);
						if (val13 != null)
						{
							JsonElement? orCreateTransformedSchema = OpenAIClientExtensions.StrictSchemaTransformCache.GetOrCreateTransformedSchema(val13);
							if (orCreateTransformedSchema.HasValue)
							{
								JsonElement valueOrDefault = orCreateTransformedSchema.GetValueOrDefault();
								runOptions.ResponseFormat = AssistantResponseFormat.CreateJsonSchemaFormat(val13.SchemaName, BinaryData.FromBytes(JsonSerializer.SerializeToUtf8Bytes(valueOrDefault, OpenAIJsonContext.Default.JsonElement)), val13.SchemaDescription, OpenAIClientExtensions.HasStrict((IReadOnlyDictionary<string, object?>?)options.AdditionalProperties));
							}
							else
							{
								runOptions.ResponseFormat = AssistantResponseFormat.CreateJsonObjectFormat();
							}
						}
					}
					else
					{
						runOptions.ResponseFormat = AssistantResponseFormat.CreateTextFormat();
					}
				}
			}
			StringBuilder instructions = null;
			AppendSystemInstructions(runOptions.AdditionalInstructions);
			AppendSystemInstructions((options != null) ? options.Instructions : null);
			List<FunctionResultContent> list = null;
			foreach (ChatMessage message in messages)
			{
				List<MessageContent> list2 = new List<MessageContent>();
				if (message.Role == ChatRole.System || message.Role == OpenAIClientExtensions.ChatRoleDeveloper)
				{
					foreach (TextContent item5 in message.Contents.OfType<TextContent>())
					{
						AppendSystemInstructions(item5.Text);
					}
					continue;
				}
				foreach (AIContent content in message.Contents)
				{
					AIContent val14 = content;
					if (val14 == null)
					{
						continue;
					}
					object rawRepresentation = content.RawRepresentation;
					MessageContent val15 = (MessageContent)((rawRepresentation is MessageContent) ? rawRepresentation : null);
					if (val15 == null)
					{
						TextContent val16 = (TextContent)(object)((val14 is TextContent) ? val14 : null);
						if (val16 == null)
						{
							UriContent val17 = (UriContent)(object)((val14 is UriContent) ? val14 : null);
							if (val17 == null)
							{
								FunctionResultContent val18 = (FunctionResultContent)(object)((val14 is FunctionResultContent) ? val14 : null);
								if (val18 != null && message.Role == ChatRole.Tool)
								{
									(list ?? (list = new List<FunctionResultContent>())).Add(val18);
								}
							}
							else if (val17.HasTopLevelMediaType("image"))
							{
								list2.Add(MessageContent.FromImageUri(val17.Uri, (MessageImageDetail?)null));
							}
						}
						else
						{
							list2.Add(MessageContent.FromText(val16.Text));
						}
					}
					else
					{
						list2.Add(val15);
					}
				}
				if (list2.Count > 0)
				{
					runOptions.AdditionalMessages.Add(new ThreadInitializationMessage((MessageRole)((message.Role == ChatRole.Assistant) ? 1 : 0), (IEnumerable<MessageContent>)list2));
				}
			}
			runOptions.AdditionalInstructions = instructions?.ToString();
			return (runOptions, resources, list);
			void AppendSystemInstructions(string? toAppend)
			{
				if (!string.IsNullOrEmpty(toAppend))
				{
					if (instructions == null)
					{
						instructions = new StringBuilder(toAppend);
					}
					else
					{
						instructions.AppendLine().AppendLine(toAppend);
					}
				}
			}
		}

		private static string? ConvertFunctionResultsToToolOutput(List<FunctionResultContent>? toolResults, out List<ToolOutput>? toolOutputs)
		{
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00af: Expected O, but got Unknown
			string text = null;
			toolOutputs = null;
			if (toolResults != null && toolResults.Count > 0)
			{
				foreach (FunctionResultContent toolResult in toolResults)
				{
					string[] array;
					try
					{
						array = JsonSerializer.Deserialize(toolResult.CallId, OpenAIJsonContext.Default.StringArray);
					}
					catch
					{
						continue;
					}
					if (array != null && array.Length == 2 && !string.IsNullOrWhiteSpace(array[0]) && !string.IsNullOrWhiteSpace(array[1]) && (text == null || !(text != array[0])))
					{
						text = array[0];
						(toolOutputs ?? (toolOutputs = new List<ToolOutput>())).Add(new ToolOutput(array[1], toolResult.Result?.ToString() ?? string.Empty));
					}
				}
			}
			return text;
		}
	}
	internal sealed class OpenAIChatClient : IChatClient, IDisposable
	{
		private sealed class FunctionCallInfo
		{
			public string? CallId;

			public string? Name;

			public StringBuilder? Arguments;
		}

		[CompilerGenerated]
		private sealed class <FromOpenAIStreamingChatCompletionAsync>d__14 : IAsyncEnumerable<ChatResponseUpdate>, IAsyncEnumerator<ChatResponseUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private ChatResponseUpdate <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private IAsyncEnumerable<StreamingChatCompletionUpdate> updates;

			public IAsyncEnumerable<StreamingChatCompletionUpdate> <>3__updates;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private ChatCompletionOptions options;

			public ChatCompletionOptions <>3__options;

			private Dictionary<int, FunctionCallInfo> <functionCallInfos>5__2;

			private ChatRole? <streamedRole>5__3;

			private ChatFinishReason? <finishReason>5__4;

			private StringBuilder <refusal>5__5;

			private string <responseId>5__6;

			private DateTimeOffset? <createdAt>5__7;

			private string <modelId>5__8;

			private ConfiguredCancelableAsyncEnumerable<StreamingChatCompletionUpdate>.Enumerator <>7__wrap8;

			private object <>7__wrap9;

			private int <>7__wrap10;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2;

			ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <FromOpenAIStreamingChatCompletionAsync>d__14(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				//IL_0581: Unknown result type (might be due to invalid IL or missing references)
				//IL_0586: Unknown result type (might be due to invalid IL or missing references)
				//IL_0592: Unknown result type (might be due to invalid IL or missing references)
				//IL_059e: Unknown result type (might be due to invalid IL or missing references)
				//IL_05aa: Unknown result type (might be due to invalid IL or missing references)
				//IL_05b6: Unknown result type (might be due to invalid IL or missing references)
				//IL_05c2: Unknown result type (might be due to invalid IL or missing references)
				//IL_05d0: Expected O, but got Unknown
				//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0102: Unknown result type (might be due to invalid IL or missing references)
				//IL_0146: 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_0111: Unknown result type (might be due to invalid IL or missing references)
				//IL_0112: Unknown result type (might be due to invalid IL or missing references)
				//IL_015b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0682: Unknown result type (might be due to invalid IL or missing references)
				//IL_0687: Unknown result type (might be due to invalid IL or missing references)
				//IL_0697: Expected O, but got Unknown
				//IL_01c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_01c8: Unknown result type (might be due to invalid IL or missing references)
				//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
				//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f1: Unknown result type (might be due to invalid IL or missing references)
				//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
				//IL_0209: Unknown result type (might be due to invalid IL or missing references)
				//IL_0210: Unknown result type (might be due to invalid IL or missing references)
				//IL_021e: Expected O, but got Unknown
				//IL_0270: Unknown result type (might be due to invalid IL or missing references)
				//IL_0275: Unknown result type (might be due to invalid IL or missing references)
				//IL_0282: Expected O, but got Unknown
				//IL_03ed: Unknown result type (might be due to invalid IL or missing references)
				//IL_03f2: Unknown result type (might be due to invalid IL or missing references)
				//IL_03ff: Expected O, but got Unknown
				int num = <>1__state;
				try
				{
					ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter;
					object obj;
					ChatResponseUpdate val;
					Dictionary<int, FunctionCallInfo>.Enumerator enumerator;
					switch (num)
					{
					default:
						if (<>w__disposeMode)
						{
							break;
						}
						num = (<>1__state = -1);
						<functionCallInfos>5__2 = null;
						<streamedRole>5__3 = null;
						<finishReason>5__4 = null;
						<refusal>5__5 = null;
						<responseId>5__6 = null;
						<createdAt>5__7 = null;
						<modelId>5__8 = null;
						<>7__wrap8 = updates.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
						<>7__wrap9 = null;
						<>7__wrap10 = 0;
						goto case -4;
					case -4:
					case 0:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -4)
							{
								if (num != 0)
								{
									goto IL_042c;
								}
								awaiter2 = <>u__1;
								<>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
								num = (<>1__state = -1);
								goto IL_0497;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_042c;
							}
							goto end_IL_00b9;
							IL_042c:
							<>2__current = null;
							awaiter2 = <>7__wrap8.MoveNextAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter2;
								<FromOpenAIStreamingChatCompletionAsync>d__14 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_0497;
							IL_0497:
							StreamingChatCompletionUpdate current;
							ChatResponseUpdate val4;
							if (awaiter2.GetResult())
							{
								current = <>7__wrap8.Current;
								ChatRole? val2 = <streamedRole>5__3;
								if (!val2.HasValue)
								{
									ChatMessageRole? role = current.Role;
									ChatRole? obj2;
									if (role.HasValue)
									{
										ChatMessageRole valueOrDefault = role.GetValueOrDefault();
										obj2 = FromOpenAIChatRole(valueOrDefault);
									}
									else
									{
										obj2 = null;
									}
									<streamedRole>5__3 = obj2;
								}
								ChatFinishReason? val3 = <finishReason>5__4;
								if (!val3.HasValue)
								{
									ChatFinishReason? finishReason = current.FinishReason;
									ChatFinishReason? obj3;
									if (finishReason.HasValue)
									{
										ChatFinishReason valueOrDefault2 = finishReason.GetValueOrDefault();
										obj3 = FromOpenAIFinishReason(valueOrDefault2);
									}
									else
									{
										obj3 = null;
									}
									<finishReason>5__4 = obj3;
								}
								if (<responseId>5__6 == null)
								{
									<responseId>5__6 = current.CompletionId;
								}
								DateTimeOffset valueOrDefault3 = <createdAt>5__7.GetValueOrDefault();
								if (!<createdAt>5__7.HasValue)
								{
									valueOrDefault3 = current.CreatedAt;
									<createdAt>5__7 = valueOrDefault3;
								}
								if (<modelId>5__8 == null)
								{
									<modelId>5__8 = current.Model;
								}
								val4 = new ChatResponseUpdate
								{
									ResponseId = current.CompletionId,
									MessageId = current.CompletionId,
									CreatedAt = current.CreatedAt,
									FinishReason = <finishReason>5__4,
									ModelId = <modelId>5__8,
									RawRepresentation = current,
									Role = <streamedRole>5__3
								};
								ChatMessageContent contentUpdate = current.ContentUpdate;
								if (contentUpdate != null && ((Collection<ChatMessageContentPart>)(object)contentUpdate).Count > 0)
								{
									ConvertContentParts(current.ContentUpdate, val4.Contents);
								}
								StreamingChatOutputAudioUpdate outputAudioUpdate = current.OutputAudioUpdate;
								if (outputAudioUpdate != null)
								{
									val4.Contents.Add((AIContent)new DataContent(outputAudioUpdate.AudioBytesUpdate.ToMemory(), GetOutputAudioMimeType(options))
									{
										RawRepresentation = outputAudioUpdate
									});
								}
								if (current.RefusalUpdate != null)
								{
									(<refusal>5__5 ?? (<refusal>5__5 = new StringBuilder())).Append(current.RefusalUpdate);
								}
								IReadOnlyList<StreamingChatToolCallUpdate> toolCallUpdates = current.ToolCallUpdates;
								if (toolCallUpdates == null || toolCallUpdates.Count <= 0)
								{
									goto IL_03d3;
								}
								IEnumerator<StreamingChatToolCallUpdate> enumerator2 = toolCallUpdates.GetEnumerator();
								try
								{
									while (enumerator2.MoveNext())
									{
										StreamingChatToolCallUpdate current2 = enumerator2.Current;
										if (<functionCallInfos>5__2 == null)
										{
											<functionCallInfos>5__2 = new Dictionary<int, FunctionCallInfo>();
										}
										if (!<functionCallInfos>5__2.TryGetValue(current2.Index, out FunctionCallInfo value2))
										{
											value2 = (<functionCallInfos>5__2[current2.Index] = new FunctionCallInfo());
										}
										FunctionCallInfo functionCallInfo2 = value2;
										if (functionCallInfo2.CallId == null)
										{
											functionCallInfo2.CallId = current2.ToolCallId;
										}
										functionCallInfo2 = value2;
										if (functionCallInfo2.Name == null)
										{
											functionCallInfo2.Name = current2.FunctionName;
										}
										BinaryData functionArgumentsUpdate = current2.FunctionArgumentsUpdate;
										if (functionArgumentsUpdate != null && !functionArgumentsUpdate.ToMemory().IsEmpty)
										{
											functionCallInfo2 = value2;
											(functionCallInfo2.Arguments ?? (functionCallInfo2.Arguments = new StringBuilder())).Append(((object)functionArgumentsUpdate).ToString());
										}
									}
								}
								finally
								{
									if (num == -1)
									{
										enumerator2?.Dispose();
									}
								}
								if (

BepInEx/core/Microsoft.Extensions.Caching.Abstractions.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Primitives;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Caching.Abstractions")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Caching abstractions for in-memory cache and distributed cache.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Caching.Distributed.IDistributedCache\r\nMicrosoft.Extensions.Caching.Memory.IMemoryCache")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Caching.Abstractions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: AssemblyVersion("10.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = 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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace System
{
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Runtime.CompilerServices
{
	[EditorBrowsable(EditorBrowsableState.Never)]
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	public interface ISystemClock
	{
		DateTimeOffset UtcNow { get; }
	}
	public class SystemClock : ISystemClock
	{
		public DateTimeOffset UtcNow => DateTimeOffset.UtcNow;
	}
}
namespace Microsoft.Extensions.Caching.Hybrid
{
	public abstract class HybridCache
	{
		private static class WrappedCallbackCache<T>
		{
			public static readonly Func<Func<CancellationToken, ValueTask<T>>, CancellationToken, ValueTask<T>> Instance = (Func<CancellationToken, ValueTask<T>> callback, CancellationToken ct) => callback(ct);
		}

		public abstract ValueTask<T> GetOrCreateAsync<TState, T>(string key, TState state, Func<TState, CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default(CancellationToken));

		public ValueTask<T> GetOrCreateAsync<T>(string key, Func<CancellationToken, ValueTask<T>> factory, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return GetOrCreateAsync<Func<CancellationToken, ValueTask<T>>, T>(key, factory, WrappedCallbackCache<T>.Instance, options, tags, cancellationToken);
		}

		public abstract ValueTask SetAsync<T>(string key, T value, HybridCacheEntryOptions? options = null, IEnumerable<string>? tags = null, CancellationToken cancellationToken = default(CancellationToken));

		public abstract ValueTask RemoveAsync(string key, CancellationToken cancellationToken = default(CancellationToken));

		public virtual ValueTask RemoveAsync(IEnumerable<string> keys, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (keys != null)
			{
				if (keys is ICollection<string> collection)
				{
					int count = collection.Count;
					if (count == 0)
					{
						goto IL_001d;
					}
					if (count == 1)
					{
						return RemoveAsync(keys.First(), cancellationToken);
					}
				}
				return ForEachAsync(this, keys, cancellationToken);
			}
			goto IL_001d;
			IL_001d:
			return default(ValueTask);
			static async ValueTask ForEachAsync(HybridCache @this, IEnumerable<string> keys, CancellationToken cancellationToken)
			{
				foreach (string key in keys)
				{
					await @this.RemoveAsync(key, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				}
			}
		}

		public virtual ValueTask RemoveByTagAsync(IEnumerable<string> tags, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (tags != null)
			{
				if (tags is ICollection<string> collection)
				{
					int count = collection.Count;
					if (count == 0)
					{
						goto IL_001d;
					}
					if (count == 1)
					{
						return RemoveByTagAsync(tags.Single(), cancellationToken);
					}
				}
				return ForEachAsync(this, tags, cancellationToken);
			}
			goto IL_001d;
			IL_001d:
			return default(ValueTask);
			static async ValueTask ForEachAsync(HybridCache @this, IEnumerable<string> keys, CancellationToken cancellationToken)
			{
				foreach (string key in keys)
				{
					await @this.RemoveByTagAsync(key, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				}
			}
		}

		public abstract ValueTask RemoveByTagAsync(string tag, CancellationToken cancellationToken = default(CancellationToken));
	}
	[Flags]
	public enum HybridCacheEntryFlags
	{
		None = 0,
		DisableLocalCacheRead = 1,
		DisableLocalCacheWrite = 2,
		DisableLocalCache = 3,
		DisableDistributedCacheRead = 4,
		DisableDistributedCacheWrite = 8,
		DisableDistributedCache = 0xC,
		DisableUnderlyingData = 0x10,
		DisableCompression = 0x20
	}
	public sealed class HybridCacheEntryOptions
	{
		private DistributedCacheEntryOptions _dc;

		public TimeSpan? Expiration { get; init; }

		public TimeSpan? LocalCacheExpiration { get; init; }

		public HybridCacheEntryFlags? Flags { get; init; }

		internal DistributedCacheEntryOptions ToDistributedCacheEntryOptions()
		{
			object obj;
			if (Expiration.HasValue)
			{
				obj = _dc;
				if (obj == null)
				{
					DistributedCacheEntryOptions obj2 = new DistributedCacheEntryOptions
					{
						AbsoluteExpirationRelativeToNow = Expiration
					};
					DistributedCacheEntryOptions result = obj2;
					_dc = obj2;
					return result;
				}
			}
			else
			{
				obj = null;
			}
			return (DistributedCacheEntryOptions)obj;
		}
	}
	public interface IHybridCacheSerializer<T>
	{
		T Deserialize(ReadOnlySequence<byte> source);

		void Serialize(T value, IBufferWriter<byte> target);
	}
	public interface IHybridCacheSerializerFactory
	{
		bool TryCreateSerializer<T>([NotNullWhen(true)] out IHybridCacheSerializer<T>? serializer);
	}
}
namespace Microsoft.Extensions.Caching.Distributed
{
	public static class DistributedCacheEntryExtensions
	{
		public static DistributedCacheEntryOptions SetAbsoluteExpiration(this DistributedCacheEntryOptions options, TimeSpan relative)
		{
			options.AbsoluteExpirationRelativeToNow = relative;
			return options;
		}

		public static DistributedCacheEntryOptions SetAbsoluteExpiration(this DistributedCacheEntryOptions options, DateTimeOffset absolute)
		{
			options.AbsoluteExpiration = absolute;
			return options;
		}

		public static DistributedCacheEntryOptions SetSlidingExpiration(this DistributedCacheEntryOptions options, TimeSpan offset)
		{
			options.SlidingExpiration = offset;
			return options;
		}
	}
	public class DistributedCacheEntryOptions
	{
		private DateTimeOffset _absoluteExpiration;

		private bool _absoluteExpirationSet;

		private TimeSpan _absoluteExpirationRelativeToNow;

		private bool _absoluteExpirationRelativeToNowSet;

		private TimeSpan _slidingExpiration;

		private bool _slidingExpirationSet;

		private bool _frozen;

		public DateTimeOffset? AbsoluteExpiration
		{
			get
			{
				if (!_absoluteExpirationSet)
				{
					return null;
				}
				return _absoluteExpiration;
			}
			set
			{
				Set(ref _absoluteExpiration, ref _absoluteExpirationSet, in value);
			}
		}

		public TimeSpan? AbsoluteExpirationRelativeToNow
		{
			get
			{
				if (!_absoluteExpirationRelativeToNowSet)
				{
					return null;
				}
				return _absoluteExpirationRelativeToNow;
			}
			set
			{
				if (value <= TimeSpan.Zero)
				{
					throw new ArgumentOutOfRangeException("AbsoluteExpirationRelativeToNow", value, "The relative expiration value must be positive.");
				}
				Set(ref _absoluteExpirationRelativeToNow, ref _absoluteExpirationRelativeToNowSet, in value);
			}
		}

		public TimeSpan? SlidingExpiration
		{
			get
			{
				if (!_slidingExpirationSet)
				{
					return null;
				}
				return _slidingExpiration;
			}
			set
			{
				if (value <= TimeSpan.Zero)
				{
					throw new ArgumentOutOfRangeException("SlidingExpiration", value, "The sliding expiration value must be positive.");
				}
				Set(ref _slidingExpiration, ref _slidingExpirationSet, in value);
			}
		}

		internal DistributedCacheEntryOptions Freeze()
		{
			_frozen = true;
			return this;
		}

		private void Set<T>(ref T field, ref bool isSet, in T? value) where T : struct
		{
			if (_frozen)
			{
				ThrowFrozen();
			}
			field = value.GetValueOrDefault();
			isSet = value.HasValue;
			static void ThrowFrozen()
			{
				throw new InvalidOperationException("This instance has been frozen and cannot be mutated");
			}
		}
	}
	public static class DistributedCacheExtensions
	{
		private static readonly DistributedCacheEntryOptions DefaultOptions = new DistributedCacheEntryOptions().Freeze();

		public static void Set(this IDistributedCache cache, string key, byte[] value)
		{
			ExceptionPolyfills.ThrowIfNull(key, "key");
			ExceptionPolyfills.ThrowIfNull(value, "value");
			cache.Set(key, value, DefaultOptions);
		}

		public static Task SetAsync(this IDistributedCache cache, string key, byte[] value, CancellationToken token = default(CancellationToken))
		{
			ExceptionPolyfills.ThrowIfNull(key, "key");
			ExceptionPolyfills.ThrowIfNull(value, "value");
			return cache.SetAsync(key, value, DefaultOptions, token);
		}

		public static void SetString(this IDistributedCache cache, string key, string value)
		{
			cache.SetString(key, value, DefaultOptions);
		}

		public static void SetString(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options)
		{
			ExceptionPolyfills.ThrowIfNull(key, "key");
			ExceptionPolyfills.ThrowIfNull(value, "value");
			cache.Set(key, Encoding.UTF8.GetBytes(value), options);
		}

		public static Task SetStringAsync(this IDistributedCache cache, string key, string value, CancellationToken token = default(CancellationToken))
		{
			return cache.SetStringAsync(key, value, DefaultOptions, token);
		}

		public static Task SetStringAsync(this IDistributedCache cache, string key, string value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
		{
			ExceptionPolyfills.ThrowIfNull(key, "key");
			ExceptionPolyfills.ThrowIfNull(value, "value");
			return cache.SetAsync(key, Encoding.UTF8.GetBytes(value), options, token);
		}

		public static string? GetString(this IDistributedCache cache, string key)
		{
			byte[] array = cache.Get(key);
			if (array == null)
			{
				return null;
			}
			return Encoding.UTF8.GetString(array, 0, array.Length);
		}

		public static async Task<string?> GetStringAsync(this IDistributedCache cache, string key, CancellationToken token = default(CancellationToken))
		{
			byte[] array = await cache.GetAsync(key, token).ConfigureAwait(continueOnCapturedContext: false);
			if (array == null)
			{
				return null;
			}
			return Encoding.UTF8.GetString(array, 0, array.Length);
		}
	}
	public interface IBufferDistributedCache : IDistributedCache
	{
		bool TryGet(string key, IBufferWriter<byte> destination);

		ValueTask<bool> TryGetAsync(string key, IBufferWriter<byte> destination, CancellationToken token = default(CancellationToken));

		void Set(string key, ReadOnlySequence<byte> value, DistributedCacheEntryOptions options);

		ValueTask SetAsync(string key, ReadOnlySequence<byte> value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken));
	}
	public interface IDistributedCache
	{
		byte[]? Get(string key);

		Task<byte[]?> GetAsync(string key, CancellationToken token = default(CancellationToken));

		void Set(string key, byte[] value, DistributedCacheEntryOptions options);

		Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken));

		void Refresh(string key);

		Task RefreshAsync(string key, CancellationToken token = default(CancellationToken));

		void Remove(string key);

		Task RemoveAsync(string key, CancellationToken token = default(CancellationToken));
	}
}
namespace Microsoft.Extensions.Caching.Memory
{
	public static class CacheEntryExtensions
	{
		public static ICacheEntry SetPriority(this ICacheEntry entry, CacheItemPriority priority)
		{
			entry.Priority = priority;
			return entry;
		}

		public static ICacheEntry AddExpirationToken(this ICacheEntry entry, IChangeToken expirationToken)
		{
			ExceptionPolyfills.ThrowIfNull(expirationToken, "expirationToken");
			entry.ExpirationTokens.Add(expirationToken);
			return entry;
		}

		public static ICacheEntry SetAbsoluteExpiration(this ICacheEntry entry, TimeSpan relative)
		{
			entry.AbsoluteExpirationRelativeToNow = relative;
			return entry;
		}

		public static ICacheEntry SetAbsoluteExpiration(this ICacheEntry entry, DateTimeOffset absolute)
		{
			entry.AbsoluteExpiration = absolute;
			return entry;
		}

		public static ICacheEntry SetSlidingExpiration(this ICacheEntry entry, TimeSpan offset)
		{
			entry.SlidingExpiration = offset;
			return entry;
		}

		public static ICacheEntry RegisterPostEvictionCallback(this ICacheEntry entry, PostEvictionDelegate callback)
		{
			return entry.RegisterPostEvictionCallback(callback, null);
		}

		public static ICacheEntry RegisterPostEvictionCallback(this ICacheEntry entry, PostEvictionDelegate callback, object? state)
		{
			ExceptionPolyfills.ThrowIfNull(callback, "callback");
			entry.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration
			{
				EvictionCallback = callback,
				State = state
			});
			return entry;
		}

		public static ICacheEntry SetValue(this ICacheEntry entry, object? value)
		{
			entry.Value = value;
			return entry;
		}

		public static ICacheEntry SetSize(this ICacheEntry entry, long size)
		{
			if (size < 0)
			{
				throw new ArgumentOutOfRangeException("size", size, "size must be non-negative.");
			}
			entry.Size = size;
			return entry;
		}

		public static ICacheEntry SetOptions(this ICacheEntry entry, MemoryCacheEntryOptions options)
		{
			ExceptionPolyfills.ThrowIfNull(options, "options");
			entry.AbsoluteExpiration = options.AbsoluteExpiration;
			entry.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow;
			entry.SlidingExpiration = options.SlidingExpiration;
			entry.Priority = options.Priority;
			entry.Size = options.Size;
			List<IChangeToken> expirationTokensDirect = options.ExpirationTokensDirect;
			if (expirationTokensDirect != null)
			{
				foreach (IChangeToken item in expirationTokensDirect)
				{
					entry.AddExpirationToken(item);
				}
			}
			List<PostEvictionCallbackRegistration> postEvictionCallbacksDirect = options.PostEvictionCallbacksDirect;
			if (postEvictionCallbacksDirect != null)
			{
				for (int i = 0; i < postEvictionCallbacksDirect.Count; i++)
				{
					PostEvictionCallbackRegistration postEvictionCallbackRegistration = postEvictionCallbacksDirect[i];
					if (postEvictionCallbackRegistration.EvictionCallback == null)
					{
						ThrowNullCallback(i, "options");
					}
					entry.PostEvictionCallbacks.Add(postEvictionCallbackRegistration);
				}
			}
			return entry;
		}

		[DoesNotReturn]
		private static void ThrowNullCallback(int index, string paramName)
		{
			throw new ArgumentException($"MemoryCacheEntryOptions.PostEvictionCallbacks contains a PostEvictionCallbackRegistration with a null EvictionCallback at index {index}.", paramName);
		}
	}
	public enum CacheItemPriority
	{
		Low,
		Normal,
		High,
		NeverRemove
	}
	public enum EvictionReason
	{
		None,
		Removed,
		Replaced,
		Expired,
		TokenExpired,
		Capacity
	}
	public interface ICacheEntry : IDisposable
	{
		object Key { get; }

		object? Value { get; set; }

		DateTimeOffset? AbsoluteExpiration { get; set; }

		TimeSpan? AbsoluteExpirationRelativeToNow { get; set; }

		TimeSpan? SlidingExpiration { get; set; }

		IList<IChangeToken> ExpirationTokens { get; }

		IList<PostEvictionCallbackRegistration> PostEvictionCallbacks { get; }

		CacheItemPriority Priority { get; set; }

		long? Size { get; set; }
	}
	public interface IMemoryCache : IDisposable
	{
		bool TryGetValue(object key, out object? value);

		ICacheEntry CreateEntry(object key);

		void Remove(object key);
	}
	public static class MemoryCacheEntryExtensions
	{
		public static MemoryCacheEntryOptions SetPriority(this MemoryCacheEntryOptions options, CacheItemPriority priority)
		{
			options.Priority = priority;
			return options;
		}

		public static MemoryCacheEntryOptions SetSize(this MemoryCacheEntryOptions options, long size)
		{
			if (size < 0)
			{
				throw new ArgumentOutOfRangeException("size", size, "size must be non-negative.");
			}
			options.Size = size;
			return options;
		}

		public static MemoryCacheEntryOptions AddExpirationToken(this MemoryCacheEntryOptions options, IChangeToken expirationToken)
		{
			ExceptionPolyfills.ThrowIfNull(expirationToken, "expirationToken");
			options.ExpirationTokens.Add(expirationToken);
			return options;
		}

		public static MemoryCacheEntryOptions SetAbsoluteExpiration(this MemoryCacheEntryOptions options, TimeSpan relative)
		{
			options.AbsoluteExpirationRelativeToNow = relative;
			return options;
		}

		public static MemoryCacheEntryOptions SetAbsoluteExpiration(this MemoryCacheEntryOptions options, DateTimeOffset absolute)
		{
			options.AbsoluteExpiration = absolute;
			return options;
		}

		public static MemoryCacheEntryOptions SetSlidingExpiration(this MemoryCacheEntryOptions options, TimeSpan offset)
		{
			options.SlidingExpiration = offset;
			return options;
		}

		public static MemoryCacheEntryOptions RegisterPostEvictionCallback(this MemoryCacheEntryOptions options, PostEvictionDelegate callback)
		{
			ExceptionPolyfills.ThrowIfNull(callback, "callback");
			return options.RegisterPostEvictionCallback(callback, null);
		}

		public static MemoryCacheEntryOptions RegisterPostEvictionCallback(this MemoryCacheEntryOptions options, PostEvictionDelegate callback, object? state)
		{
			ExceptionPolyfills.ThrowIfNull(callback, "callback");
			options.PostEvictionCallbacks.Add(new PostEvictionCallbackRegistration
			{
				EvictionCallback = callback,
				State = state
			});
			return options;
		}
	}
	public class MemoryCacheEntryOptions
	{
		private DateTimeOffset? _absoluteExpiration;

		private TimeSpan? _absoluteExpirationRelativeToNow;

		private TimeSpan? _slidingExpiration;

		private long? _size;

		private List<IChangeToken> _expirationTokens;

		private List<PostEvictionCallbackRegistration> _postEvictionCallbacks;

		public DateTimeOffset? AbsoluteExpiration
		{
			get
			{
				return _absoluteExpiration;
			}
			set
			{
				_absoluteExpiration = value;
			}
		}

		public TimeSpan? AbsoluteExpirationRelativeToNow
		{
			get
			{
				return _absoluteExpirationRelativeToNow;
			}
			set
			{
				if (value <= TimeSpan.Zero)
				{
					throw new ArgumentOutOfRangeException("AbsoluteExpirationRelativeToNow", value, "The relative expiration value must be positive.");
				}
				_absoluteExpirationRelativeToNow = value;
			}
		}

		public TimeSpan? SlidingExpiration
		{
			get
			{
				return _slidingExpiration;
			}
			set
			{
				if (value <= TimeSpan.Zero)
				{
					throw new ArgumentOutOfRangeException("SlidingExpiration", value, "The sliding expiration value must be positive.");
				}
				_slidingExpiration = value;
			}
		}

		public IList<IChangeToken> ExpirationTokens => _expirationTokens ?? (_expirationTokens = new List<IChangeToken>());

		internal List<IChangeToken>? ExpirationTokensDirect => _expirationTokens;

		public IList<PostEvictionCallbackRegistration> PostEvictionCallbacks => _postEvictionCallbacks ?? (_postEvictionCallbacks = new List<PostEvictionCallbackRegistration>());

		internal List<PostEvictionCallbackRegistration>? PostEvictionCallbacksDirect => _postEvictionCallbacks;

		public CacheItemPriority Priority { get; set; } = CacheItemPriority.Normal;


		public long? Size
		{
			get
			{
				return _size;
			}
			set
			{
				if (value < 0)
				{
					throw new ArgumentOutOfRangeException("value", value, "value must be non-negative.");
				}
				_size = value;
			}
		}
	}
	public static class CacheExtensions
	{
		public static object? Get(this IMemoryCache cache, object key)
		{
			cache.TryGetValue(key, out object value);
			return value;
		}

		public static TItem? Get<TItem>(this IMemoryCache cache, object key)
		{
			cache.TryGetValue(key, out object value);
			if (value != null)
			{
				return (TItem)value;
			}
			return default(TItem);
		}

		public static bool TryGetValue<TItem>(this IMemoryCache cache, object key, out TItem? value)
		{
			if (cache.TryGetValue(key, out object value2))
			{
				if (value2 == null)
				{
					value = default(TItem);
					return true;
				}
				if (value2 is TItem val)
				{
					value = val;
					return true;
				}
			}
			value = default(TItem);
			return false;
		}

		public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value)
		{
			ICacheEntry cacheEntry = cache.CreateEntry(key);
			cacheEntry.Value = value;
			cacheEntry.Dispose();
			return value;
		}

		public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, DateTimeOffset absoluteExpiration)
		{
			using ICacheEntry cacheEntry = cache.CreateEntry(key);
			cacheEntry.AbsoluteExpiration = absoluteExpiration;
			cacheEntry.Value = value;
			return value;
		}

		public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, TimeSpan absoluteExpirationRelativeToNow)
		{
			using ICacheEntry cacheEntry = cache.CreateEntry(key);
			cacheEntry.AbsoluteExpirationRelativeToNow = absoluteExpirationRelativeToNow;
			cacheEntry.Value = value;
			return value;
		}

		public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, IChangeToken expirationToken)
		{
			using ICacheEntry cacheEntry = cache.CreateEntry(key);
			cacheEntry.AddExpirationToken(expirationToken);
			cacheEntry.Value = value;
			return value;
		}

		public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions? options)
		{
			using ICacheEntry cacheEntry = cache.CreateEntry(key);
			if (options != null)
			{
				cacheEntry.SetOptions(options);
			}
			cacheEntry.Value = value;
			return value;
		}

		public static TItem? GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory)
		{
			return cache.GetOrCreate(key, factory, null);
		}

		public static TItem? GetOrCreate<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, TItem> factory, MemoryCacheEntryOptions? createOptions)
		{
			if (!cache.TryGetValue(key, out object value))
			{
				using ICacheEntry cacheEntry = cache.CreateEntry(key);
				if (createOptions != null)
				{
					cacheEntry.SetOptions(createOptions);
				}
				value = (cacheEntry.Value = factory(cacheEntry));
			}
			return (TItem)value;
		}

		public static Task<TItem?> GetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory)
		{
			return cache.GetOrCreateAsync(key, factory, null);
		}

		public static async Task<TItem?> GetOrCreateAsync<TItem>(this IMemoryCache cache, object key, Func<ICacheEntry, Task<TItem>> factory, MemoryCacheEntryOptions? createOptions)
		{
			if (!cache.TryGetValue(key, out object value))
			{
				using ICacheEntry entry = cache.CreateEntry(key);
				if (createOptions != null)
				{
					entry.SetOptions(createOptions);
				}
				value = (entry.Value = await factory(entry).ConfigureAwait(continueOnCapturedContext: false));
			}
			return (TItem)value;
		}
	}
	public class MemoryCacheStatistics
	{
		public long CurrentEntryCount { get; init; }

		public long? CurrentEstimatedSize { get; init; }

		public long TotalMisses { get; init; }

		public long TotalHits { get; init; }
	}
	public class PostEvictionCallbackRegistration
	{
		public PostEvictionDelegate? EvictionCallback { get; set; }

		public object? State { get; set; }
	}
	public delegate void PostEvictionDelegate(object key, object? value, EvictionReason reason, object? state);
}

BepInEx/core/Microsoft.Extensions.DependencyInjection.Abstractions.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading.Tasks;
using FxResources.Microsoft.Extensions.DependencyInjection.Abstractions;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.DependencyInjection.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection.Abstractions")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Abstractions for dependency injection.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.DependencyInjection.IServiceCollection")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection.Abstractions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: AssemblyVersion("10.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(true)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.Microsoft.Extensions.DependencyInjection.Abstractions
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string AmbiguousConstructorMatch => GetResourceString("AmbiguousConstructorMatch");

		internal static string CannotResolveService => GetResourceString("CannotResolveService");

		internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch");

		internal static string NoServiceRegistered => GetResourceString("NoServiceRegistered");

		internal static string ServiceCollectionReadOnly => GetResourceString("ServiceCollectionReadOnly");

		internal static string TryAddIndistinguishableTypeToEnumerable => GetResourceString("TryAddIndistinguishableTypeToEnumerable");

		internal static string MultipleCtorsMarkedWithAttribute => GetResourceString("MultipleCtorsMarkedWithAttribute");

		internal static string MarkedCtorMissingArgumentTypes => GetResourceString("MarkedCtorMissingArgumentTypes");

		internal static string CannotCreateAbstractClasses => GetResourceString("CannotCreateAbstractClasses");

		internal static string MultipleCtorsFoundWithBestLength => GetResourceString("MultipleCtorsFoundWithBestLength");

		internal static string UnableToResolveService => GetResourceString("UnableToResolveService");

		internal static string CtorNotLocated => GetResourceString("CtorNotLocated");

		internal static string MultipleCtorsFound => GetResourceString("MultipleCtorsFound");

		internal static string KeyedServicesNotSupported => GetResourceString("KeyedServicesNotSupported");

		internal static string NonKeyedDescriptorMisuse => GetResourceString("NonKeyedDescriptorMisuse");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string? EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type? StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false)]
	internal sealed class CompilerLoweringPreserveAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[CompilerLoweringPreserve]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000,
		NonPublicConstructorsWithInherited = 0x4004,
		NonPublicMethodsWithInherited = 0x8010,
		NonPublicFieldsWithInherited = 0x10040,
		NonPublicNestedTypesWithInherited = 0x20100,
		NonPublicPropertiesWithInherited = 0x40400,
		NonPublicEventsWithInherited = 0x81000,
		PublicConstructorsWithInherited = 0x100003,
		PublicNestedTypesWithInherited = 0x200080,
		AllConstructors = 0x104007,
		AllMethods = 0x8018,
		AllFields = 0x10060,
		AllNestedTypes = 0x220180,
		AllProperties = 0x40600,
		AllEvents = 0x81800,
		[EditorBrowsable(EditorBrowsableState.Never)]
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public bool ExcludeStatics { get; set; }

		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	internal static class ParameterDefaultValue
	{
		public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue)
		{
			bool tryToGetDefaultValue;
			bool num = CheckHasDefaultValue(parameter, out tryToGetDefaultValue);
			defaultValue = null;
			if (num)
			{
				if (tryToGetDefaultValue)
				{
					defaultValue = parameter.DefaultValue;
				}
				bool flag = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>);
				if (defaultValue == null && parameter.ParameterType.IsValueType && !flag)
				{
					defaultValue = CreateValueType(parameter.ParameterType);
				}
				if (defaultValue != null && flag)
				{
					Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType);
					if (underlyingType != null && underlyingType.IsEnum)
					{
						defaultValue = Enum.ToObject(underlyingType, defaultValue);
					}
				}
			}
			return num;
			[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2067:UnrecognizedReflectionPattern", Justification = "CreateValueType is only called on a ValueType. You can always create an instance of a ValueType.")]
			static object? CreateValueType(Type t)
			{
				return RuntimeHelpers.GetUninitializedObject(t);
			}
		}

		public static bool CheckHasDefaultValue(ParameterInfo parameter, out bool tryToGetDefaultValue)
		{
			tryToGetDefaultValue = true;
			try
			{
				return parameter.HasDefaultValue;
			}
			catch (FormatException) when (parameter.ParameterType == typeof(DateTime))
			{
				tryToGetDefaultValue = false;
				return true;
			}
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection
{
	public static class ActivatorUtilities
	{
		private readonly struct FactoryParameterContext
		{
			public Type ParameterType { get; }

			public bool HasDefaultValue { get; }

			public object DefaultValue { get; }

			public int ArgumentIndex { get; }

			public object ServiceKey { get; }

			public FactoryParameterContext(Type parameterType, bool hasDefaultValue, object defaultValue, int argumentIndex, object serviceKey)
			{
				ParameterType = parameterType;
				HasDefaultValue = hasDefaultValue;
				DefaultValue = defaultValue;
				ArgumentIndex = argumentIndex;
				ServiceKey = serviceKey;
			}
		}

		private sealed class ConstructorInfoEx
		{
			public readonly ConstructorInfo Info;

			public readonly ParameterInfo[] Parameters;

			public readonly bool IsPreferred;

			private readonly object[] _parameterKeys;

			public ConstructorInfoEx(ConstructorInfo constructor)
			{
				Info = constructor;
				Parameters = constructor.GetParameters();
				IsPreferred = constructor.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);
				for (int i = 0; i < Parameters.Length; i++)
				{
					FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(Parameters[i], typeof(FromKeyedServicesAttribute), inherit: false);
					if (fromKeyedServicesAttribute != null)
					{
						if (_parameterKeys == null)
						{
							_parameterKeys = new object[Parameters.Length];
						}
						_parameterKeys[i] = fromKeyedServicesAttribute.Key;
					}
				}
			}

			public bool IsService(IServiceProviderIsService serviceProviderIsService, int parameterIndex)
			{
				ParameterInfo parameterInfo = Parameters[parameterIndex];
				object[] parameterKeys = _parameterKeys;
				object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null);
				if (obj != null)
				{
					if (serviceProviderIsService is IServiceProviderIsKeyedService serviceProviderIsKeyedService)
					{
						return serviceProviderIsKeyedService.IsKeyedService(parameterInfo.ParameterType, obj);
					}
					throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
				}
				return serviceProviderIsService.IsService(parameterInfo.ParameterType);
			}

			public object GetService(IServiceProvider serviceProvider, int parameterIndex)
			{
				ParameterInfo parameterInfo = Parameters[parameterIndex];
				object[] parameterKeys = _parameterKeys;
				object obj = ((parameterKeys != null) ? parameterKeys[parameterIndex] : null);
				if (obj != null)
				{
					if (serviceProvider is IKeyedServiceProvider keyedServiceProvider)
					{
						return keyedServiceProvider.GetKeyedService(parameterInfo.ParameterType, obj);
					}
					throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
				}
				return serviceProvider.GetService(parameterInfo.ParameterType);
			}
		}

		private readonly ref struct ConstructorMatcher
		{
			private readonly ConstructorInfoEx _constructor;

			private readonly object[] _parameterValues;

			public ConstructorInfoEx ConstructorInfo => _constructor;

			public ConstructorMatcher(ConstructorInfoEx constructor, object[] parameterValues)
			{
				_constructor = constructor;
				_parameterValues = parameterValues;
			}

			public int Match(object[] givenParameters, IServiceProviderIsService serviceProviderIsService)
			{
				for (int i = 0; i < givenParameters.Length; i++)
				{
					Type c = givenParameters[i]?.GetType();
					bool flag = false;
					for (int j = 0; j < _constructor.Parameters.Length; j++)
					{
						if (_parameterValues[j] == null && _constructor.Parameters[j].ParameterType.IsAssignableFrom(c))
						{
							flag = true;
							_parameterValues[j] = givenParameters[i];
							break;
						}
					}
					if (!flag)
					{
						return -1;
					}
				}
				for (int k = 0; k < _constructor.Parameters.Length; k++)
				{
					if (_parameterValues[k] == null && !_constructor.IsService(serviceProviderIsService, k))
					{
						if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[k], out object defaultValue))
						{
							return -1;
						}
						_parameterValues[k] = defaultValue;
					}
				}
				return _constructor.Parameters.Length;
			}

			public object CreateInstance(IServiceProvider provider)
			{
				for (int i = 0; i < _constructor.Parameters.Length; i++)
				{
					if (_parameterValues[i] != null)
					{
						continue;
					}
					object service = _constructor.GetService(provider, i);
					if (service == null)
					{
						if (!ParameterDefaultValue.TryGetDefaultValue(_constructor.Parameters[i], out object defaultValue))
						{
							throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, _constructor.Parameters[i].ParameterType, _constructor.Info.DeclaringType));
						}
						_parameterValues[i] = defaultValue;
					}
					else
					{
						_parameterValues[i] = service;
					}
				}
				try
				{
					return _constructor.Info.Invoke(_parameterValues);
				}
				catch (TargetInvocationException ex) when (ex.InnerException != null)
				{
					ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
					throw;
				}
			}

			public void MapParameters(int?[] parameterMap, object[] givenParameters)
			{
				for (int i = 0; i < _constructor.Parameters.Length; i++)
				{
					if (parameterMap[i].HasValue)
					{
						_parameterValues[i] = givenParameters[parameterMap[i].Value];
					}
				}
			}
		}

		private static readonly MethodInfo GetServiceInfo = new Func<IServiceProvider, Type, Type, bool, object, object>(GetService).Method;

		public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			if (instanceType.IsAbstract)
			{
				throw new InvalidOperationException(System.SR.CannotCreateAbstractClasses);
			}
			ConstructorInfoEx[] array = CreateConstructorInfoExs(instanceType);
			object[] ctorArgs2 = null;
			object[] array2 = null;
			ConstructorMatcher constructorMatcher = default(ConstructorMatcher);
			IServiceProviderIsService service = provider.GetService<IServiceProviderIsService>();
			ConstructorInfoEx constructorInfoEx;
			if (service != null)
			{
				for (int i = 0; i < array.Length; i++)
				{
					constructorInfoEx = array[i];
					if (!constructorInfoEx.IsPreferred)
					{
						continue;
					}
					for (int j = i + 1; j < array.Length; j++)
					{
						if (array[j].IsPreferred)
						{
							ThrowMultipleCtorsMarkedWithAttributeException();
						}
					}
					InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length);
					constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2);
					if (constructorMatcher.Match(parameters, service) == -1)
					{
						ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
					}
					return constructorMatcher.CreateInstance(provider);
				}
				int num = -1;
				ConstructorMatcher constructorMatcher2 = default(ConstructorMatcher);
				bool flag = false;
				for (int k = 0; k < array.Length; k++)
				{
					constructorInfoEx = array[k];
					InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length);
					constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2);
					int num2 = constructorMatcher.Match(parameters, service);
					if (num < num2)
					{
						num = num2;
						if (k == array.Length - 1)
						{
							array2 = ctorArgs2;
						}
						else
						{
							array2 = new object[num2];
							ctorArgs2.CopyTo(array2, 0);
						}
						constructorMatcher2 = new ConstructorMatcher(constructorMatcher.ConstructorInfo, array2);
						flag = false;
					}
					else if (num == num2)
					{
						flag = true;
					}
				}
				if (num != -1)
				{
					if (flag)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFoundWithBestLength, instanceType, num));
					}
					return constructorMatcher2.CreateInstance(provider);
				}
			}
			Type[] array3;
			if (parameters.Length == 0)
			{
				array3 = Type.EmptyTypes;
			}
			else
			{
				array3 = new Type[parameters.Length];
				for (int l = 0; l < array3.Length; l++)
				{
					array3[l] = parameters[l]?.GetType();
				}
			}
			FindApplicableConstructor(instanceType, array3, array, out var matchingConstructor, out var matchingParameterMap);
			constructorInfoEx = FindConstructorEx(matchingConstructor, array);
			InitializeCtorArgValues(ref ctorArgs2, constructorInfoEx.Parameters.Length);
			constructorMatcher = new ConstructorMatcher(constructorInfoEx, ctorArgs2);
			constructorMatcher.MapParameters(matchingParameterMap, parameters);
			return constructorMatcher.CreateInstance(provider);
			static void InitializeCtorArgValues(ref object[] ctorArgs, int length)
			{
				if (ctorArgs != null && ctorArgs.Length == length)
				{
					Array.Clear(ctorArgs, 0, length);
				}
				else
				{
					ctorArgs = new object[length];
				}
			}
		}

		private static ConstructorInfoEx[] CreateConstructorInfoExs([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
		{
			ConstructorInfo[] constructors = type.GetConstructors();
			ConstructorInfoEx[] array = new ConstructorInfoEx[constructors.Length];
			for (int i = 0; i < constructors.Length; i++)
			{
				array[i] = new ConstructorInfoEx(constructors[i]);
			}
			return array;
		}

		public static ObjectFactory CreateFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes)
		{
			if (!RuntimeFeature.IsDynamicCodeCompiled)
			{
				return CreateFactoryReflection(instanceType, argumentTypes);
			}
			CreateFactoryInternal(instanceType, argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody);
			return Expression.Lambda<ObjectFactory>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }).Compile();
		}

		public static ObjectFactory<T> CreateFactory<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(Type[] argumentTypes)
		{
			if (!RuntimeFeature.IsDynamicCodeCompiled)
			{
				ObjectFactory factory = CreateFactoryReflection(typeof(T), argumentTypes);
				return (IServiceProvider serviceProvider, object[] arguments) => (T)factory(serviceProvider, arguments);
			}
			CreateFactoryInternal(typeof(T), argumentTypes, out var provider, out var argumentArray, out var factoryExpressionBody);
			return Expression.Lambda<ObjectFactory<T>>(factoryExpressionBody, new ParameterExpression[2] { provider, argumentArray }).Compile();
		}

		private static void CreateFactoryInternal([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ParameterExpression provider, out ParameterExpression argumentArray, out Expression factoryExpressionBody)
		{
			FindApplicableConstructor(instanceType, argumentTypes, null, out var matchingConstructor, out var matchingParameterMap);
			provider = Expression.Parameter(typeof(IServiceProvider), "provider");
			argumentArray = Expression.Parameter(typeof(object[]), "argumentArray");
			factoryExpressionBody = BuildFactoryExpression(matchingConstructor, matchingParameterMap, provider, argumentArray);
		}

		public static T CreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider, params object[] parameters)
		{
			return (T)CreateInstance(provider, typeof(T), parameters);
		}

		public static T GetServiceOrCreateInstance<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] T>(IServiceProvider provider)
		{
			return (T)GetServiceOrCreateInstance(provider, typeof(T));
		}

		public static object GetServiceOrCreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type type)
		{
			return provider.GetService(type) ?? CreateInstance(provider, type);
		}

		private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool hasDefaultValue, object key)
		{
			object obj = ((key == null) ? sp.GetService(type) : GetKeyedService(sp, type, key));
			if (obj == null && !hasDefaultValue)
			{
				ThrowHelperUnableToResolveService(type, requiredBy);
			}
			return obj;
		}

		[DoesNotReturn]
		private static void ThrowHelperUnableToResolveService(Type type, Type requiredBy)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.UnableToResolveService, type, requiredBy));
		}

		private static BlockExpression BuildFactoryExpression(ConstructorInfo constructor, int?[] parameterMap, Expression serviceProvider, Expression factoryArgumentArray)
		{
			ParameterInfo[] parameters = constructor.GetParameters();
			Expression[] array = new Expression[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				ParameterInfo parameterInfo = parameters[i];
				Type parameterType = parameterInfo.ParameterType;
				object defaultValue;
				bool flag = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue);
				if (parameterMap[i].HasValue)
				{
					array[i] = Expression.ArrayAccess(factoryArgumentArray, Expression.Constant(parameterMap[i]));
				}
				else
				{
					FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false);
					Expression[] arguments = new Expression[5]
					{
						serviceProvider,
						Expression.Constant(parameterType, typeof(Type)),
						Expression.Constant(constructor.DeclaringType, typeof(Type)),
						Expression.Constant(flag),
						Expression.Constant(fromKeyedServicesAttribute?.Key, typeof(object))
					};
					array[i] = Expression.Call(GetServiceInfo, arguments);
				}
				if (flag)
				{
					ConstantExpression right = Expression.Constant(defaultValue);
					array[i] = Expression.Coalesce(array[i], right);
				}
				array[i] = Expression.Convert(array[i], parameterType);
			}
			return Expression.Block(Expression.IfThen(Expression.Equal(serviceProvider, Expression.Constant(null)), Expression.Throw(Expression.Constant(new ArgumentNullException("serviceProvider")))), Expression.New(constructor, array));
		}

		private static ObjectFactory CreateFactoryReflection([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes)
		{
			FindApplicableConstructor(instanceType, argumentTypes, null, out var constructor, out var parameterMap);
			Type declaringType = constructor.DeclaringType;
			ParameterInfo[] constructorParameters = constructor.GetParameters();
			if (constructorParameters.Length == 0)
			{
				return (IServiceProvider serviceProvider, object[] arguments) => constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, null, null);
			}
			FactoryParameterContext[] parameters = GetFactoryParameterContext();
			return (IServiceProvider serviceProvider, object[] arguments) => ReflectionFactoryCanonical(constructor, parameters, declaringType, serviceProvider, arguments);
			FactoryParameterContext[] GetFactoryParameterContext()
			{
				FactoryParameterContext[] array = new FactoryParameterContext[constructorParameters.Length];
				for (int i = 0; i < constructorParameters.Length; i++)
				{
					ParameterInfo parameterInfo = constructorParameters[i];
					FromKeyedServicesAttribute fromKeyedServicesAttribute = (FromKeyedServicesAttribute)Attribute.GetCustomAttribute(parameterInfo, typeof(FromKeyedServicesAttribute), inherit: false);
					object defaultValue;
					bool hasDefaultValue = ParameterDefaultValue.TryGetDefaultValue(parameterInfo, out defaultValue);
					array[i] = new FactoryParameterContext(parameterInfo.ParameterType, hasDefaultValue, defaultValue, parameterMap[i].GetValueOrDefault(-1), fromKeyedServicesAttribute?.Key);
				}
				return array;
			}
		}

		private static void FindApplicableConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, ConstructorInfoEx[] constructors, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap)
		{
			if (!TryFindPreferredConstructor(instanceType, argumentTypes, constructors, out var matchingConstructor2, out var parameterMap) && !TryFindMatchingConstructor(instanceType, argumentTypes, out matchingConstructor2, out parameterMap))
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.CtorNotLocated, instanceType));
			}
			matchingConstructor = matchingConstructor2;
			matchingParameterMap = parameterMap;
		}

		private static ConstructorInfoEx FindConstructorEx(ConstructorInfo constructorInfo, ConstructorInfoEx[] constructorExs)
		{
			for (int i = 0; i < constructorExs.Length; i++)
			{
				if ((object)constructorExs[i].Info == constructorInfo)
				{
					return constructorExs[i];
				}
			}
			return null;
		}

		private static bool TryFindMatchingConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap)
		{
			matchingConstructor = null;
			parameterMap = null;
			ConstructorInfo[] constructors = instanceType.GetConstructors();
			foreach (ConstructorInfo constructorInfo in constructors)
			{
				if (TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2))
				{
					if (matchingConstructor != null)
					{
						throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsFound, instanceType));
					}
					matchingConstructor = constructorInfo;
					parameterMap = parameterMap2;
				}
			}
			if (matchingConstructor != null)
			{
				return true;
			}
			return false;
		}

		private static bool TryFindPreferredConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, ConstructorInfoEx[] constructors, [NotNullWhen(true)] out ConstructorInfo matchingConstructor, [NotNullWhen(true)] out int?[] parameterMap)
		{
			bool flag = false;
			matchingConstructor = null;
			parameterMap = null;
			if (constructors == null)
			{
				constructors = CreateConstructorInfoExs(instanceType);
			}
			ConstructorInfoEx[] array = constructors;
			foreach (ConstructorInfoEx constructorInfoEx in array)
			{
				if (constructorInfoEx.IsPreferred)
				{
					if (flag)
					{
						ThrowMultipleCtorsMarkedWithAttributeException();
					}
					if (!TryCreateParameterMap(constructorInfoEx.Info.GetParameters(), argumentTypes, out var parameterMap2))
					{
						ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
					}
					matchingConstructor = constructorInfoEx.Info;
					parameterMap = parameterMap2;
					flag = true;
				}
			}
			if (matchingConstructor != null)
			{
				return true;
			}
			return false;
		}

		private static bool TryCreateParameterMap(ParameterInfo[] constructorParameters, Type[] argumentTypes, out int?[] parameterMap)
		{
			parameterMap = new int?[constructorParameters.Length];
			for (int i = 0; i < argumentTypes.Length; i++)
			{
				bool flag = false;
				Type c = argumentTypes[i];
				for (int j = 0; j < constructorParameters.Length; j++)
				{
					if (!parameterMap[j].HasValue && constructorParameters[j].ParameterType.IsAssignableFrom(c))
					{
						flag = true;
						parameterMap[j] = i;
						break;
					}
				}
				if (!flag)
				{
					return false;
				}
			}
			return true;
		}

		private static void ThrowMultipleCtorsMarkedWithAttributeException()
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.MultipleCtorsMarkedWithAttribute, "ActivatorUtilitiesConstructorAttribute"));
		}

		private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments()
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.MarkedCtorMissingArgumentTypes, "ActivatorUtilitiesConstructorAttribute"));
		}

		private static object ReflectionFactoryCanonical(ConstructorInfo constructor, FactoryParameterContext[] parameters, Type declaringType, IServiceProvider serviceProvider, object[] arguments)
		{
			ExceptionPolyfills.ThrowIfNull(serviceProvider, "serviceProvider");
			object[] array = new object[parameters.Length];
			for (int i = 0; i < parameters.Length; i++)
			{
				ref FactoryParameterContext reference = ref parameters[i];
				array[i] = ((reference.ArgumentIndex != -1) ? arguments[reference.ArgumentIndex] : GetService(serviceProvider, reference.ParameterType, declaringType, reference.HasDefaultValue, reference.ServiceKey)) ?? reference.DefaultValue;
			}
			return constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, array, null);
		}

		private static object GetKeyedService(IServiceProvider provider, Type type, object serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			if (provider is IKeyedServiceProvider keyedServiceProvider)
			{
				return keyedServiceProvider.GetKeyedService(type, serviceKey);
			}
			throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
		}
	}
	[AttributeUsage(AttributeTargets.All)]
	public class ActivatorUtilitiesConstructorAttribute : Attribute
	{
	}
	[DebuggerDisplay("{ServiceProvider,nq}")]
	public readonly struct AsyncServiceScope : IServiceScope, IDisposable, IAsyncDisposable
	{
		private readonly IServiceScope _serviceScope;

		public IServiceProvider ServiceProvider => _serviceScope.ServiceProvider;

		public AsyncServiceScope(IServiceScope serviceScope)
		{
			ExceptionPolyfills.ThrowIfNull(serviceScope, "serviceScope");
			_serviceScope = serviceScope;
		}

		public void Dispose()
		{
			_serviceScope.Dispose();
		}

		public ValueTask DisposeAsync()
		{
			if (_serviceScope is IAsyncDisposable asyncDisposable)
			{
				return asyncDisposable.DisposeAsync();
			}
			_serviceScope.Dispose();
			return default(ValueTask);
		}
	}
	[AttributeUsage(AttributeTargets.Parameter)]
	public class FromKeyedServicesAttribute : Attribute
	{
		public object? Key { get; }

		public ServiceKeyLookupMode LookupMode { get; }

		public FromKeyedServicesAttribute(object? key)
		{
			Key = key;
			LookupMode = ((key == null) ? ServiceKeyLookupMode.NullKey : ServiceKeyLookupMode.ExplicitKey);
		}

		public FromKeyedServicesAttribute()
		{
			Key = null;
			LookupMode = ServiceKeyLookupMode.InheritKey;
		}
	}
	public interface IKeyedServiceProvider : IServiceProvider
	{
		object? GetKeyedService(Type serviceType, object? serviceKey);

		object GetRequiredKeyedService(Type serviceType, object? serviceKey);
	}
	public static class KeyedService
	{
		private sealed class AnyKeyObj
		{
			public override string ToString()
			{
				return "*";
			}
		}

		public static object AnyKey { get; } = new AnyKeyObj();

	}
	public interface IServiceCollection : IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable
	{
	}
	public interface IServiceProviderFactory<TContainerBuilder> where TContainerBuilder : notnull
	{
		TContainerBuilder CreateBuilder(IServiceCollection services);

		IServiceProvider CreateServiceProvider(TContainerBuilder containerBuilder);
	}
	public interface IServiceProviderIsKeyedService : IServiceProviderIsService
	{
		bool IsKeyedService(Type serviceType, object? serviceKey);
	}
	public interface IServiceProviderIsService
	{
		bool IsService(Type serviceType);
	}
	public interface IServiceScope : IDisposable
	{
		IServiceProvider ServiceProvider { get; }
	}
	public interface IServiceScopeFactory
	{
		IServiceScope CreateScope();
	}
	public interface ISupportRequiredService
	{
		object GetRequiredService(Type serviceType);
	}
	public delegate object ObjectFactory(IServiceProvider serviceProvider, object?[]? arguments);
	public delegate T ObjectFactory<out T>(IServiceProvider serviceProvider, object?[]? arguments);
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	[DebuggerTypeProxy(typeof(ServiceCollectionDebugView))]
	public class ServiceCollection : IServiceCollection, IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable
	{
		private sealed class ServiceCollectionDebugView
		{
			private readonly ServiceCollection _services;

			[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
			public ServiceDescriptor[] Items
			{
				get
				{
					ServiceDescriptor[] array = new ServiceDescriptor[_services.Count];
					_services.CopyTo(array, 0);
					return array;
				}
			}

			public ServiceCollectionDebugView(ServiceCollection services)
			{
				_services = services;
			}
		}

		private readonly List<ServiceDescriptor> _descriptors = new List<ServiceDescriptor>();

		private bool _isReadOnly;

		public int Count => _descriptors.Count;

		public bool IsReadOnly => _isReadOnly;

		public ServiceDescriptor this[int index]
		{
			get
			{
				return _descriptors[index];
			}
			set
			{
				CheckReadOnly();
				_descriptors[index] = value;
			}
		}

		public void Clear()
		{
			CheckReadOnly();
			_descriptors.Clear();
		}

		public bool Contains(ServiceDescriptor item)
		{
			return _descriptors.Contains(item);
		}

		public void CopyTo(ServiceDescriptor[] array, int arrayIndex)
		{
			_descriptors.CopyTo(array, arrayIndex);
		}

		public bool Remove(ServiceDescriptor item)
		{
			CheckReadOnly();
			return _descriptors.Remove(item);
		}

		public IEnumerator<ServiceDescriptor> GetEnumerator()
		{
			return _descriptors.GetEnumerator();
		}

		void ICollection<ServiceDescriptor>.Add(ServiceDescriptor item)
		{
			CheckReadOnly();
			_descriptors.Add(item);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public int IndexOf(ServiceDescriptor item)
		{
			return _descriptors.IndexOf(item);
		}

		public void Insert(int index, ServiceDescriptor item)
		{
			CheckReadOnly();
			_descriptors.Insert(index, item);
		}

		public void RemoveAt(int index)
		{
			CheckReadOnly();
			_descriptors.RemoveAt(index);
		}

		public void MakeReadOnly()
		{
			_isReadOnly = true;
		}

		private void CheckReadOnly()
		{
			if (_isReadOnly)
			{
				ThrowReadOnlyException();
			}
		}

		private static void ThrowReadOnlyException()
		{
			throw new InvalidOperationException(System.SR.ServiceCollectionReadOnly);
		}

		private string DebuggerToString()
		{
			string text = $"Count = {_descriptors.Count}";
			if (_isReadOnly)
			{
				text += ", IsReadOnly = true";
			}
			return text;
		}
	}
	public static class ServiceCollectionServiceExtensions
	{
		public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return Add(services, serviceType, implementationType, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Add(services, serviceType, implementationFactory, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddTransient(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			return services.AddTransient(serviceType, serviceType);
		}

		public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddTransient(typeof(TService));
		}

		public static IServiceCollection AddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddTransient(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddTransient<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddTransient(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return Add(services, serviceType, implementationType, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Add(services, serviceType, implementationFactory, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddScoped(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			return services.AddScoped(serviceType, serviceType);
		}

		public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddScoped(typeof(TService));
		}

		public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddScoped(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddScoped<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddScoped(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return Add(services, serviceType, implementationType, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Add(services, serviceType, implementationFactory, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddSingleton(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			return services.AddSingleton(serviceType, serviceType);
		}

		public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddSingleton(typeof(TService));
		}

		public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddSingleton(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddSingleton<TService, TImplementation>(this IServiceCollection services, Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddSingleton(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, object implementationInstance)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance");
			ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationInstance);
			services.Add(item);
			return services;
		}

		public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, TService implementationInstance) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance");
			return services.AddSingleton(typeof(TService), implementationInstance);
		}

		private static IServiceCollection Add(IServiceCollection collection, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
		{
			ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationType, lifetime);
			collection.Add(item);
			return collection;
		}

		private static IServiceCollection Add(IServiceCollection collection, Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime)
		{
			ServiceDescriptor item = new ServiceDescriptor(serviceType, implementationFactory, lifetime);
			collection.Add(item);
			return collection;
		}

		public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddKeyedTransient(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddKeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddKeyedTransient(typeof(TService), serviceKey, typeof(TImplementation));
		}

		public static IServiceCollection AddKeyedTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			return services.AddKeyedTransient(serviceType, serviceKey, serviceType);
		}

		public static IServiceCollection AddKeyedTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddKeyedTransient(typeof(TService), serviceKey);
		}

		public static IServiceCollection AddKeyedTransient<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedTransient<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedTransient(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddKeyedScoped(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddKeyedScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddKeyedScoped(typeof(TService), serviceKey, typeof(TImplementation));
		}

		public static IServiceCollection AddKeyedScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			return services.AddKeyedScoped(serviceType, serviceKey, serviceType);
		}

		public static IServiceCollection AddKeyedScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddKeyedScoped(typeof(TService), serviceKey);
		}

		public static IServiceCollection AddKeyedScoped<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedScoped<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedScoped(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return AddKeyed(services, serviceType, serviceKey, implementationType, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return AddKeyed(services, serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddKeyedSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection services, object? serviceKey) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TImplementation));
		}

		public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType, object? serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			return services.AddKeyedSingleton(serviceType, serviceKey, serviceType);
		}

		public static IServiceCollection AddKeyedSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services, object? serviceKey) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, typeof(TService));
		}

		public static IServiceCollection AddKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedSingleton<TService, TImplementation>(this IServiceCollection services, object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationFactory);
		}

		public static IServiceCollection AddKeyedSingleton(this IServiceCollection services, Type serviceType, object? serviceKey, object implementationInstance)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance");
			ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationInstance);
			services.Add(item);
			return services;
		}

		public static IServiceCollection AddKeyedSingleton<TService>(this IServiceCollection services, object? serviceKey, TService implementationInstance) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance");
			return services.AddKeyedSingleton(typeof(TService), serviceKey, implementationInstance);
		}

		private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
		{
			ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime);
			collection.Add(item);
			return collection;
		}

		private static IServiceCollection AddKeyed(IServiceCollection collection, Type serviceType, object serviceKey, Func<IServiceProvider, object, object> implementationFactory, ServiceLifetime lifetime)
		{
			ServiceDescriptor item = new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime);
			collection.Add(item);
			return collection;
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	public class ServiceDescriptor
	{
		[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		private Type _implementationType;

		private object _implementationInstance;

		private object _implementationFactory;

		public ServiceLifetime Lifetime { get; }

		public object? ServiceKey { get; }

		public Type ServiceType { get; }

		[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		public Type? ImplementationType
		{
			get
			{
				if (!IsKeyedService)
				{
					return _implementationType;
				}
				return null;
			}
		}

		[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		public Type? KeyedImplementationType
		{
			get
			{
				if (!IsKeyedService)
				{
					ThrowNonKeyedDescriptor();
				}
				return _implementationType;
			}
		}

		public object? ImplementationInstance
		{
			get
			{
				if (!IsKeyedService)
				{
					return _implementationInstance;
				}
				return null;
			}
		}

		public object? KeyedImplementationInstance
		{
			get
			{
				if (!IsKeyedService)
				{
					ThrowNonKeyedDescriptor();
				}
				return _implementationInstance;
			}
		}

		public Func<IServiceProvider, object>? ImplementationFactory
		{
			get
			{
				if (!IsKeyedService)
				{
					return (Func<IServiceProvider, object>)_implementationFactory;
				}
				return null;
			}
		}

		public Func<IServiceProvider, object?, object>? KeyedImplementationFactory
		{
			get
			{
				if (!IsKeyedService)
				{
					ThrowNonKeyedDescriptor();
				}
				return (Func<IServiceProvider, object, object>)_implementationFactory;
			}
		}

		public bool IsKeyedService => ServiceKey != null;

		public ServiceDescriptor(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
			: this(serviceType, null, implementationType, lifetime)
		{
		}

		public ServiceDescriptor(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
			: this(serviceType, serviceKey, lifetime)
		{
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			_implementationType = implementationType;
		}

		public ServiceDescriptor(Type serviceType, object instance)
			: this(serviceType, null, instance)
		{
		}

		public ServiceDescriptor(Type serviceType, object? serviceKey, object instance)
			: this(serviceType, serviceKey, ServiceLifetime.Singleton)
		{
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(instance, "instance");
			_implementationInstance = instance;
		}

		public ServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime)
			: this(serviceType, (object)null, lifetime)
		{
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(factory, "factory");
			_implementationFactory = factory;
		}

		public ServiceDescriptor(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> factory, ServiceLifetime lifetime)
		{
			Func<IServiceProvider, object, object> factory2 = factory;
			this..ctor(serviceType, serviceKey, lifetime);
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(factory2, "factory");
			if (serviceKey == null)
			{
				Func<IServiceProvider, object> implementationFactory = (IServiceProvider sp) => factory2(sp, null);
				_implementationFactory = implementationFactory;
			}
			else
			{
				_implementationFactory = factory2;
			}
		}

		private ServiceDescriptor(Type serviceType, object serviceKey, ServiceLifetime lifetime)
		{
			Lifetime = lifetime;
			ServiceType = serviceType;
			ServiceKey = serviceKey;
		}

		public override string ToString()
		{
			string text = string.Format("{0}: {1} {2}: {3} ", "ServiceType", ServiceType, "Lifetime", Lifetime);
			if (IsKeyedService)
			{
				text += string.Format("{0}: {1} ", "ServiceKey", ServiceKey);
				if (KeyedImplementationType != null)
				{
					return text + string.Format("{0}: {1}", "KeyedImplementationType", KeyedImplementationType);
				}
				if (KeyedImplementationFactory != null)
				{
					MethodInfo method = KeyedImplementationFactory.Method;
					string text2 = method.DeclaringType?.FullName;
					string name = method.Name;
					return text + "KeyedImplementationFactory: " + text2 + "." + name;
				}
				return text + string.Format("{0}: {1}", "KeyedImplementationInstance", KeyedImplementationInstance);
			}
			if (ImplementationType != null)
			{
				return text + string.Format("{0}: {1}", "ImplementationType", ImplementationType);
			}
			if (ImplementationFactory != null)
			{
				MethodInfo method2 = ImplementationFactory.Method;
				string text3 = method2.DeclaringType?.FullName;
				string name2 = method2.Name;
				return text + "ImplementationFactory: " + text3 + "." + name2;
			}
			return text + string.Format("{0}: {1}", "ImplementationInstance", ImplementationInstance);
		}

		internal Type GetImplementationType()
		{
			if (ServiceKey == null)
			{
				if (ImplementationType != null)
				{
					return ImplementationType;
				}
				if (ImplementationInstance != null)
				{
					return ImplementationInstance.GetType();
				}
				if (ImplementationFactory != null)
				{
					return ImplementationFactory.GetType().GenericTypeArguments[1];
				}
			}
			else
			{
				if (KeyedImplementationType != null)
				{
					return KeyedImplementationType;
				}
				if (KeyedImplementationInstance != null)
				{
					return KeyedImplementationInstance.GetType();
				}
				if (KeyedImplementationFactory != null)
				{
					return KeyedImplementationFactory.GetType().GenericTypeArguments[2];
				}
			}
			return null;
		}

		public static ServiceDescriptor Transient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return Describe(service, implementationType, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(service, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor KeyedTransient(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Scoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			return Describe(service, implementationType, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(service, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor KeyedScoped(Type service, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(service, serviceKey, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Singleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>((object)null, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object? serviceKey) where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed<TService, TImplementation>(serviceKey, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return Describe(service, implementationType, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton(Type service, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			return DescribeKeyed(service, serviceKey, implementationType, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton<TService, TImplementation>(object? serviceKey, Func<IServiceProvider, object?, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, Func<IServiceProvider, object?, TService> implementationFactory) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(typeof(TService), serviceKey, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton(Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			return DescribeKeyed(serviceType, serviceKey, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService>(TService implementationInstance) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance");
			return Singleton(typeof(TService), implementationInstance);
		}

		public static ServiceDescriptor KeyedSingleton<TService>(object? serviceKey, TService implementationInstance) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance");
			return KeyedSingleton(typeof(TService), serviceKey, implementationInstance);
		}

		public static ServiceDescriptor Singleton(Type serviceType, object implementationInstance)
		{
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance");
			return new ServiceDescriptor(serviceType, implementationInstance);
		}

		public static ServiceDescriptor KeyedSingleton(Type serviceType, object? serviceKey, object implementationInstance)
		{
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			ExceptionPolyfills.ThrowIfNull(implementationInstance, "implementationInstance");
			return new ServiceDescriptor(serviceType, serviceKey, implementationInstance);
		}

		private static ServiceDescriptor DescribeKeyed<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(object serviceKey, ServiceLifetime lifetime) where TService : class where TImplementation : class, TService
		{
			return DescribeKeyed(typeof(TService), serviceKey, typeof(TImplementation), lifetime);
		}

		public static ServiceDescriptor Describe(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, implementationType, lifetime);
		}

		public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, serviceKey, implementationType, lifetime);
		}

		public static ServiceDescriptor Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, implementationFactory, lifetime);
		}

		public static ServiceDescriptor DescribeKeyed(Type serviceType, object? serviceKey, Func<IServiceProvider, object?, object> implementationFactory, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, serviceKey, implementationFactory, lifetime);
		}

		private string DebuggerToString()
		{
			string text = $"Lifetime = {Lifetime}, ServiceType = \"{ServiceType.FullName}\"";
			if (IsKeyedService)
			{
				text += $", ServiceKey = \"{ServiceKey}\"";
				if (KeyedImplementationType != null)
				{
					return text + ", KeyedImplementationType = \"" + KeyedImplementationType.FullName + "\"";
				}
				if (KeyedImplementationFactory != null)
				{
					return text + $", KeyedImplementationFactory = {KeyedImplementationFactory.Method}";
				}
				return text + $", KeyedImplementationInstance = {KeyedImplementationInstance}";
			}
			if (ImplementationType != null)
			{
				return text + ", ImplementationType = \"" + ImplementationType.FullName + "\"";
			}
			if (ImplementationFactory != null)
			{
				return text + $", ImplementationFactory = {ImplementationFactory.Method}";
			}
			return text + $", ImplementationInstance = {ImplementationInstance}";
		}

		private static void ThrowNonKeyedDescriptor()
		{
			throw new InvalidOperationException(System.SR.NonKeyedDescriptorMisuse);
		}
	}
	[AttributeUsage(AttributeTargets.Parameter)]
	public class ServiceKeyAttribute : Attribute
	{
	}
	public enum ServiceKeyLookupMode
	{
		InheritKey,
		NullKey,
		ExplicitKey
	}
	public enum ServiceLifetime
	{
		Singleton,
		Scoped,
		Transient
	}
	public static class ServiceProviderKeyedServiceExtensions
	{
		public static T? GetKeyedService<T>(this IServiceProvider provider, object? serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			if (provider is IKeyedServiceProvider keyedServiceProvider)
			{
				return (T)keyedServiceProvider.GetKeyedService(typeof(T), serviceKey);
			}
			throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
		}

		public static object? GetKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			if (provider is IKeyedServiceProvider keyedServiceProvider)
			{
				return keyedServiceProvider.GetKeyedService(serviceType, serviceKey);
			}
			throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
		}

		public static object GetRequiredKeyedService(this IServiceProvider provider, Type serviceType, object? serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			if (provider is IKeyedServiceProvider keyedServiceProvider)
			{
				return keyedServiceProvider.GetRequiredKeyedService(serviceType, serviceKey);
			}
			throw new InvalidOperationException(System.SR.KeyedServicesNotSupported);
		}

		public static T GetRequiredKeyedService<T>(this IServiceProvider provider, object? serviceKey) where T : notnull
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			return (T)provider.GetRequiredKeyedService(typeof(T), serviceKey);
		}

		public static IEnumerable<T> GetKeyedServices<T>(this IServiceProvider provider, object? serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			return provider.GetRequiredKeyedService<IEnumerable<T>>(serviceKey);
		}

		[RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")]
		public static IEnumerable<object?> GetKeyedServices(this IServiceProvider provider, Type serviceType, object? serviceKey)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType);
			return (IEnumerable<object>)provider.GetRequiredKeyedService(serviceType2, serviceKey);
		}
	}
	public static class ServiceProviderServiceExtensions
	{
		public static T? GetService<T>(this IServiceProvider provider)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			return (T)provider.GetService(typeof(T));
		}

		public static object GetRequiredService(this IServiceProvider provider, Type serviceType)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			if (provider is ISupportRequiredService supportRequiredService)
			{
				return supportRequiredService.GetRequiredService(serviceType);
			}
			return provider.GetService(serviceType) ?? throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType));
		}

		public static T GetRequiredService<T>(this IServiceProvider provider) where T : notnull
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			return (T)provider.GetRequiredService(typeof(T));
		}

		public static IEnumerable<T> GetServices<T>(this IServiceProvider provider)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			return provider.GetRequiredService<IEnumerable<T>>();
		}

		[RequiresDynamicCode("The native code for an IEnumerable<serviceType> might not be available at runtime.")]
		public static IEnumerable<object?> GetServices(this IServiceProvider provider, Type serviceType)
		{
			ExceptionPolyfills.ThrowIfNull(provider, "provider");
			ExceptionPolyfills.ThrowIfNull(serviceType, "serviceType");
			Type serviceType2 = typeof(IEnumerable<>).MakeGenericType(serviceType);
			return (IEnumerable<object>)provider.GetRequiredService(serviceType2);
		}

		public static IServiceScope CreateScope(this IServiceProvider provider)
		{
			return provider.GetRequiredService<IServiceScopeFactory>().CreateScope();
		}

		public static AsyncServiceScope CreateAsyncScope(this IServiceProvider provider)
		{
			return new AsyncServiceScope(provider.CreateScope());
		}

		public static AsyncServiceScope CreateAsyncScope(this IServiceScopeFactory serviceScopeFactory)
		{
			return new AsyncServiceScope(serviceScopeFactory.CreateScope());
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection.Extensions
{
	public static class ServiceCollectionDescriptorExtensions
	{
		public static IServiceCollection Add(this IServiceCollection collection, ServiceDescriptor descriptor)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor");
			collection.Add(descriptor);
			return collection;
		}

		public static IServiceCollection Add(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors");
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				collection.Add(descriptor);
			}
			return collection;
		}

		public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor");
			int count = collection.Count;
			for (int i = 0; i < count; i++)
			{
				if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey))
				{
					return;
				}
			}
			collection.Add(descriptor);
		}

		public static void TryAdd(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors");
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				collection.TryAdd(descriptor);
			}
		}

		public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			collection.TryAddTransient(typeof(TService), typeof(TService));
		}

		public static void TryAddTransient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			collection.TryAddTransient(typeof(TService), typeof(TImplementation));
		}

		public static void TryAddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			services.TryAdd(ServiceDescriptor.Transient(implementationFactory));
		}

		public static void TryAddScoped(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			collection.TryAddScoped(typeof(TService), typeof(TService));
		}

		public static void TryAddScoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			collection.TryAddScoped(typeof(TService), typeof(TImplementation));
		}

		public static void TryAddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			services.TryAdd(ServiceDescriptor.Scoped(implementationFactory));
		}

		public static void TryAddSingleton(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationType, "implementationType");
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(service, "service");
			ExceptionPolyfills.ThrowIfNull(implementationFactory, "implementationFactory");
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			collection.TryAddSingleton(typeof(TService), typeof(TService));
		}

		public static void TryAddSingleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(this IServiceCollection collection) where TService : class where TImplementation : class, TService
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			collection.TryAddSingleton(typeof(TService), typeof(TImplementation));
		}

		public static void TryAddSingleton<TService>(this IServiceCollection collection, TService instance) where TService : class
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(instance, "instance");
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(typeof(TService), instance);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			services.TryAdd(ServiceDescriptor.Singleton(implementationFactory));
		}

		public static void TryAddEnumerable(this IServiceCollection services, ServiceDescriptor descriptor)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor");
			Type implementationType = descriptor.GetImplementationType();
			if (implementationType == typeof(object) || implementationType == descriptor.ServiceType)
			{
				throw new ArgumentException(System.SR.Format(System.SR.TryAddIndistinguishableTypeToEnumerable, implementationType, descriptor.ServiceType), "descriptor");
			}
			int count = services.Count;
			for (int i = 0; i < count; i++)
			{
				ServiceDescriptor serviceDescriptor = services[i];
				if (serviceDescriptor.ServiceType == descriptor.ServiceType && serviceDescriptor.GetImplementationType() == implementationType && object.Equals(serviceDescriptor.ServiceKey, descriptor.ServiceKey))
				{
					return;
				}
			}
			services.Add(descriptor);
		}

		public static void TryAddEnumerable(this IServiceCollection services, IEnumerable<ServiceDescriptor> descriptors)
		{
			ExceptionPolyfills.ThrowIfNull(services, "services");
			ExceptionPolyfills.ThrowIfNull(descriptors, "descriptors");
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				services.TryAddEnumerable(descriptor);
			}
		}

		public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor)
		{
			ExceptionPolyfills.ThrowIfNull(collection, "collection");
			ExceptionPolyfills.ThrowIfNull(descriptor, "descriptor");
			int count = collection.Count;
			for (int i = 0; i < count; i++)
			{
				if (collection[i].ServiceType == descriptor.ServiceType && object.Equals(collection[i].ServiceKey, descriptor.ServiceKey))
				{
					collection.RemoveAt(i);
					break;
				}
			}
			collection.Add(descriptor);
			return collection;
		}

		public static IServiceCollection RemoveAll<T>(this IServiceCollection collection)
		{
			return collection.RemoveAll(typeof(T));
		}

		public static IServiceCollection RemoveAll(th

BepInEx/core/Microsoft.Extensions.Logging.Abstractions.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using FxResources.Microsoft.Extensions.Logging.Abstractions;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("Microsoft.Extensions.Logging.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f33a29044fa9d740c9b3213a93e57c84b472c84e0b8a0e1ae48e67a9f8f6de9d5f7f3d52ac23e48ac51801f1dc950abe901da34d2a9e3baadb141a17c77ef3c565dd5ee5054b91cf63bb3c6ab83f72ab3aafe93d0fc3c2348b764fafb0b1c0733de51459aeab46580384bf9d74c4e28164b7cde247f891ba07891c9d872ad2bb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Logging.Abstractions")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Logging abstractions for Microsoft.Extensions.Logging.\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Logging.ILogger\r\nMicrosoft.Extensions.Logging.ILoggerFactory\r\nMicrosoft.Extensions.Logging.ILogger<TCategoryName>\r\nMicrosoft.Extensions.Logging.LogLevel\r\nMicrosoft.Extensions.Logging.Logger<T>\r\nMicrosoft.Extensions.Logging.LoggerMessage\r\nMicrosoft.Extensions.Logging.Abstractions.NullLogger")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Logging.Abstractions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("10.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(true)]
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
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.Microsoft.Extensions.Logging.Abstractions
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string UnexpectedNumberOfNamedParameters => GetResourceString("UnexpectedNumberOfNamedParameters");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string? EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type? StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string? s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string? s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	internal static class TypeNameHelper
	{
		private readonly struct DisplayNameOptions
		{
			public bool FullName { get; }

			public bool IncludeGenericParameters { get; }

			public bool IncludeGenericParameterNames { get; }

			public char NestedTypeDelimiter { get; }

			public DisplayNameOptions(bool fullName, bool includeGenericParameterNames, bool includeGenericParameters, char nestedTypeDelimiter)
			{
				FullName = fullName;
				IncludeGenericParameters = includeGenericParameters;
				IncludeGenericParameterNames = includeGenericParameterNames;
				NestedTypeDelimiter = nestedTypeDelimiter;
			}
		}

		private const char DefaultNestedTypeDelimiter = '+';

		private static readonly Dictionary<Type, string> _builtInTypeNames = new Dictionary<Type, string>
		{
			{
				typeof(void),
				"void"
			},
			{
				typeof(bool),
				"bool"
			},
			{
				typeof(byte),
				"byte"
			},
			{
				typeof(char),
				"char"
			},
			{
				typeof(decimal),
				"decimal"
			},
			{
				typeof(double),
				"double"
			},
			{
				typeof(float),
				"float"
			},
			{
				typeof(int),
				"int"
			},
			{
				typeof(long),
				"long"
			},
			{
				typeof(object),
				"object"
			},
			{
				typeof(sbyte),
				"sbyte"
			},
			{
				typeof(short),
				"short"
			},
			{
				typeof(string),
				"string"
			},
			{
				typeof(uint),
				"uint"
			},
			{
				typeof(ulong),
				"ulong"
			},
			{
				typeof(ushort),
				"ushort"
			}
		};

		[return: NotNullIfNotNull("item")]
		public static string? GetTypeDisplayName(object? item, bool fullName = true)
		{
			if (item != null)
			{
				return GetTypeDisplayName(item.GetType(), fullName);
			}
			return null;
		}

		public static string GetTypeDisplayName(Type type, bool fullName = true, bool includeGenericParameterNames = false, bool includeGenericParameters = true, char nestedTypeDelimiter = '+')
		{
			StringBuilder builder = null;
			DisplayNameOptions options = new DisplayNameOptions(fullName, includeGenericParameterNames, includeGenericParameters, nestedTypeDelimiter);
			return ProcessType(ref builder, type, in options) ?? builder?.ToString() ?? string.Empty;
		}

		private static string ProcessType(ref StringBuilder builder, Type type, in DisplayNameOptions options)
		{
			string value;
			if (type.IsGenericType)
			{
				Type[] genericArguments = type.GetGenericArguments();
				if (builder == null)
				{
					builder = new StringBuilder();
				}
				ProcessGenericType(builder, type, genericArguments, genericArguments.Length, in options);
			}
			else if (type.IsArray)
			{
				if (builder == null)
				{
					builder = new StringBuilder();
				}
				ProcessArrayType(builder, type, in options);
			}
			else if (_builtInTypeNames.TryGetValue(type, out value))
			{
				if (builder == null)
				{
					return value;
				}
				builder.Append(value);
			}
			else if (type.IsGenericParameter)
			{
				if (options.IncludeGenericParameterNames)
				{
					if (builder == null)
					{
						return type.Name;
					}
					builder.Append(type.Name);
				}
			}
			else
			{
				string text = (options.FullName ? type.FullName : type.Name);
				if (builder == null)
				{
					if (options.NestedTypeDelimiter != '+')
					{
						return text.Replace('+', options.NestedTypeDelimiter);
					}
					return text;
				}
				builder.Append(text);
				if (options.NestedTypeDelimiter != '+')
				{
					builder.Replace('+', options.NestedTypeDelimiter, builder.Length - text.Length, text.Length);
				}
			}
			return null;
		}

		private static void ProcessArrayType(StringBuilder builder, Type type, in DisplayNameOptions options)
		{
			Type type2 = type;
			while (type2.IsArray)
			{
				type2 = type2.GetElementType();
			}
			ProcessType(ref builder, type2, in options);
			while (type.IsArray)
			{
				builder.Append('[');
				builder.Append(',', type.GetArrayRank() - 1);
				builder.Append(']');
				type = type.GetElementType();
			}
		}

		private static void ProcessGenericType(StringBuilder builder, Type type, Type[] genericArguments, int length, in DisplayNameOptions options)
		{
			int num = 0;
			if (type.IsNested)
			{
				num = type.DeclaringType.GetGenericArguments().Length;
			}
			if (options.FullName)
			{
				if (type.IsNested)
				{
					ProcessGenericType(builder, type.DeclaringType, genericArguments, num, in options);
					builder.Append(options.NestedTypeDelimiter);
				}
				else if (!string.IsNullOrEmpty(type.Namespace))
				{
					builder.Append(type.Namespace);
					builder.Append('.');
				}
			}
			int num2 = type.Name.IndexOf('`');
			if (num2 <= 0)
			{
				builder.Append(type.Name);
				return;
			}
			builder.Append(type.Name, 0, num2);
			if (!options.IncludeGenericParameters)
			{
				return;
			}
			builder.Append('<');
			for (int i = num; i < length; i++)
			{
				ProcessType(ref builder, genericArguments[i], in options);
				if (i + 1 != length)
				{
					builder.Append(',');
					if (options.IncludeGenericParameterNames || !genericArguments[i + 1].IsGenericParameter)
					{
						builder.Append(' ');
					}
				}
			}
			builder.Append('>');
		}
	}
}
namespace Microsoft.Extensions.Logging
{
	public readonly struct EventId : IEquatable<EventId>
	{
		public int Id { get; }

		public string? Name { get; }

		public static implicit operator EventId(int i)
		{
			return new EventId(i);
		}

		public static bool operator ==(EventId left, EventId right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(EventId left, EventId right)
		{
			return !left.Equals(right);
		}

		public EventId(int id, string? name = null)
		{
			Id = id;
			Name = name;
		}

		public override string ToString()
		{
			return Name ?? Id.ToString();
		}

		public bool Equals(EventId other)
		{
			return Id == other.Id;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj == null)
			{
				return false;
			}
			if (obj is EventId other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return Id;
		}
	}
	internal struct FormattedLogValues : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>>
	{
		[CompilerGenerated]
		private sealed class <GetEnumerator>d__15 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private KeyValuePair<string, object> <>2__current;

			public FormattedLogValues <>4__this;

			private int <i>5__2;

			KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

			[DebuggerHidden]
			public <GetEnumerator>d__15(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				switch (<>1__state)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<i>5__2 = 0;
					break;
				case 1:
				{
					<>1__state = -1;
					int num = <i>5__2 + 1;
					<i>5__2 = num;
					break;
				}
				}
				if (<i>5__2 < <>4__this.Count)
				{
					<>2__current = <>4__this[<i>5__2];
					<>1__state = 1;
					return true;
				}
				return false;
			}

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

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		internal const int MaxCachedFormatters = 1024;

		private const string NullFormat = "[null]";

		private static int s_count;

		private static readonly ConcurrentDictionary<string, LogValuesFormatter> s_formatters = new ConcurrentDictionary<string, LogValuesFormatter>();

		private readonly LogValuesFormatter _formatter;

		private readonly object[] _values;

		private readonly string _originalMessage;

		private string _cachedToString;

		internal LogValuesFormatter? Formatter => _formatter;

		public KeyValuePair<string, object?> this[int index]
		{
			get
			{
				if (index < 0 || index >= Count)
				{
					throw new IndexOutOfRangeException("index");
				}
				if (index == Count - 1)
				{
					return new KeyValuePair<string, object>("{OriginalFormat}", _originalMessage);
				}
				return _formatter.GetValue(_values, index);
			}
		}

		public int Count
		{
			get
			{
				if (_formatter == null)
				{
					return 1;
				}
				return _formatter.ValueNames.Count + 1;
			}
		}

		public FormattedLogValues(string? format, params object?[]? values)
		{
			if (values != null && values.Length != 0 && format != null)
			{
				if (s_count >= 1024)
				{
					if (!s_formatters.TryGetValue(format, out _formatter))
					{
						_formatter = new LogValuesFormatter(format);
					}
				}
				else
				{
					_formatter = s_formatters.GetOrAdd(format, delegate(string f)
					{
						Interlocked.Increment(ref s_count);
						return new LogValuesFormatter(f);
					});
				}
			}
			else
			{
				_formatter = null;
			}
			_originalMessage = format ?? "[null]";
			_values = values;
			_cachedToString = null;
		}

		[IteratorStateMachine(typeof(<GetEnumerator>d__15))]
		public IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetEnumerator>d__15(0)
			{
				<>4__this = this
			};
		}

		public override string ToString()
		{
			if (_formatter == null)
			{
				return _originalMessage;
			}
			return _cachedToString ?? (_cachedToString = _formatter.Format(_values));
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public interface IExternalScopeProvider
	{
		void ForEachScope<TState>(Action<object?, TState> callback, TState state);

		IDisposable Push(object? state);
	}
	public interface ILogger
	{
		void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter);

		bool IsEnabled(LogLevel logLevel);

		IDisposable? BeginScope<TState>(TState state) where TState : notnull;
	}
	public interface ILoggerFactory : IDisposable
	{
		ILogger CreateLogger(string categoryName);

		void AddProvider(ILoggerProvider provider);
	}
	public interface ILoggerProvider : IDisposable
	{
		ILogger CreateLogger(string categoryName);
	}
	public interface ILogger<out TCategoryName> : ILogger
	{
	}
	public interface ILoggingBuilder
	{
		IServiceCollection Services { get; }
	}
	public interface ISupportExternalScope
	{
		void SetScopeProvider(IExternalScopeProvider scopeProvider);
	}
	public class LogDefineOptions
	{
		public bool SkipEnabledCheck { get; set; }
	}
	public static class LoggerExtensions
	{
		private static readonly Func<FormattedLogValues, Exception, string> _messageFormatter = MessageFormatter;

		public static void LogDebug(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Debug, eventId, exception, message, args);
		}

		public static void LogDebug(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Debug, eventId, message, args);
		}

		public static void LogDebug(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Debug, exception, message, args);
		}

		public static void LogDebug(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Debug, message, args);
		}

		public static void LogTrace(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Trace, eventId, exception, message, args);
		}

		public static void LogTrace(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Trace, eventId, message, args);
		}

		public static void LogTrace(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Trace, exception, message, args);
		}

		public static void LogTrace(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Trace, message, args);
		}

		public static void LogInformation(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Information, eventId, exception, message, args);
		}

		public static void LogInformation(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Information, eventId, message, args);
		}

		public static void LogInformation(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Information, exception, message, args);
		}

		public static void LogInformation(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Information, message, args);
		}

		public static void LogWarning(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Warning, eventId, exception, message, args);
		}

		public static void LogWarning(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Warning, eventId, message, args);
		}

		public static void LogWarning(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Warning, exception, message, args);
		}

		public static void LogWarning(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Warning, message, args);
		}

		public static void LogError(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Error, eventId, exception, message, args);
		}

		public static void LogError(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Error, eventId, message, args);
		}

		public static void LogError(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Error, exception, message, args);
		}

		public static void LogError(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Error, message, args);
		}

		public static void LogCritical(this ILogger logger, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Critical, eventId, exception, message, args);
		}

		public static void LogCritical(this ILogger logger, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Critical, eventId, message, args);
		}

		public static void LogCritical(this ILogger logger, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Critical, exception, message, args);
		}

		public static void LogCritical(this ILogger logger, string? message, params object?[] args)
		{
			logger.Log(LogLevel.Critical, message, args);
		}

		public static void Log(this ILogger logger, LogLevel logLevel, string? message, params object?[] args)
		{
			logger.Log(logLevel, 0, null, message, args);
		}

		public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, string? message, params object?[] args)
		{
			logger.Log(logLevel, eventId, null, message, args);
		}

		public static void Log(this ILogger logger, LogLevel logLevel, Exception? exception, string? message, params object?[] args)
		{
			logger.Log(logLevel, 0, exception, message, args);
		}

		public static void Log(this ILogger logger, LogLevel logLevel, EventId eventId, Exception? exception, string? message, params object?[] args)
		{
			ExceptionPolyfills.ThrowIfNull(logger, "logger");
			logger.Log(logLevel, eventId, new FormattedLogValues(message, args), exception, _messageFormatter);
		}

		public static IDisposable? BeginScope(this ILogger logger, string messageFormat, params object?[] args)
		{
			ExceptionPolyfills.ThrowIfNull(logger, "logger");
			return logger.BeginScope(new FormattedLogValues(messageFormat, args));
		}

		private static string MessageFormatter(FormattedLogValues state, Exception error)
		{
			return state.ToString();
		}
	}
	public class LoggerExternalScopeProvider : IExternalScopeProvider
	{
		private sealed class Scope : IDisposable
		{
			private readonly LoggerExternalScopeProvider _provider;

			private bool _isDisposed;

			public Scope Parent { get; }

			public object State { get; }

			internal Scope(LoggerExternalScopeProvider provider, object state, Scope parent)
			{
				_provider = provider;
				State = state;
				Parent = parent;
			}

			public override string ToString()
			{
				return State?.ToString();
			}

			public void Dispose()
			{
				if (!_isDisposed)
				{
					_provider._currentScope.Value = Parent;
					_isDisposed = true;
				}
			}
		}

		private readonly AsyncLocal<Scope> _currentScope = new AsyncLocal<Scope>();

		public void ForEachScope<TState>(Action<object?, TState> callback, TState state)
		{
			Action<object, TState> callback2 = callback;
			TState state2 = state;
			Report(_currentScope.Value);
			void Report(Scope? current)
			{
				if (current != null)
				{
					Report(current.Parent);
					callback2(current.State, state2);
				}
			}
		}

		public IDisposable Push(object? state)
		{
			Scope value = _currentScope.Value;
			Scope scope = new Scope(this, state, value);
			_currentScope.Value = scope;
			return scope;
		}
	}
	public static class LoggerFactoryExtensions
	{
		public static ILogger<T> CreateLogger<T>(this ILoggerFactory factory)
		{
			ExceptionPolyfills.ThrowIfNull(factory, "factory");
			return new Logger<T>(factory);
		}

		public static ILogger CreateLogger(this ILoggerFactory factory, Type type)
		{
			ExceptionPolyfills.ThrowIfNull(factory, "factory");
			ExceptionPolyfills.ThrowIfNull(type, "type");
			return factory.CreateLogger(TypeNameHelper.GetTypeDisplayName(type, fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.'));
		}
	}
	public static class LoggerMessage
	{
		private readonly struct LogValues : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__7 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object> <>2__current;

				public LogValues <>4__this;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__7(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<>2__current = <>4__this[0];
						<>1__state = 1;
						return true;
					case 1:
						<>1__state = -1;
						return false;
					}
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			public static readonly Func<LogValues, Exception, string> Callback = (LogValues state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			public KeyValuePair<string, object> this[int index]
			{
				get
				{
					if (index == 0)
					{
						return new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat);
					}
					throw new IndexOutOfRangeException("index");
				}
			}

			public int Count => 1;

			public LogValues(LogValuesFormatter formatter)
			{
				_formatter = formatter;
			}

			[IteratorStateMachine(typeof(<GetEnumerator>d__7))]
			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__7(0)
				{
					<>4__this = this
				};
			}

			public override string ToString()
			{
				return _formatter.Format();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__8 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object> <>2__current;

				public LogValues<T0> <>4__this;

				private int <i>5__2;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__8(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<i>5__2 = 0;
						break;
					case 1:
					{
						<>1__state = -1;
						int num = <i>5__2 + 1;
						<i>5__2 = num;
						break;
					}
					}
					if (<i>5__2 < <>4__this.Count)
					{
						<>2__current = <>4__this[<i>5__2];
						<>1__state = 1;
						return true;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			public static readonly Func<LogValues<T0>, Exception, string> Callback = (LogValues<T0> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public int Count => 2;

			public LogValues(LogValuesFormatter formatter, T0 value0)
			{
				_formatter = formatter;
				_value0 = value0;
			}

			[IteratorStateMachine(typeof(LogValues<>.<GetEnumerator>d__8))]
			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__8(0)
				{
					<>4__this = this
				};
			}

			public override string ToString()
			{
				return _formatter.Format(_value0);
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__9 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object> <>2__current;

				public LogValues<T0, T1> <>4__this;

				private int <i>5__2;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__9(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<i>5__2 = 0;
						break;
					case 1:
					{
						<>1__state = -1;
						int num = <i>5__2 + 1;
						<i>5__2 = num;
						break;
					}
					}
					if (<i>5__2 < <>4__this.Count)
					{
						<>2__current = <>4__this[<i>5__2];
						<>1__state = 1;
						return true;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			public static readonly Func<LogValues<T0, T1>, Exception, string> Callback = (LogValues<T0, T1> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public int Count => 3;

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
			}

			[IteratorStateMachine(typeof(LogValues<, >.<GetEnumerator>d__9))]
			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__9(0)
				{
					<>4__this = this
				};
			}

			public override string ToString()
			{
				return _formatter.Format(_value0, _value1);
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1, T2> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__11 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object> <>2__current;

				public LogValues<T0, T1, T2> <>4__this;

				private int <i>5__2;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__11(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<i>5__2 = 0;
						break;
					case 1:
					{
						<>1__state = -1;
						int num = <i>5__2 + 1;
						<i>5__2 = num;
						break;
					}
					}
					if (<i>5__2 < <>4__this.Count)
					{
						<>2__current = <>4__this[<i>5__2];
						<>1__state = 1;
						return true;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			public static readonly Func<LogValues<T0, T1, T2>, Exception, string> Callback = (LogValues<T0, T1, T2> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			private readonly T2 _value2;

			public int Count => 4;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 
				3 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
				_value2 = value2;
			}

			public override string ToString()
			{
				return _formatter.Format(_value0, _value1, _value2);
			}

			[IteratorStateMachine(typeof(LogValues<, , >.<GetEnumerator>d__11))]
			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__11(0)
				{
					<>4__this = this
				};
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1, T2, T3> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__13 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object> <>2__current;

				public LogValues<T0, T1, T2, T3> <>4__this;

				private int <i>5__2;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__13(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<i>5__2 = 0;
						break;
					case 1:
					{
						<>1__state = -1;
						int num = <i>5__2 + 1;
						<i>5__2 = num;
						break;
					}
					}
					if (<i>5__2 < <>4__this.Count)
					{
						<>2__current = <>4__this[<i>5__2];
						<>1__state = 1;
						return true;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			public static readonly Func<LogValues<T0, T1, T2, T3>, Exception, string> Callback = (LogValues<T0, T1, T2, T3> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			private readonly T2 _value2;

			private readonly T3 _value3;

			public int Count => 5;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 
				3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 
				4 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
				_value2 = value2;
				_value3 = value3;
			}

			private object[] ToArray()
			{
				return new object[4] { _value0, _value1, _value2, _value3 };
			}

			public override string ToString()
			{
				return _formatter.FormatWithOverwrite(ToArray());
			}

			[IteratorStateMachine(typeof(LogValues<, , , >.<GetEnumerator>d__13))]
			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__13(0)
				{
					<>4__this = this
				};
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1, T2, T3, T4> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__14 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object> <>2__current;

				public LogValues<T0, T1, T2, T3, T4> <>4__this;

				private int <i>5__2;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__14(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<i>5__2 = 0;
						break;
					case 1:
					{
						<>1__state = -1;
						int num = <i>5__2 + 1;
						<i>5__2 = num;
						break;
					}
					}
					if (<i>5__2 < <>4__this.Count)
					{
						<>2__current = <>4__this[<i>5__2];
						<>1__state = 1;
						return true;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			public static readonly Func<LogValues<T0, T1, T2, T3, T4>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			private readonly T2 _value2;

			private readonly T3 _value3;

			private readonly T4 _value4;

			public int Count => 6;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 
				3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 
				4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 
				5 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
				_value2 = value2;
				_value3 = value3;
				_value4 = value4;
			}

			private object[] ToArray()
			{
				return new object[5] { _value0, _value1, _value2, _value3, _value4 };
			}

			public override string ToString()
			{
				return _formatter.FormatWithOverwrite(ToArray());
			}

			[IteratorStateMachine(typeof(LogValues<, , , , >.<GetEnumerator>d__14))]
			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__14(0)
				{
					<>4__this = this
				};
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly struct LogValues<T0, T1, T2, T3, T4, T5> : IReadOnlyList<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__15 : IEnumerator<KeyValuePair<string, object>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object> <>2__current;

				public LogValues<T0, T1, T2, T3, T4, T5> <>4__this;

				private int <i>5__2;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__15(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<i>5__2 = 0;
						break;
					case 1:
					{
						<>1__state = -1;
						int num = <i>5__2 + 1;
						<i>5__2 = num;
						break;
					}
					}
					if (<i>5__2 < <>4__this.Count)
					{
						<>2__current = <>4__this[<i>5__2];
						<>1__state = 1;
						return true;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			public static readonly Func<LogValues<T0, T1, T2, T3, T4, T5>, Exception, string> Callback = (LogValues<T0, T1, T2, T3, T4, T5> state, Exception exception) => state.ToString();

			private readonly LogValuesFormatter _formatter;

			private readonly T0 _value0;

			private readonly T1 _value1;

			private readonly T2 _value2;

			private readonly T3 _value3;

			private readonly T4 _value4;

			private readonly T5 _value5;

			public int Count => 7;

			public KeyValuePair<string, object> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>(_formatter.ValueNames[0], _value0), 
				1 => new KeyValuePair<string, object>(_formatter.ValueNames[1], _value1), 
				2 => new KeyValuePair<string, object>(_formatter.ValueNames[2], _value2), 
				3 => new KeyValuePair<string, object>(_formatter.ValueNames[3], _value3), 
				4 => new KeyValuePair<string, object>(_formatter.ValueNames[4], _value4), 
				5 => new KeyValuePair<string, object>(_formatter.ValueNames[5], _value5), 
				6 => new KeyValuePair<string, object>("{OriginalFormat}", _formatter.OriginalFormat), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public LogValues(LogValuesFormatter formatter, T0 value0, T1 value1, T2 value2, T3 value3, T4 value4, T5 value5)
			{
				_formatter = formatter;
				_value0 = value0;
				_value1 = value1;
				_value2 = value2;
				_value3 = value3;
				_value4 = value4;
				_value5 = value5;
			}

			private object[] ToArray()
			{
				return new object[6] { _value0, _value1, _value2, _value3, _value4, _value5 };
			}

			public override string ToString()
			{
				return _formatter.FormatWithOverwrite(ToArray());
			}

			[IteratorStateMachine(typeof(LogValues<, , , , , >.<GetEnumerator>d__15))]
			public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__15(0)
				{
					<>4__this = this
				};
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		public static Func<ILogger, IDisposable?> DefineScope(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0);
			LogValues logValues = new LogValues(formatter);
			return (ILogger logger) => logger.BeginScope(logValues);
		}

		public static Func<ILogger, T1, IDisposable?> DefineScope<T1>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1);
			return (ILogger logger, T1 arg1) => logger.BeginScope(new LogValues<T1>(formatter, arg1));
		}

		public static Func<ILogger, T1, T2, IDisposable?> DefineScope<T1, T2>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2);
			return (ILogger logger, T1 arg1, T2 arg2) => logger.BeginScope(new LogValues<T1, T2>(formatter, arg1, arg2));
		}

		public static Func<ILogger, T1, T2, T3, IDisposable?> DefineScope<T1, T2, T3>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3);
			return (ILogger logger, T1 arg1, T2 arg2, T3 arg3) => logger.BeginScope(new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3));
		}

		public static Func<ILogger, T1, T2, T3, T4, IDisposable?> DefineScope<T1, T2, T3, T4>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4);
			return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4) => logger.BeginScope(new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4));
		}

		public static Func<ILogger, T1, T2, T3, T4, T5, IDisposable?> DefineScope<T1, T2, T3, T4, T5>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5);
			return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5));
		}

		public static Func<ILogger, T1, T2, T3, T4, T5, T6, IDisposable?> DefineScope<T1, T2, T3, T4, T5, T6>(string formatString)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6);
			return (ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6) => logger.BeginScope(new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6));
		}

		public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, Exception?> Define(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 0);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, exception);
				}
			};
			void Log(ILogger logger, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues(formatter), exception, LogValues.Callback);
			}
		}

		public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, Exception?> Define<T1>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 1);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1>(formatter, arg1), exception, LogValues<T1>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, Exception?> Define<T1, T2>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 2);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2>(formatter, arg1, arg2), exception, LogValues<T1, T2>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2, T3>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, T3, Exception?> Define<T1, T2, T3>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 3);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, arg3, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2, T3>(formatter, arg1, arg2, arg3), exception, LogValues<T1, T2, T3>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2, T3, T4>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, T3, T4, Exception?> Define<T1, T2, T3, T4>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 4);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, arg3, arg4, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4>(formatter, arg1, arg2, arg3, arg4), exception, LogValues<T1, T2, T3, T4>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2, T3, T4, T5>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, T3, T4, T5, Exception?> Define<T1, T2, T3, T4, T5>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 5);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, arg3, arg4, arg5, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5>(formatter, arg1, arg2, arg3, arg4, arg5), exception, LogValues<T1, T2, T3, T4, T5>.Callback);
			}
		}

		public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString)
		{
			return Define<T1, T2, T3, T4, T5, T6>(logLevel, eventId, formatString, null);
		}

		public static Action<ILogger, T1, T2, T3, T4, T5, T6, Exception?> Define<T1, T2, T3, T4, T5, T6>(LogLevel logLevel, EventId eventId, string formatString, LogDefineOptions? options)
		{
			LogValuesFormatter formatter = CreateLogValuesFormatter(formatString, 6);
			if (options != null && options.SkipEnabledCheck)
			{
				return Log;
			}
			return delegate(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception)
			{
				if (logger.IsEnabled(logLevel))
				{
					Log(logger, arg1, arg2, arg3, arg4, arg5, arg6, exception);
				}
			};
			void Log(ILogger logger, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, Exception exception)
			{
				logger.Log(logLevel, eventId, new LogValues<T1, T2, T3, T4, T5, T6>(formatter, arg1, arg2, arg3, arg4, arg5, arg6), exception, LogValues<T1, T2, T3, T4, T5, T6>.Callback);
			}
		}

		private static LogValuesFormatter CreateLogValuesFormatter(string formatString, int expectedNamedParameterCount)
		{
			LogValuesFormatter logValuesFormatter = new LogValuesFormatter(formatString);
			int count = logValuesFormatter.ValueNames.Count;
			if (count != expectedNamedParameterCount)
			{
				throw new ArgumentException(System.SR.Format(System.SR.UnexpectedNumberOfNamedParameters, formatString, expectedNamedParameterCount, count));
			}
			return logValuesFormatter;
		}
	}
	[AttributeUsage(AttributeTargets.Method)]
	public sealed class LoggerMessageAttribute : Attribute
	{
		public int EventId { get; set; } = -1;


		public string? EventName { get; set; }

		public LogLevel Level { get; set; } = LogLevel.None;


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


		public bool SkipEnabledCheck { get; set; }

		public LoggerMessageAttribute()
		{
		}

		public LoggerMessageAttribute(int eventId, LogLevel level, string message)
		{
			EventId = eventId;
			Level = level;
			Message = message;
		}

		public LoggerMessageAttribute(LogLevel level, string message)
		{
			Level = level;
			Message = message;
		}

		public LoggerMessageAttribute(LogLevel level)
		{
			Level = level;
		}

		public LoggerMessageAttribute(string message)
		{
			Message = message;
		}
	}
	[DebuggerDisplay("{DebuggerToString(),nq}")]
	public class Logger<T> : ILogger<T>, ILogger
	{
		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		private readonly ILogger _logger;

		public Logger(ILoggerFactory factory)
		{
			ExceptionPolyfills.ThrowIfNull(factory, "factory");
			_logger = factory.CreateLogger(GetCategoryName());
		}

		IDisposable ILogger.BeginScope<TState>(TState state)
		{
			return _logger.BeginScope(state);
		}

		bool ILogger.IsEnabled(LogLevel logLevel)
		{
			return _logger.IsEnabled(logLevel);
		}

		void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
		{
			_logger.Log(logLevel, eventId, state, exception, formatter);
		}

		private static string GetCategoryName()
		{
			return TypeNameHelper.GetTypeDisplayName(typeof(T), fullName: true, includeGenericParameterNames: false, includeGenericParameters: false, '.');
		}

		internal string DebuggerToString()
		{
			return DebuggerDisplayFormatting.DebuggerToString(GetCategoryName(), this);
		}
	}
	public enum LogLevel
	{
		Trace,
		Debug,
		Information,
		Warning,
		Error,
		Critical,
		None
	}
	internal sealed class LogValuesFormatter
	{
		private const string NullValue = "(null)";

		private readonly List<string> _valueNames = new List<string>();

		private readonly string _format;

		public string OriginalFormat { get; }

		public List<string> ValueNames => _valueNames;

		public LogValuesFormatter(string format)
		{
			ExceptionPolyfills.ThrowIfNull(format, "format");
			OriginalFormat = format;
			Span<char> initialBuffer = stackalloc char[256];
			System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer);
			int num = 0;
			int length = format.Length;
			while (num < length)
			{
				int num2 = FindBraceIndex(format, '{', num, length);
				if (num == 0 && num2 == length)
				{
					_format = format;
					return;
				}
				int num3 = FindBraceIndex(format, '}', num2, length);
				if (num3 == length)
				{
					valueStringBuilder.Append(format.AsSpan(num, length - num));
					num = length;
					continue;
				}
				int num4 = format.AsSpan(num2, num3 - num2).IndexOfAny(',', ':');
				num4 = ((num4 < 0) ? num3 : (num4 + num2));
				valueStringBuilder.Append(format.AsSpan(num, num2 - num + 1));
				valueStringBuilder.Append(_valueNames.Count.ToString(CultureInfo.InvariantCulture));
				_valueNames.Add(format.Substring(num2 + 1, num4 - num2 - 1));
				valueStringBuilder.Append(format.AsSpan(num4, num3 - num4 + 1));
				num = num3 + 1;
			}
			_format = valueStringBuilder.ToString();
		}

		private static int FindBraceIndex(string format, char brace, int startIndex, int endIndex)
		{
			int result = endIndex;
			int i = startIndex;
			int num = 0;
			for (; i < endIndex; i++)
			{
				if (num > 0 && format[i] != brace)
				{
					if (num % 2 != 0)
					{
						break;
					}
					num = 0;
					result = endIndex;
				}
				else
				{
					if (format[i] != brace)
					{
						continue;
					}
					if (brace == '}')
					{
						if (num == 0)
						{
							result = i;
						}
					}
					else
					{
						result = i;
					}
					num++;
				}
			}
			return result;
		}

		public string Format(object?[]? values)
		{
			object[] array = values;
			if (values != null)
			{
				for (int i = 0; i < values.Length; i++)
				{
					object obj = FormatArgument(values[i]);
					if (obj != values[i])
					{
						array = new object[values.Length];
						Array.Copy(values, array, i);
						array[i++] = obj;
						for (; i < values.Length; i++)
						{
							array[i] = FormatArgument(values[i]);
						}
						break;
					}
				}
			}
			return string.Format(CultureInfo.InvariantCulture, _format, array ?? Array.Empty<object>());
		}

		internal string FormatWithOverwrite(object?[]? values)
		{
			if (values != null)
			{
				for (int i = 0; i < values.Length; i++)
				{
					values[i] = FormatArgument(values[i]);
				}
			}
			return string.Format(CultureInfo.InvariantCulture, _format, values ?? Array.Empty<object>());
		}

		internal string Format()
		{
			return _format;
		}

		internal string Format(object? arg0)
		{
			return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0));
		}

		internal string Format(object? arg0, object? arg1)
		{
			return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1));
		}

		internal string Format(object? arg0, object? arg1, object? arg2)
		{
			return string.Format(CultureInfo.InvariantCulture, _format, FormatArgument(arg0), FormatArgument(arg1), FormatArgument(arg2));
		}

		public KeyValuePair<string, object?> GetValue(object?[] values, int index)
		{
			if (index < 0 || index > _valueNames.Count)
			{
				throw new IndexOutOfRangeException("index");
			}
			if (_valueNames.Count > index)
			{
				return new KeyValuePair<string, object>(_valueNames[index], values[index]);
			}
			return new KeyValuePair<string, object>("{OriginalFormat}", OriginalFormat);
		}

		public IEnumerable<KeyValuePair<string, object?>> GetValues(object[] values)
		{
			KeyValuePair<string, object>[] array = new KeyValuePair<string, object>[values.Length + 1];
			for (int i = 0; i != _valueNames.Count; i++)
			{
				array[i] = new KeyValuePair<string, object>(_valueNames[i], values[i]);
			}
			array[^1] = new KeyValuePair<string, object>("{OriginalFormat}", OriginalFormat);
			return array;
		}

		private static object FormatArgument(object value)
		{
			if (!TryFormatArgumentIfNullOrEnumerable(value, out var stringValue))
			{
				return value;
			}
			return stringValue;
		}

		private static bool TryFormatArgumentIfNullOrEnumerable<T>(T value, [NotNullWhen(true)] out object stringValue)
		{
			if (value == null)
			{
				stringValue = "(null)";
				return true;
			}
			if (!(value is string) && (object)value is IEnumerable enumerable)
			{
				Span<char> initialBuffer = stackalloc char[256];
				System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer);
				bool flag = true;
				foreach (object item in enumerable)
				{
					if (!flag)
					{
						valueStringBuilder.Append(", ");
					}
					valueStringBuilder.Append((item is IFormattable formattable) ? formattable.ToString(null, CultureInfo.InvariantCulture) : ((item != null) ? item.ToString() : "(null)"));
					flag = false;
				}
				stringValue = valueStringBuilder.ToString();
				return true;
			}
			stringValue = null;
			return false;
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
	public class ProviderAliasAttribute : Attribute
	{
		public string Alias { get; }

		public ProviderAliasAttribute(string alias)
		{
			Alias = alias;
		}
	}
	internal sealed class NullExternalScopeProvider : IExternalScopeProvider
	{
		public static IExternalScopeProvider Instance { get; } = new NullExternalScopeProvider();


		private NullExternalScopeProvider()
		{
		}

		void IExternalScopeProvider.ForEachScope<TState>(Action<object, TState> callback, TState state)
		{
		}

		IDisposable IExternalScopeProvider.Push(object state)
		{
			return NullScope.Instance;
		}
	}
	internal sealed class NullScope : IDisposable
	{
		public static NullScope Instance { get; } = new NullScope();


		private NullScope()
		{
		}

		public void Dispose()
		{
		}
	}
	internal static class DebuggerDisplayFormatting
	{
		internal static string DebuggerToString(string name, ILogger logger)
		{
			LogLevel? logLevel = CalculateEnabledLogLevel(logger);
			string text = "Name = \"" + name + "\"";
			if (logLevel.HasValue)
			{
				return text + $", MinLevel = {logLevel}";
			}
			return text + ", Enabled = false";
		}

		internal static LogLevel? CalculateEnabledLogLevel(ILogger logger)
		{
			object obj = global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6;
			if (obj == null)
			{
				obj = new int[6] { 5, 4, 3, 2, 1, 0 };
				global::<PrivateImplementationDetails>.CAA894F8CBB8DC2FF3ED187413A26E53B37FCE43E7F0F09BAA4FE14884322DE8_A6 = (int[])obj;
			}
			ReadOnlySpan<LogLevel> readOnlySpan = new ReadOnlySpan<LogLevel>((LogLevel[]?)obj);
			LogLevel? result = null;
			ReadOnlySpan<LogLevel> readOnlySpan2 = readOnlySpan;
			for (int i = 0; i < readOnlySpan2.Length; i++)
			{
				LogLevel logLevel = readOnlySpan2[i];
				if (!logger.IsEnabled(logLevel))
				{
					break;
				}
				result = logLevel;
			}
			return result;
		}
	}
}
namespace Microsoft.Extensions.Logging.Abstractions
{
	public abstract class BufferedLogRecord
	{
		public abstract DateTimeOffset Timestamp { get; }

		public abstract LogLevel LogLevel { get; }

		public abstract EventId EventId { get; }

		public virtual string? Exception => null;

		public virtual ActivitySpanId? ActivitySpanId => null;

		public virtual ActivityTraceId? ActivityTraceId => null;

		public virtual int? ManagedThreadId => null;

		public virtual string? FormattedMessage => null;

		public virtual string? MessageTemplate => null;

		public virtual IReadOnlyList<KeyValuePair<string, object?>> Attributes => Array.Empty<KeyValuePair<string, object>>();
	}
	public interface IBufferedLogger
	{
		void LogRecords(IEnumerable<BufferedLogRecord> records);
	}
	public readonly struct LogEntry<TState>
	{
		public LogLevel LogLevel { get; }

		public string Category { get; }

		public EventId EventId { get; }

		public TState State { get; }

		public Exception? Exception { get; }

		public Func<TState, Exception?, string> Formatter { get; }

		public LogEntry(LogLevel logLevel, string category, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
		{
			LogLevel = logLevel;
			Category = category;
			EventId = eventId;
			State = state;
			Exception = exception;
			Formatter = formatter;
		}
	}
	public sealed class NullLogger : ILogger
	{
		public static NullLogger Instance { get; } = new NullLogger();


		private NullLogger()
		{
		}

		public IDisposable BeginScope<TState>(TState state) where TState : notnull
		{
			return NullScope.Instance;
		}

		public bool IsEnabled(LogLevel logLevel)
		{
			return false;
		}

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
		{
		}
	}
	public class NullLoggerFactory : ILoggerFactory, IDisposable
	{
		public static readonly NullLoggerFactory Instance = new NullLoggerFactory();

		public ILogger CreateLogger(string name)
		{
			return NullLogger.Instance;
		}

		public void AddProvider(ILoggerProvider provider)
		{
		}

		public void Dispose()
		{
		}
	}
	public sealed class NullLoggerProvider : ILoggerProvider, IDisposable
	{
		public static NullLoggerProvider Instance { get; } = new NullLoggerProvider();


		private NullLoggerProvider()
		{
		}

		public ILogger CreateLogger(string categoryName)
		{
			return NullLogger.Instance;
		}

		public void Dispose()
		{
		}
	}
	public class NullLogger<T> : ILogger<T>, ILogger
	{
		public static readonly NullLogger<T> Instance = new NullLogger<T>();

		public IDisposable BeginScope<TState>(TState state) where TState : notnull
		{
			return NullScope.Instance;
		}

		public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
		{
		}

		public bool IsEnabled(LogLevel logLevel)
		{
			return false;
		}
	}
}

BepInEx/core/Microsoft.Extensions.Primitives.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using FxResources.Microsoft.Extensions.Primitives;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.Primitives")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Primitives shared by framework extensions. Commonly used types include:\r\n\r\nCommonly Used Types:\r\nMicrosoft.Extensions.Primitives.IChangeToken\r\nMicrosoft.Extensions.Primitives.StringValues\r\nMicrosoft.Extensions.Primitives.StringSegment")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.Primitives")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("10.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.Microsoft.Extensions.Primitives
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Argument_InvalidOffsetLength => GetResourceString("Argument_InvalidOffsetLength");

		internal static string Argument_InvalidOffsetLengthStringSegment => GetResourceString("Argument_InvalidOffsetLengthStringSegment");

		internal static string Capacity_CannotChangeAfterWriteStarted => GetResourceString("Capacity_CannotChangeAfterWriteStarted");

		internal static string Capacity_NotEnough => GetResourceString("Capacity_NotEnough");

		internal static string Capacity_NotUsedEntirely => GetResourceString("Capacity_NotUsedEntirely");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace System.Numerics.Hashing
{
	internal static class HashHelpers
	{
		public static int Combine(int h1, int h2)
		{
			return (((h1 << 5) | (h1 >>> 27)) + h1) ^ h2;
		}
	}
}
namespace Microsoft.Extensions.FileProviders
{
	internal sealed class EmptyDisposable : IDisposable
	{
		public static EmptyDisposable Instance { get; } = new EmptyDisposable();


		private EmptyDisposable()
		{
		}

		public void Dispose()
		{
		}
	}
}
namespace Microsoft.Extensions.Internal
{
	internal static class ChangeCallbackRegistrar
	{
		internal static IDisposable UnsafeRegisterChangeCallback<T>(Action<object> callback, object state, CancellationToken token, Action<T> onFailure, T onFailureState)
		{
			bool flag = false;
			if (!ExecutionContext.IsFlowSuppressed())
			{
				ExecutionContext.SuppressFlow();
				flag = true;
			}
			try
			{
				return token.Register(callback, state);
			}
			catch (ObjectDisposedException)
			{
				onFailure(onFailureState);
			}
			finally
			{
				if (flag)
				{
					ExecutionContext.RestoreFlow();
				}
			}
			return EmptyDisposable.Instance;
		}
	}
}
namespace Microsoft.Extensions.Primitives
{
	[DebuggerDisplay("HasChanged = {HasChanged}")]
	public class CancellationChangeToken : IChangeToken
	{
		public bool ActiveChangeCallbacks { get; private set; } = true;


		public bool HasChanged => Token.IsCancellationRequested;

		private CancellationToken Token { get; }

		public CancellationChangeToken(CancellationToken cancellationToken)
		{
			Token = cancellationToken;
		}

		public IDisposable RegisterChangeCallback(Action<object?> callback, object? state)
		{
			return ChangeCallbackRegistrar.UnsafeRegisterChangeCallback(callback, state, Token, delegate(CancellationChangeToken s)
			{
				s.ActiveChangeCallbacks = false;
			}, this);
		}
	}
	public static class ChangeToken
	{
		private sealed class ChangeTokenRegistration<TState> : IDisposable
		{
			private sealed class NoopDisposable : IDisposable
			{
				public void Dispose()
				{
				}
			}

			private readonly Func<IChangeToken> _changeTokenProducer;

			private readonly Action<TState> _changeTokenConsumer;

			private readonly TState _state;

			private IDisposable _disposable;

			private static readonly NoopDisposable _disposedSentinel = new NoopDisposable();

			public ChangeTokenRegistration(Func<IChangeToken> changeTokenProducer, Action<TState> changeTokenConsumer, TState state)
			{
				_changeTokenProducer = changeTokenProducer;
				_changeTokenConsumer = changeTokenConsumer;
				_state = state;
				IChangeToken token = changeTokenProducer();
				RegisterChangeTokenCallback(token);
			}

			private void OnChangeTokenFired()
			{
				IChangeToken token = _changeTokenProducer();
				try
				{
					_changeTokenConsumer(_state);
				}
				finally
				{
					RegisterChangeTokenCallback(token);
				}
			}

			private void RegisterChangeTokenCallback(IChangeToken token)
			{
				if (token != null)
				{
					IDisposable disposable = token.RegisterChangeCallback(delegate(object s)
					{
						((ChangeTokenRegistration<TState>)s).OnChangeTokenFired();
					}, this);
					if (token.HasChanged && token.ActiveChangeCallbacks)
					{
						disposable?.Dispose();
					}
					else
					{
						SetDisposable(disposable);
					}
				}
			}

			private void SetDisposable(IDisposable disposable)
			{
				IDisposable disposable2 = Volatile.Read(ref _disposable);
				if (disposable2 == _disposedSentinel)
				{
					disposable.Dispose();
					return;
				}
				IDisposable disposable3 = Interlocked.CompareExchange(ref _disposable, disposable, disposable2);
				if (disposable3 == _disposedSentinel)
				{
					disposable.Dispose();
				}
				else if (disposable3 != disposable2)
				{
					throw new InvalidOperationException("Somebody else set the _disposable field");
				}
			}

			public void Dispose()
			{
				Interlocked.Exchange(ref _disposable, _disposedSentinel)?.Dispose();
			}
		}

		public static IDisposable OnChange(Func<IChangeToken?> changeTokenProducer, Action changeTokenConsumer)
		{
			if (changeTokenProducer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer);
			}
			if (changeTokenConsumer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer);
			}
			return new ChangeTokenRegistration<Action>(changeTokenProducer, delegate(Action callback)
			{
				callback();
			}, changeTokenConsumer);
		}

		public static IDisposable OnChange<TState>(Func<IChangeToken?> changeTokenProducer, Action<TState> changeTokenConsumer, TState state)
		{
			if (changeTokenProducer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenProducer);
			}
			if (changeTokenConsumer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokenConsumer);
			}
			return new ChangeTokenRegistration<TState>(changeTokenProducer, changeTokenConsumer, state);
		}
	}
	[DebuggerDisplay("HasChanged = {HasChanged}")]
	public class CompositeChangeToken : IChangeToken
	{
		private static readonly Action<object> _onChangeDelegate = OnChange;

		private readonly object _callbackLock = new object();

		private CancellationTokenSource _cancellationTokenSource;

		private List<IDisposable> _disposables;

		[MemberNotNullWhen(true, "_cancellationTokenSource")]
		[MemberNotNullWhen(true, "_disposables")]
		private bool RegisteredCallbackProxy
		{
			[MemberNotNullWhen(true, "_cancellationTokenSource")]
			[MemberNotNullWhen(true, "_disposables")]
			get;
			[MemberNotNullWhen(true, "_cancellationTokenSource")]
			[MemberNotNullWhen(true, "_disposables")]
			set;
		}

		public IReadOnlyList<IChangeToken> ChangeTokens { get; }

		public bool HasChanged
		{
			get
			{
				if (_cancellationTokenSource != null && _cancellationTokenSource.Token.IsCancellationRequested)
				{
					return true;
				}
				for (int i = 0; i < ChangeTokens.Count; i++)
				{
					if (ChangeTokens[i].HasChanged)
					{
						OnChange(this);
						return true;
					}
				}
				return false;
			}
		}

		public bool ActiveChangeCallbacks { get; }

		public CompositeChangeToken(IReadOnlyList<IChangeToken> changeTokens)
		{
			if (changeTokens == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.changeTokens);
			}
			ChangeTokens = changeTokens;
			for (int i = 0; i < ChangeTokens.Count; i++)
			{
				if (ChangeTokens[i].ActiveChangeCallbacks)
				{
					ActiveChangeCallbacks = true;
					break;
				}
			}
		}

		public IDisposable RegisterChangeCallback(Action<object?> callback, object? state)
		{
			EnsureCallbacksInitialized();
			return _cancellationTokenSource.Token.Register(callback, state);
		}

		[MemberNotNull("_cancellationTokenSource")]
		[MemberNotNull("_disposables")]
		private void EnsureCallbacksInitialized()
		{
			if (RegisteredCallbackProxy)
			{
				return;
			}
			lock (_callbackLock)
			{
				if (RegisteredCallbackProxy)
				{
					return;
				}
				_cancellationTokenSource = new CancellationTokenSource();
				_disposables = new List<IDisposable>();
				for (int i = 0; i < ChangeTokens.Count; i++)
				{
					if (ChangeTokens[i].ActiveChangeCallbacks)
					{
						IDisposable disposable = ChangeTokens[i].RegisterChangeCallback(_onChangeDelegate, this);
						if (_cancellationTokenSource.IsCancellationRequested)
						{
							disposable.Dispose();
							break;
						}
						_disposables.Add(disposable);
					}
				}
				RegisteredCallbackProxy = true;
			}
		}

		private static void OnChange(object state)
		{
			CompositeChangeToken compositeChangeToken = (CompositeChangeToken)state;
			if (compositeChangeToken._cancellationTokenSource == null)
			{
				return;
			}
			lock (compositeChangeToken._callbackLock)
			{
				if (compositeChangeToken._cancellationTokenSource.IsCancellationRequested)
				{
					return;
				}
				try
				{
					compositeChangeToken._cancellationTokenSource.Cancel();
				}
				catch
				{
				}
			}
			List<IDisposable> disposables = compositeChangeToken._disposables;
			for (int i = 0; i < disposables.Count; i++)
			{
				disposables[i].Dispose();
			}
		}
	}
	public static class Extensions
	{
		public static StringBuilder Append(this StringBuilder builder, StringSegment segment)
		{
			return builder.Append(segment.Buffer, segment.Offset, segment.Length);
		}
	}
	public interface IChangeToken
	{
		bool HasChanged { get; }

		bool ActiveChangeCallbacks { get; }

		IDisposable RegisterChangeCallback(Action<object?> callback, object? state);
	}
	[DebuggerDisplay("Value = {_value}")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	[Obsolete("This type is retained only for compatibility. The recommended alternative is string.Create<TState> (int length, TState state, System.Buffers.SpanAction<char,TState> action).", true)]
	public struct InplaceStringBuilder
	{
		private int _offset;

		private int _capacity;

		private string _value;

		public int Capacity
		{
			get
			{
				return _capacity;
			}
			set
			{
				if (value < 0)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.value);
				}
				if (_offset > 0)
				{
					ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_CannotChangeAfterWriteStarted);
				}
				_capacity = value;
			}
		}

		public InplaceStringBuilder(int capacity)
		{
			this = default(InplaceStringBuilder);
			if (capacity < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity);
			}
			_capacity = capacity;
		}

		public void Append(string? value)
		{
			if (value == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
			}
			Append(value, 0, value.Length);
		}

		public void Append(StringSegment segment)
		{
			Append(segment.Buffer, segment.Offset, segment.Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Append(string? value, int offset, int count)
		{
			EnsureValueIsInitialized();
			if (value == null || offset < 0 || value.Length - offset < count || Capacity - _offset < count)
			{
				ThrowValidationError(value, offset, count);
			}
			fixed (char* ptr = _value)
			{
				fixed (char* ptr2 = value)
				{
					Unsafe.CopyBlockUnaligned(ptr + _offset, ptr2 + offset, (uint)(count * 2));
					_offset += count;
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public unsafe void Append(char c)
		{
			EnsureValueIsInitialized();
			if (_offset >= Capacity)
			{
				ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotEnough, 1, Capacity - _offset);
			}
			fixed (char* ptr = _value)
			{
				ptr[_offset++] = c;
			}
		}

		public override string? ToString()
		{
			if (Capacity != _offset)
			{
				ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotUsedEntirely, Capacity, _offset);
			}
			return _value;
		}

		private void EnsureValueIsInitialized()
		{
			if (_value == null)
			{
				_value = new string('\0', _capacity);
			}
		}

		private void ThrowValidationError(string value, int offset, int count)
		{
			if (value == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
			}
			if (offset < 0 || value.Length - offset < count)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset);
			}
			if (Capacity - _offset < count)
			{
				ThrowHelper.ThrowInvalidOperationException(ExceptionResource.Capacity_NotEnough, value.Length, Capacity - _offset);
			}
		}
	}
	[DebuggerDisplay("{Value}")]
	public readonly struct StringSegment : IEquatable<StringSegment>, IEquatable<string?>
	{
		public static readonly StringSegment Empty = string.Empty;

		public string? Buffer { get; }

		public int Offset { get; }

		public int Length { get; }

		public string? Value
		{
			get
			{
				if (!HasValue)
				{
					return null;
				}
				return Buffer.Substring(Offset, Length);
			}
		}

		[MemberNotNullWhen(true, "Buffer")]
		[MemberNotNullWhen(true, "Value")]
		public bool HasValue
		{
			[MemberNotNullWhen(true, "Buffer")]
			[MemberNotNullWhen(true, "Value")]
			get
			{
				return Buffer != null;
			}
		}

		public char this[int index]
		{
			get
			{
				if ((uint)index >= (uint)Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
				}
				return Buffer[Offset + index];
			}
		}

		public StringSegment(string? buffer)
		{
			Buffer = buffer;
			Offset = 0;
			Length = buffer?.Length ?? 0;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public StringSegment(string buffer, int offset, int length)
		{
			if (buffer == null || (uint)offset > (uint)buffer.Length || (uint)length > (uint)(buffer.Length - offset))
			{
				ThrowInvalidArguments(buffer, offset, length);
			}
			Buffer = buffer;
			Offset = offset;
			Length = length;
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return Buffer.AsSpan(Offset, Length);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			if (!HasValue || start < 0)
			{
				ThrowInvalidArguments(start, Length - start, ExceptionArgument.start);
			}
			return Buffer.AsSpan(Offset + start, Length - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			if (!HasValue || start < 0 || length < 0 || (uint)(start + length) > (uint)Length)
			{
				ThrowInvalidArguments(start, length, ExceptionArgument.start);
			}
			return Buffer.AsSpan(Offset + start, length);
		}

		public ReadOnlyMemory<char> AsMemory()
		{
			return Buffer.AsMemory(Offset, Length);
		}

		public static int Compare(StringSegment a, StringSegment b, StringComparison comparisonType)
		{
			if (a.HasValue && b.HasValue)
			{
				return a.AsSpan().CompareTo(b.AsSpan(), comparisonType);
			}
			CheckStringComparison(comparisonType);
			if (a.HasValue)
			{
				return 1;
			}
			if (!b.HasValue)
			{
				return 0;
			}
			return -1;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is StringSegment other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(StringSegment other)
		{
			return Equals(other, StringComparison.Ordinal);
		}

		public bool Equals(StringSegment other, StringComparison comparisonType)
		{
			if (HasValue && other.HasValue)
			{
				return MemoryExtensions.Equals(AsSpan(), other.AsSpan(), comparisonType);
			}
			CheckStringComparison(comparisonType);
			if (!HasValue)
			{
				return !other.HasValue;
			}
			return false;
		}

		public static bool Equals(StringSegment a, StringSegment b, StringComparison comparisonType)
		{
			return a.Equals(b, comparisonType);
		}

		public bool Equals(string? text)
		{
			return Equals(text, StringComparison.Ordinal);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool Equals(string? text, StringComparison comparisonType)
		{
			if (!HasValue || text == null)
			{
				CheckStringComparison(comparisonType);
				return text == Buffer;
			}
			return MemoryExtensions.Equals(AsSpan(), text.AsSpan(), comparisonType);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override int GetHashCode()
		{
			return Value?.GetHashCode() ?? 0;
		}

		public static bool operator ==(StringSegment left, StringSegment right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(StringSegment left, StringSegment right)
		{
			return !left.Equals(right);
		}

		public static implicit operator StringSegment(string? value)
		{
			return new StringSegment(value);
		}

		public static implicit operator ReadOnlySpan<char>(StringSegment segment)
		{
			return segment.AsSpan();
		}

		public static implicit operator ReadOnlyMemory<char>(StringSegment segment)
		{
			return segment.AsMemory();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool StartsWith(string text, StringComparison comparisonType)
		{
			if (text == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
			}
			if (!HasValue)
			{
				CheckStringComparison(comparisonType);
				return false;
			}
			return AsSpan().StartsWith(text.AsSpan(), comparisonType);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool EndsWith(string text, StringComparison comparisonType)
		{
			if (text == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.text);
			}
			if (!HasValue)
			{
				CheckStringComparison(comparisonType);
				return false;
			}
			return AsSpan().EndsWith(text.AsSpan(), comparisonType);
		}

		public string Substring(int offset)
		{
			return Substring(offset, Length - offset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public string Substring(int offset, int length)
		{
			if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length)
			{
				ThrowInvalidArguments(offset, length, ExceptionArgument.offset);
			}
			return Buffer.Substring(Offset + offset, length);
		}

		public StringSegment Subsegment(int offset)
		{
			return Subsegment(offset, Length - offset);
		}

		public StringSegment Subsegment(int offset, int length)
		{
			if (!HasValue || offset < 0 || length < 0 || (uint)(offset + length) > (uint)Length)
			{
				ThrowInvalidArguments(offset, length, ExceptionArgument.offset);
			}
			return new StringSegment(Buffer, Offset + offset, length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public int IndexOf(char c, int start, int count)
		{
			int num = -1;
			if (HasValue)
			{
				if ((uint)start > (uint)Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
				}
				if ((uint)count > (uint)(Length - start))
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count);
				}
				num = AsSpan(start, count).IndexOf(c);
				if (num >= 0)
				{
					num += start;
				}
			}
			return num;
		}

		public int IndexOf(char c, int start)
		{
			return IndexOf(c, start, Length - start);
		}

		public int IndexOf(char c)
		{
			return IndexOf(c, 0, Length);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public int IndexOfAny(char[] anyOf, int startIndex, int count)
		{
			int num = -1;
			if (HasValue)
			{
				if ((uint)startIndex > (uint)Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
				}
				if ((uint)count > (uint)(Length - startIndex))
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count);
				}
				num = Buffer.IndexOfAny(anyOf, Offset + startIndex, count);
				if (num != -1)
				{
					num -= Offset;
				}
			}
			return num;
		}

		public int IndexOfAny(char[] anyOf, int startIndex)
		{
			return IndexOfAny(anyOf, startIndex, Length - startIndex);
		}

		public int IndexOfAny(char[] anyOf)
		{
			return IndexOfAny(anyOf, 0, Length);
		}

		public int LastIndexOf(char value)
		{
			return AsSpan().LastIndexOf(value);
		}

		public StringSegment Trim()
		{
			return TrimStart().TrimEnd();
		}

		public StringSegment TrimStart()
		{
			ReadOnlySpan<char> readOnlySpan = AsSpan();
			int i;
			for (i = 0; i < readOnlySpan.Length && char.IsWhiteSpace(readOnlySpan[i]); i++)
			{
			}
			return Subsegment(i);
		}

		public StringSegment TrimEnd()
		{
			ReadOnlySpan<char> readOnlySpan = AsSpan();
			int num = readOnlySpan.Length - 1;
			while (num >= 0 && char.IsWhiteSpace(readOnlySpan[num]))
			{
				num--;
			}
			return Subsegment(0, num + 1);
		}

		public StringTokenizer Split(char[] chars)
		{
			return new StringTokenizer(this, chars);
		}

		public static bool IsNullOrEmpty(StringSegment value)
		{
			bool result = false;
			if (!value.HasValue || value.Length == 0)
			{
				result = true;
			}
			return result;
		}

		public override string ToString()
		{
			return Value ?? string.Empty;
		}

		private static void CheckStringComparison(StringComparison comparisonType)
		{
			if ((uint)comparisonType > 5u)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.comparisonType);
			}
		}

		[DoesNotReturn]
		private static void ThrowInvalidArguments(string buffer, int offset, int length)
		{
			throw GetInvalidArgumentsException();
			Exception GetInvalidArgumentsException()
			{
				if (buffer == null)
				{
					return ThrowHelper.GetArgumentNullException(ExceptionArgument.buffer);
				}
				if (offset < 0)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.offset);
				}
				if (length < 0)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length);
				}
				return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLength);
			}
		}

		[DoesNotReturn]
		private void ThrowInvalidArguments(int offset, int length, ExceptionArgument offsetOrStart)
		{
			throw GetInvalidArgumentsException(HasValue);
			Exception GetInvalidArgumentsException(bool hasValue)
			{
				if (!hasValue)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart);
				}
				if (offset < 0)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(offsetOrStart);
				}
				if (length < 0)
				{
					return ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.length);
				}
				return ThrowHelper.GetArgumentException(ExceptionResource.Argument_InvalidOffsetLengthStringSegment);
			}
		}
	}
	public class StringSegmentComparer : IComparer<StringSegment>, IEqualityComparer<StringSegment>
	{
		public static StringSegmentComparer Ordinal { get; } = new StringSegmentComparer(StringComparison.Ordinal, StringComparer.Ordinal);


		public static StringSegmentComparer OrdinalIgnoreCase { get; } = new StringSegmentComparer(StringComparison.OrdinalIgnoreCase, StringComparer.OrdinalIgnoreCase);


		private StringComparison Comparison { get; }

		private StringComparer Comparer { get; }

		private StringSegmentComparer(StringComparison comparison, StringComparer comparer)
		{
			Comparison = comparison;
			Comparer = comparer;
		}

		public int Compare(StringSegment x, StringSegment y)
		{
			return StringSegment.Compare(x, y, Comparison);
		}

		public bool Equals(StringSegment x, StringSegment y)
		{
			return StringSegment.Equals(x, y, Comparison);
		}

		public int GetHashCode(StringSegment obj)
		{
			if (!obj.HasValue)
			{
				return 0;
			}
			return Comparer.GetHashCode(obj.Value);
		}
	}
	public readonly struct StringTokenizer : IEnumerable<StringSegment>, IEnumerable
	{
		public struct Enumerator : IEnumerator<StringSegment>, IEnumerator, IDisposable
		{
			private readonly StringSegment _value;

			private readonly char[] _separators;

			private int _index;

			public StringSegment Current { get; private set; }

			object IEnumerator.Current => Current;

			internal Enumerator(in StringSegment value, char[] separators)
			{
				_value = value;
				_separators = separators;
				Current = default(StringSegment);
				_index = 0;
			}

			public Enumerator(ref StringTokenizer tokenizer)
			{
				_value = tokenizer._value;
				_separators = tokenizer._separators;
				Current = default(StringSegment);
				_index = 0;
			}

			public void Dispose()
			{
			}

			public bool MoveNext()
			{
				if (!_value.HasValue || _index > _value.Length)
				{
					Current = default(StringSegment);
					return false;
				}
				int num = _value.IndexOfAny(_separators, _index);
				if (num == -1)
				{
					num = _value.Length;
				}
				Current = _value.Subsegment(_index, num - _index);
				_index = num + 1;
				return true;
			}

			public void Reset()
			{
				Current = default(StringSegment);
				_index = 0;
			}
		}

		private readonly StringSegment _value;

		private readonly char[] _separators;

		public StringTokenizer(string value, char[] separators)
		{
			if (value == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
			}
			if (separators == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators);
			}
			_value = value;
			_separators = separators;
		}

		public StringTokenizer(StringSegment value, char[] separators)
		{
			if (!value.HasValue)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.value);
			}
			if (separators == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.separators);
			}
			_value = value;
			_separators = separators;
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(in _value, _separators);
		}

		IEnumerator<StringSegment> IEnumerable<StringSegment>.GetEnumerator()
		{
			return GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	[DebuggerDisplay("{ToString()}")]
	[DebuggerTypeProxy(typeof(StringValuesDebugView))]
	public readonly struct StringValues : IList<string?>, ICollection<string?>, IEnumerable<string?>, IEnumerable, IReadOnlyList<string?>, IReadOnlyCollection<string?>, IEquatable<StringValues>, IEquatable<string?>, IEquatable<string?[]?>
	{
		public struct Enumerator : IEnumerator<string?>, IEnumerator, IDisposable
		{
			private readonly string[] _values;

			private int _index;

			private string _current;

			public string? Current => _current;

			object? IEnumerator.Current => _current;

			internal Enumerator(object value)
			{
				if (value is string current)
				{
					_values = null;
					_current = current;
				}
				else
				{
					_current = null;
					_values = Unsafe.As<string[]>(value);
				}
				_index = 0;
			}

			public Enumerator(ref StringValues values)
				: this(values._values)
			{
			}

			public bool MoveNext()
			{
				int index = _index;
				if (index < 0)
				{
					return false;
				}
				string[] values = _values;
				if (values != null)
				{
					if ((uint)index < (uint)values.Length)
					{
						_index = index + 1;
						_current = values[index];
						return true;
					}
					_index = -1;
					return false;
				}
				_index = -1;
				return _current != null;
			}

			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			public void Dispose()
			{
			}
		}

		private sealed class StringValuesDebugView
		{
			[CompilerGenerated]
			private StringValues <values>P;

			[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
			public string[] Items => <values>P.ToArray();

			public StringValuesDebugView(StringValues values)
			{
				<values>P = values;
				base..ctor();
			}
		}

		public static readonly StringValues Empty = new StringValues(Array.Empty<string>());

		private readonly object _values;

		public int Count
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object values = _values;
				if (values == null)
				{
					return 0;
				}
				if (values is string)
				{
					return 1;
				}
				return Unsafe.As<string[]>(values).Length;
			}
		}

		bool ICollection<string>.IsReadOnly => true;

		string? IList<string>.this[int index]
		{
			get
			{
				return this[index];
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public string? this[int index]
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				object values = _values;
				if (values is string result)
				{
					if (index == 0)
					{
						return result;
					}
				}
				else if (values != null)
				{
					return Unsafe.As<string[]>(values)[index];
				}
				return OutOfBounds();
			}
		}

		public StringValues(string? value)
		{
			_values = value;
		}

		public StringValues(string?[]? values)
		{
			_values = values;
		}

		public static implicit operator StringValues(string? value)
		{
			return new StringValues(value);
		}

		public static implicit operator StringValues(string?[]? values)
		{
			return new StringValues(values);
		}

		public static implicit operator string?(StringValues values)
		{
			return values.GetStringValue();
		}

		public static implicit operator string?[]?(StringValues value)
		{
			return value.GetArrayValue();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static string OutOfBounds()
		{
			return Array.Empty<string>()[0];
		}

		public override string ToString()
		{
			return GetStringValue() ?? string.Empty;
		}

		private string GetStringValue()
		{
			object values2 = _values;
			if (values2 is string result)
			{
				return result;
			}
			return GetStringValueFromArray(values2);
			static string GetJoinedStringValueFromArray(string[] values)
			{
				int num = 0;
				foreach (string text in values)
				{
					if (text != null && text.Length > 0)
					{
						if (num > 0)
						{
							num++;
						}
						num += text.Length;
					}
				}
				System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(num);
				bool flag = false;
				foreach (string text2 in values)
				{
					if (text2 != null && text2.Length > 0)
					{
						if (flag)
						{
							valueStringBuilder.Append(',');
						}
						valueStringBuilder.Append(text2);
						flag = true;
					}
				}
				return valueStringBuilder.ToString();
			}
			static string GetStringValueFromArray(object value)
			{
				if (value == null)
				{
					return null;
				}
				string[] array = Unsafe.As<string[]>(value);
				return array.Length switch
				{
					0 => null, 
					1 => array[0], 
					_ => GetJoinedStringValueFromArray(array), 
				};
			}
		}

		public string?[] ToArray()
		{
			return GetArrayValue() ?? Array.Empty<string>();
		}

		private string[] GetArrayValue()
		{
			object values = _values;
			if (values is string[] result)
			{
				return result;
			}
			if (values != null)
			{
				return new string[1] { Unsafe.As<string>(values) };
			}
			return null;
		}

		int IList<string>.IndexOf(string item)
		{
			return IndexOf(item);
		}

		private int IndexOf(string item)
		{
			object values = _values;
			if (values is string[] array)
			{
				for (int i = 0; i < array.Length; i++)
				{
					if (string.Equals(array[i], item, StringComparison.Ordinal))
					{
						return i;
					}
				}
				return -1;
			}
			if (values != null)
			{
				if (!string.Equals(Unsafe.As<string>(values), item, StringComparison.Ordinal))
				{
					return -1;
				}
				return 0;
			}
			return -1;
		}

		bool ICollection<string>.Contains(string item)
		{
			return IndexOf(item) >= 0;
		}

		void ICollection<string>.CopyTo(string[] array, int arrayIndex)
		{
			CopyTo(array, arrayIndex);
		}

		private void CopyTo(string[] array, int arrayIndex)
		{
			object values = _values;
			if (values is string[] array2)
			{
				Array.Copy(array2, 0, array, arrayIndex, array2.Length);
			}
			else if (values != null)
			{
				if (array == null)
				{
					ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
				}
				if (arrayIndex < 0)
				{
					throw new ArgumentOutOfRangeException("arrayIndex");
				}
				if (array.Length - arrayIndex < 1)
				{
					throw new ArgumentException("'array' is not long enough to copy all the items in the collection. Check 'arrayIndex' and 'array' length.");
				}
				array[arrayIndex] = Unsafe.As<string>(values);
			}
		}

		void ICollection<string>.Add(string item)
		{
			throw new NotSupportedException();
		}

		void IList<string>.Insert(int index, string item)
		{
			throw new NotSupportedException();
		}

		bool ICollection<string>.Remove(string item)
		{
			throw new NotSupportedException();
		}

		void IList<string>.RemoveAt(int index)
		{
			throw new NotSupportedException();
		}

		void ICollection<string>.Clear()
		{
			throw new NotSupportedException();
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(_values);
		}

		IEnumerator<string> IEnumerable<string>.GetEnumerator()
		{
			return GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public static bool IsNullOrEmpty(StringValues value)
		{
			object values = value._values;
			if (values == null)
			{
				return true;
			}
			if (values is string[] array)
			{
				return array.Length switch
				{
					0 => true, 
					1 => string.IsNullOrEmpty(array[0]), 
					_ => false, 
				};
			}
			return string.IsNullOrEmpty(Unsafe.As<string>(values));
		}

		public static StringValues Concat(StringValues values1, StringValues values2)
		{
			int count = values1.Count;
			int count2 = values2.Count;
			if (count == 0)
			{
				return values2;
			}
			if (count2 == 0)
			{
				return values1;
			}
			string[] array = new string[count + count2];
			values1.CopyTo(array, 0);
			values2.CopyTo(array, count);
			return new StringValues(array);
		}

		public static StringValues Concat(in StringValues values, string? value)
		{
			if (value == null)
			{
				return values;
			}
			int count = values.Count;
			if (count == 0)
			{
				return new StringValues(value);
			}
			string[] array = new string[count + 1];
			values.CopyTo(array, 0);
			array[count] = value;
			return new StringValues(array);
		}

		public static StringValues Concat(string? value, in StringValues values)
		{
			if (value == null)
			{
				return values;
			}
			int count = values.Count;
			if (count == 0)
			{
				return new StringValues(value);
			}
			string[] array = new string[count + 1];
			array[0] = value;
			values.CopyTo(array, 1);
			return new StringValues(array);
		}

		public static bool Equals(StringValues left, StringValues right)
		{
			int count = left.Count;
			if (count != right.Count)
			{
				return false;
			}
			for (int i = 0; i < count; i++)
			{
				if (left[i] != right[i])
				{
					return false;
				}
			}
			return true;
		}

		public static bool operator ==(StringValues left, StringValues right)
		{
			return Equals(left, right);
		}

		public static bool operator !=(StringValues left, StringValues right)
		{
			return !Equals(left, right);
		}

		public bool Equals(StringValues other)
		{
			return Equals(this, other);
		}

		public static bool Equals(string? left, StringValues right)
		{
			return Equals(new StringValues(left), right);
		}

		public static bool Equals(StringValues left, string? right)
		{
			return Equals(left, new StringValues(right));
		}

		public bool Equals(string? other)
		{
			return Equals(this, new StringValues(other));
		}

		public static bool Equals(string?[]? left, StringValues right)
		{
			return Equals(new StringValues(left), right);
		}

		public static bool Equals(StringValues left, string?[]? right)
		{
			return Equals(left, new StringValues(right));
		}

		public bool Equals(string?[]? other)
		{
			return Equals(this, new StringValues(other));
		}

		public static bool operator ==(StringValues left, string? right)
		{
			return Equals(left, new StringValues(right));
		}

		public static bool operator !=(StringValues left, string? right)
		{
			return !Equals(left, new StringValues(right));
		}

		public static bool operator ==(string? left, StringValues right)
		{
			return Equals(new StringValues(left), right);
		}

		public static bool operator !=(string? left, StringValues right)
		{
			return !Equals(new StringValues(left), right);
		}

		public static bool operator ==(StringValues left, string?[]? right)
		{
			return Equals(left, new StringValues(right));
		}

		public static bool operator !=(StringValues left, string?[]? right)
		{
			return !Equals(left, new StringValues(right));
		}

		public static bool operator ==(string?[]? left, StringValues right)
		{
			return Equals(new StringValues(left), right);
		}

		public static bool operator !=(string?[]? left, StringValues right)
		{
			return !Equals(new StringValues(left), right);
		}

		public static bool operator ==(StringValues left, object? right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(StringValues left, object? right)
		{
			return !left.Equals(right);
		}

		public static bool operator ==(object? left, StringValues right)
		{
			return right.Equals(left);
		}

		public static bool operator !=(object? left, StringValues right)
		{
			return !right.Equals(left);
		}

		public override bool Equals(object? obj)
		{
			if (obj == null)
			{
				return Equals(this, Empty);
			}
			if (obj is string right)
			{
				return Equals(this, right);
			}
			if (obj is string[] right2)
			{
				return Equals(this, right2);
			}
			if (obj is StringValues right3)
			{
				return Equals(this, right3);
			}
			return false;
		}

		public override int GetHashCode()
		{
			object values = _values;
			if (values is string[] array)
			{
				if (Count == 1)
				{
					return this[0]?.GetHashCode() ?? Count.GetHashCode();
				}
				int num = 0;
				for (int i = 0; i < array.Length; i++)
				{
					num = HashHelpers.Combine(num, array[i]?.GetHashCode() ?? 0);
				}
				return num;
			}
			return Unsafe.As<string>(values)?.GetHashCode() ?? Count.GetHashCode();
		}
	}
	internal static class ThrowHelper
	{
		[DoesNotReturn]
		internal static void ThrowArgumentNullException(ExceptionArgument argument)
		{
			throw new ArgumentNullException(GetArgumentName(argument));
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument)
		{
			throw new ArgumentOutOfRangeException(GetArgumentName(argument));
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException(ExceptionResource resource)
		{
			throw new ArgumentException(GetResourceText(resource));
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException(ExceptionResource resource)
		{
			throw new InvalidOperationException(GetResourceText(resource));
		}

		[DoesNotReturn]
		internal static void ThrowInvalidOperationException(ExceptionResource resource, params object[] args)
		{
			throw new InvalidOperationException(string.Format(GetResourceText(resource), args));
		}

		internal static ArgumentNullException GetArgumentNullException(ExceptionArgument argument)
		{
			return new ArgumentNullException(GetArgumentName(argument));
		}

		internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument)
		{
			return new ArgumentOutOfRangeException(GetArgumentName(argument));
		}

		internal static ArgumentException GetArgumentException(ExceptionResource resource)
		{
			return new ArgumentException(GetResourceText(resource));
		}

		private static string GetResourceText(ExceptionResource resource)
		{
			return resource switch
			{
				ExceptionResource.Argument_InvalidOffsetLength => System.SR.Argument_InvalidOffsetLength, 
				ExceptionResource.Argument_InvalidOffsetLengthStringSegment => System.SR.Argument_InvalidOffsetLengthStringSegment, 
				ExceptionResource.Capacity_CannotChangeAfterWriteStarted => System.SR.Capacity_CannotChangeAfterWriteStarted, 
				ExceptionResource.Capacity_NotEnough => System.SR.Capacity_NotEnough, 
				ExceptionResource.Capacity_NotUsedEntirely => System.SR.Capacity_NotUsedEntirely, 
				_ => "", 
			};
		}

		private static string GetArgumentName(ExceptionArgument argument)
		{
			return argument.ToString();
		}
	}
	internal enum ExceptionArgument
	{
		buffer,
		offset,
		length,
		text,
		start,
		count,
		index,
		value,
		capacity,
		separators,
		comparisonType,
		changeTokens,
		changeTokenProducer,
		changeTokenConsumer,
		array
	}
	internal enum ExceptionResource
	{
		Argument_InvalidOffsetLength,
		Argument_InvalidOffsetLengthStringSegment,
		Capacity_CannotChangeAfterWriteStarted,
		Capacity_NotEnough,
		Capacity_NotUsedEntirely
	}
}

BepInEx/core/Microsoft.Win32.Registry.dll

Decompiled 2 weeks ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security.AccessControl;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Microsoft.Win32.Registry")]
[assembly: AssemblyDescription("Microsoft.Win32.Registry")]
[assembly: AssemblyDefaultAlias("Microsoft.Win32.Registry")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("4.0.0.0")]
[assembly: AssemblyFileVersion("4.0.0.0")]
[assembly: AssemblyVersion("4.1.0.0")]
[assembly: TypeForwardedTo(typeof(Registry))]
[assembly: TypeForwardedTo(typeof(RegistryHive))]
[assembly: TypeForwardedTo(typeof(RegistryKey))]
[assembly: TypeForwardedTo(typeof(RegistryKeyPermissionCheck))]
[assembly: TypeForwardedTo(typeof(RegistryOptions))]
[assembly: TypeForwardedTo(typeof(RegistryValueKind))]
[assembly: TypeForwardedTo(typeof(RegistryValueOptions))]
[assembly: TypeForwardedTo(typeof(RegistryView))]
[assembly: TypeForwardedTo(typeof(SafeRegistryHandle))]
[assembly: TypeForwardedTo(typeof(RegistryAccessRule))]
[assembly: TypeForwardedTo(typeof(RegistryAuditRule))]
[assembly: TypeForwardedTo(typeof(RegistryRights))]
[assembly: TypeForwardedTo(typeof(RegistrySecurity))]

BepInEx/core/Mono.Posix.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Mono.Unix;
using Mono.Unix.Native;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Mono.Posix.dll")]
[assembly: AssemblyDescription("Unix Integration Classes")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: AssemblyDelaySign(true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal sealed class Locale
{
	private Locale()
	{
	}

	public static string GetText(string msg)
	{
		return msg;
	}

	public static string GetText(string fmt, params object[] args)
	{
		return string.Format(fmt, args);
	}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Delegate)]
internal class MapAttribute : Attribute
{
	private string nativeType;

	private string suppressFlags;

	public string NativeType => nativeType;

	public string SuppressFlags
	{
		get
		{
			return suppressFlags;
		}
		set
		{
			suppressFlags = value;
		}
	}

	public MapAttribute()
	{
	}

	public MapAttribute(string nativeType)
	{
		this.nativeType = nativeType;
	}
}
namespace Mono.Unix
{
	[Serializable]
	public class AbstractUnixEndPoint : EndPoint
	{
		private string path;

		public string Path
		{
			get
			{
				return path;
			}
			set
			{
				path = value;
			}
		}

		public override AddressFamily AddressFamily => AddressFamily.Unix;

		public AbstractUnixEndPoint(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (path == "")
			{
				throw new ArgumentException("Cannot be empty.", "path");
			}
			this.path = path;
		}

		public override EndPoint Create(SocketAddress socketAddress)
		{
			byte[] array = new byte[socketAddress.Size - 2 - 1];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = socketAddress[3 + i];
			}
			return new AbstractUnixEndPoint(Encoding.Default.GetString(array));
		}

		public override SocketAddress Serialize()
		{
			byte[] bytes = Encoding.Default.GetBytes(path);
			SocketAddress socketAddress = new SocketAddress(AddressFamily, 3 + bytes.Length);
			socketAddress[2] = 0;
			for (int i = 0; i < bytes.Length; i++)
			{
				socketAddress[i + 2 + 1] = bytes[i];
			}
			return socketAddress;
		}

		public override string ToString()
		{
			return path;
		}

		public override int GetHashCode()
		{
			return path.GetHashCode();
		}

		public override bool Equals(object o)
		{
			if (!(o is AbstractUnixEndPoint abstractUnixEndPoint))
			{
				return false;
			}
			return abstractUnixEndPoint.path == path;
		}
	}
	public class Catalog
	{
		private Catalog()
		{
		}

		[DllImport("intl", CallingConvention = CallingConvention.Cdecl)]
		private static extern IntPtr bindtextdomain(IntPtr domainname, IntPtr dirname);

		[DllImport("intl", CallingConvention = CallingConvention.Cdecl)]
		private static extern IntPtr bind_textdomain_codeset(IntPtr domainname, IntPtr codeset);

		[DllImport("intl", CallingConvention = CallingConvention.Cdecl)]
		private static extern IntPtr textdomain(IntPtr domainname);

		public static void Init(string package, string localedir)
		{
			MarshalStrings(package, out var p, localedir, out var p2, "UTF-8", out var p3);
			try
			{
				if (bindtextdomain(p, p2) == IntPtr.Zero)
				{
					throw new UnixIOException(Errno.ENOMEM);
				}
				if (bind_textdomain_codeset(p, p3) == IntPtr.Zero)
				{
					throw new UnixIOException(Errno.ENOMEM);
				}
				if (textdomain(p) == IntPtr.Zero)
				{
					throw new UnixIOException(Errno.ENOMEM);
				}
			}
			finally
			{
				UnixMarshal.FreeHeap(p);
				UnixMarshal.FreeHeap(p2);
				UnixMarshal.FreeHeap(p3);
			}
		}

		private static void MarshalStrings(string s1, out IntPtr p1, string s2, out IntPtr p2, string s3, out IntPtr p3)
		{
			p1 = (p2 = (p3 = IntPtr.Zero));
			bool flag = true;
			try
			{
				p1 = UnixMarshal.StringToHeap(s1);
				p2 = UnixMarshal.StringToHeap(s2);
				if (s3 != null)
				{
					p3 = UnixMarshal.StringToHeap(s3);
				}
				flag = false;
			}
			finally
			{
				if (flag)
				{
					UnixMarshal.FreeHeap(p1);
					UnixMarshal.FreeHeap(p2);
					UnixMarshal.FreeHeap(p3);
				}
			}
		}

		[DllImport("intl", CallingConvention = CallingConvention.Cdecl)]
		private static extern IntPtr gettext(IntPtr instring);

		public static string GetString(string s)
		{
			IntPtr intPtr = UnixMarshal.StringToHeap(s);
			try
			{
				IntPtr intPtr2 = gettext(intPtr);
				if (intPtr2 != intPtr)
				{
					return UnixMarshal.PtrToStringUnix(intPtr2);
				}
				return s;
			}
			finally
			{
				UnixMarshal.FreeHeap(intPtr);
			}
		}

		[DllImport("intl", CallingConvention = CallingConvention.Cdecl)]
		private static extern IntPtr ngettext(IntPtr singular, IntPtr plural, int n);

		public static string GetPluralString(string s, string p, int n)
		{
			MarshalStrings(s, out var p2, p, out var p3, null, out var _);
			try
			{
				IntPtr intPtr = ngettext(p2, p3, n);
				if (intPtr == p2)
				{
					return s;
				}
				if (intPtr == p3)
				{
					return p;
				}
				return UnixMarshal.PtrToStringUnix(intPtr);
			}
			finally
			{
				UnixMarshal.FreeHeap(p2);
				UnixMarshal.FreeHeap(p3);
			}
		}
	}
	public enum FileAccessPattern
	{
		Normal = 0,
		Sequential = 2,
		Random = 1,
		NoReuse = 5,
		PreLoad = 3,
		FlushCache = 4
	}
	[Flags]
	public enum FileAccessPermissions
	{
		UserReadWriteExecute = 0x1C0,
		UserRead = 0x100,
		UserWrite = 0x80,
		UserExecute = 0x40,
		GroupReadWriteExecute = 0x38,
		GroupRead = 0x20,
		GroupWrite = 0x10,
		GroupExecute = 8,
		OtherReadWriteExecute = 7,
		OtherRead = 4,
		OtherWrite = 2,
		OtherExecute = 1,
		DefaultPermissions = 0x1B6,
		AllPermissions = 0x1FF
	}
	public sealed class FileHandleOperations
	{
		private FileHandleOperations()
		{
		}

		public static void AdviseFileAccessPattern(int fd, FileAccessPattern pattern, long offset, long len)
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.posix_fadvise(fd, offset, len, (PosixFadviseAdvice)pattern));
		}

		public static void AdviseFileAccessPattern(int fd, FileAccessPattern pattern)
		{
			AdviseFileAccessPattern(fd, pattern, 0L, 0L);
		}

		public static void AdviseFileAccessPattern(FileStream file, FileAccessPattern pattern, long offset, long len)
		{
			if (file == null)
			{
				throw new ArgumentNullException("file");
			}
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.posix_fadvise(file.Handle.ToInt32(), offset, len, (PosixFadviseAdvice)pattern));
		}

		public static void AdviseFileAccessPattern(FileStream file, FileAccessPattern pattern)
		{
			AdviseFileAccessPattern(file, pattern, 0L, 0L);
		}

		public static void AdviseFileAccessPattern(UnixStream stream, FileAccessPattern pattern, long offset, long len)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.posix_fadvise(stream.Handle, offset, len, (PosixFadviseAdvice)pattern));
		}

		public static void AdviseFileAccessPattern(UnixStream stream, FileAccessPattern pattern)
		{
			AdviseFileAccessPattern(stream, pattern, 0L, 0L);
		}
	}
	[Flags]
	public enum FileSpecialAttributes
	{
		SetUserId = 0x800,
		SetGroupId = 0x400,
		Sticky = 0x200
	}
	public enum FileTypes
	{
		Directory = 16384,
		CharacterDevice = 8192,
		BlockDevice = 24576,
		RegularFile = 32768,
		Fifo = 4096,
		SymbolicLink = 40960,
		Socket = 49152
	}
	internal struct PeerCredData
	{
		public int pid;

		public int uid;

		public int gid;
	}
	public class PeerCred
	{
		private const int so_peercred = 10001;

		private PeerCredData data;

		public int ProcessID => data.pid;

		public int UserID => data.uid;

		public int GroupID => data.gid;

		public PeerCred(Socket sock)
		{
			if (sock.AddressFamily != AddressFamily.Unix)
			{
				throw new ArgumentException("Only Unix sockets are supported", "sock");
			}
			data = (PeerCredData)sock.GetSocketOption(SocketOptionLevel.Socket, (SocketOptionName)10001);
		}
	}
	public class StdioFileStream : Stream
	{
		public static readonly IntPtr InvalidFileStream = IntPtr.Zero;

		public static readonly IntPtr StandardInput = Stdlib.stdin;

		public static readonly IntPtr StandardOutput = Stdlib.stdout;

		public static readonly IntPtr StandardError = Stdlib.stderr;

		private bool canSeek;

		private bool canRead;

		private bool canWrite;

		private bool owner = true;

		private IntPtr file = InvalidFileStream;

		public IntPtr Handle
		{
			get
			{
				AssertNotDisposed();
				GC.KeepAlive(this);
				return file;
			}
		}

		public override bool CanRead => canRead;

		public override bool CanSeek => canSeek;

		public override bool CanWrite => canWrite;

		public override long Length
		{
			get
			{
				AssertNotDisposed();
				if (!CanSeek)
				{
					throw new NotSupportedException("File Stream doesn't support seeking");
				}
				long num = Stdlib.ftell(file);
				if (num == -1)
				{
					throw new NotSupportedException("Unable to obtain current file position");
				}
				UnixMarshal.ThrowExceptionForLastErrorIf(Stdlib.fseek(file, 0L, SeekFlags.SEEK_END));
				long num2 = Stdlib.ftell(file);
				if (num2 == -1)
				{
					UnixMarshal.ThrowExceptionForLastError();
				}
				UnixMarshal.ThrowExceptionForLastErrorIf(Stdlib.fseek(file, num, SeekFlags.SEEK_SET));
				GC.KeepAlive(this);
				return num2;
			}
		}

		public override long Position
		{
			get
			{
				AssertNotDisposed();
				if (!CanSeek)
				{
					throw new NotSupportedException("The stream does not support seeking");
				}
				long num = Stdlib.ftell(file);
				if (num == -1)
				{
					UnixMarshal.ThrowExceptionForLastError();
				}
				GC.KeepAlive(this);
				return num;
			}
			set
			{
				AssertNotDisposed();
				Seek(value, SeekOrigin.Begin);
			}
		}

		public StdioFileStream(IntPtr fileStream)
			: this(fileStream, ownsHandle: true)
		{
		}

		public StdioFileStream(IntPtr fileStream, bool ownsHandle)
		{
			InitStream(fileStream, ownsHandle);
		}

		public StdioFileStream(IntPtr fileStream, FileAccess access)
			: this(fileStream, access, ownsHandle: true)
		{
		}

		public StdioFileStream(IntPtr fileStream, FileAccess access, bool ownsHandle)
		{
			InitStream(fileStream, ownsHandle);
			InitCanReadWrite(access);
		}

		public StdioFileStream(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			InitStream(Fopen(path, "rb"), ownsHandle: true);
		}

		public StdioFileStream(string path, string mode)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			InitStream(Fopen(path, mode), ownsHandle: true);
		}

		public StdioFileStream(string path, FileMode mode)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			InitStream(Fopen(path, ToFopenMode(path, mode)), ownsHandle: true);
		}

		public StdioFileStream(string path, FileAccess access)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			InitStream(Fopen(path, ToFopenMode(path, access)), ownsHandle: true);
			InitCanReadWrite(access);
		}

		public StdioFileStream(string path, FileMode mode, FileAccess access)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			InitStream(Fopen(path, ToFopenMode(path, mode, access)), ownsHandle: true);
			InitCanReadWrite(access);
		}

		private static IntPtr Fopen(string path, string mode)
		{
			if (path.Length == 0)
			{
				throw new ArgumentException("path");
			}
			if (mode == null)
			{
				throw new ArgumentNullException("mode");
			}
			IntPtr intPtr = Stdlib.fopen(path, mode);
			if (intPtr == IntPtr.Zero)
			{
				throw new DirectoryNotFoundException("path", UnixMarshal.CreateExceptionForLastError());
			}
			return intPtr;
		}

		private void InitStream(IntPtr fileStream, bool ownsHandle)
		{
			if (InvalidFileStream == fileStream)
			{
				throw new ArgumentException(Locale.GetText("Invalid file stream"), "fileStream");
			}
			file = fileStream;
			owner = ownsHandle;
			try
			{
				if ((long)Stdlib.fseek(file, 0L, SeekFlags.SEEK_CUR) != -1)
				{
					canSeek = true;
				}
				Stdlib.fread(IntPtr.Zero, 0uL, 0uL, file);
				if (Stdlib.ferror(file) == 0)
				{
					canRead = true;
				}
				Stdlib.fwrite(IntPtr.Zero, 0uL, 0uL, file);
				if (Stdlib.ferror(file) == 0)
				{
					canWrite = true;
				}
				Stdlib.clearerr(file);
			}
			catch (Exception)
			{
				throw new ArgumentException(Locale.GetText("Invalid file stream"), "fileStream");
			}
			GC.KeepAlive(this);
		}

		private void InitCanReadWrite(FileAccess access)
		{
			canRead = canRead && (access == FileAccess.Read || access == FileAccess.ReadWrite);
			canWrite = canWrite && (access == FileAccess.Write || access == FileAccess.ReadWrite);
		}

		private static string ToFopenMode(string file, FileMode mode)
		{
			string result = NativeConvert.ToFopenMode(mode);
			AssertFileMode(file, mode);
			return result;
		}

		private static string ToFopenMode(string file, FileAccess access)
		{
			return NativeConvert.ToFopenMode(access);
		}

		private static string ToFopenMode(string file, FileMode mode, FileAccess access)
		{
			string result = NativeConvert.ToFopenMode(mode, access);
			bool flag = AssertFileMode(file, mode);
			if (mode == FileMode.OpenOrCreate && access == FileAccess.Read && !flag)
			{
				result = "w+b";
			}
			return result;
		}

		private static bool AssertFileMode(string file, FileMode mode)
		{
			bool flag = FileExists(file);
			if (mode == FileMode.CreateNew && flag)
			{
				throw new IOException("File exists and FileMode.CreateNew specified");
			}
			if ((mode == FileMode.Open || mode == FileMode.Truncate) && !flag)
			{
				throw new FileNotFoundException("File doesn't exist and FileMode.Open specified", file);
			}
			return flag;
		}

		private static bool FileExists(string file)
		{
			IntPtr intPtr = Stdlib.fopen(file, "r");
			bool result = intPtr != IntPtr.Zero;
			if (intPtr != IntPtr.Zero)
			{
				Stdlib.fclose(intPtr);
			}
			return result;
		}

		private void AssertNotDisposed()
		{
			if (file == InvalidFileStream)
			{
				throw new ObjectDisposedException("Invalid File Stream");
			}
			GC.KeepAlive(this);
		}

		public void SaveFilePosition(FilePosition pos)
		{
			AssertNotDisposed();
			UnixMarshal.ThrowExceptionForLastErrorIf(Stdlib.fgetpos(file, pos));
			GC.KeepAlive(this);
		}

		public void RestoreFilePosition(FilePosition pos)
		{
			AssertNotDisposed();
			if (pos == null)
			{
				throw new ArgumentNullException("value");
			}
			UnixMarshal.ThrowExceptionForLastErrorIf(Stdlib.fsetpos(file, pos));
			GC.KeepAlive(this);
		}

		public override void Flush()
		{
			AssertNotDisposed();
			if (Stdlib.fflush(file) != 0)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			GC.KeepAlive(this);
		}

		public unsafe override int Read([In][Out] byte[] buffer, int offset, int count)
		{
			AssertNotDisposed();
			AssertValidBuffer(buffer, offset, count);
			if (!CanRead)
			{
				throw new NotSupportedException("Stream does not support reading");
			}
			ulong num;
			fixed (byte* ptr = &buffer[offset])
			{
				num = Stdlib.fread(ptr, 1uL, (ulong)count, file);
			}
			if (num != (ulong)count && Stdlib.ferror(file) != 0)
			{
				throw new IOException();
			}
			GC.KeepAlive(this);
			return (int)num;
		}

		private void AssertValidBuffer(byte[] buffer, int offset, int count)
		{
			if (buffer == null)
			{
				throw new ArgumentNullException("buffer");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", "< 0");
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count", "< 0");
			}
			if (offset > buffer.Length)
			{
				throw new ArgumentException("destination offset is beyond array size");
			}
			if (offset > buffer.Length - count)
			{
				throw new ArgumentException("would overrun buffer");
			}
		}

		public void Rewind()
		{
			AssertNotDisposed();
			Stdlib.rewind(file);
			GC.KeepAlive(this);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			AssertNotDisposed();
			if (!CanSeek)
			{
				throw new NotSupportedException("The File Stream does not support seeking");
			}
			SeekFlags seekFlags = SeekFlags.SEEK_CUR;
			if (Stdlib.fseek(origin: origin switch
			{
				SeekOrigin.Begin => SeekFlags.SEEK_SET, 
				SeekOrigin.Current => SeekFlags.SEEK_CUR, 
				SeekOrigin.End => SeekFlags.SEEK_END, 
				_ => throw new ArgumentException("origin"), 
			}, stream: file, offset: offset) != 0)
			{
				throw new IOException("Unable to seek", UnixMarshal.CreateExceptionForLastError());
			}
			long num = Stdlib.ftell(file);
			if (num == -1)
			{
				throw new IOException("Unable to get current file position", UnixMarshal.CreateExceptionForLastError());
			}
			GC.KeepAlive(this);
			return num;
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException("ANSI C doesn't provide a way to truncate a file");
		}

		public unsafe override void Write(byte[] buffer, int offset, int count)
		{
			AssertNotDisposed();
			AssertValidBuffer(buffer, offset, count);
			if (!CanWrite)
			{
				throw new NotSupportedException("File Stream does not support writing");
			}
			ulong num;
			fixed (byte* ptr = &buffer[offset])
			{
				num = Stdlib.fwrite(ptr, 1uL, (ulong)count, file);
			}
			if (num != (ulong)count)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			GC.KeepAlive(this);
		}

		~StdioFileStream()
		{
			Close();
		}

		public override void Close()
		{
			if (file == InvalidFileStream)
			{
				return;
			}
			if (owner)
			{
				if (Stdlib.fclose(file) != 0)
				{
					UnixMarshal.ThrowExceptionForLastError();
				}
			}
			else
			{
				Flush();
			}
			file = InvalidFileStream;
			canRead = false;
			canSeek = false;
			canWrite = false;
			GC.SuppressFinalize(this);
			GC.KeepAlive(this);
		}
	}
	public class UnixClient : MarshalByRefObject, IDisposable
	{
		private NetworkStream stream;

		private Socket client;

		private bool disposed;

		public Socket Client
		{
			get
			{
				return client;
			}
			set
			{
				client = value;
				stream = null;
			}
		}

		public PeerCred PeerCredential
		{
			get
			{
				CheckDisposed();
				return new PeerCred(client);
			}
		}

		public LingerOption LingerState
		{
			get
			{
				CheckDisposed();
				return (LingerOption)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger);
			}
			set
			{
				CheckDisposed();
				client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value);
			}
		}

		public int ReceiveBufferSize
		{
			get
			{
				CheckDisposed();
				return (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
			}
			set
			{
				CheckDisposed();
				client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
			}
		}

		public int ReceiveTimeout
		{
			get
			{
				CheckDisposed();
				return (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
			}
			set
			{
				CheckDisposed();
				client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value);
			}
		}

		public int SendBufferSize
		{
			get
			{
				CheckDisposed();
				return (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
			}
			set
			{
				CheckDisposed();
				client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value);
			}
		}

		public int SendTimeout
		{
			get
			{
				CheckDisposed();
				return (int)client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
			}
			set
			{
				CheckDisposed();
				client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
			}
		}

		public UnixClient()
		{
			if (client != null)
			{
				client.Close();
				client = null;
			}
			client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
		}

		public UnixClient(string path)
			: this()
		{
			if (path == null)
			{
				throw new ArgumentNullException("ep");
			}
			Connect(path);
		}

		public UnixClient(UnixEndPoint ep)
			: this()
		{
			if (ep == null)
			{
				throw new ArgumentNullException("ep");
			}
			Connect(ep);
		}

		internal UnixClient(Socket sock)
		{
			Client = sock;
		}

		public void Close()
		{
			CheckDisposed();
			Dispose();
		}

		public void Connect(UnixEndPoint remoteEndPoint)
		{
			CheckDisposed();
			client.Connect(remoteEndPoint);
			stream = new NetworkStream(client, ownsSocket: true);
		}

		public void Connect(string path)
		{
			CheckDisposed();
			Connect(new UnixEndPoint(path));
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposed)
			{
				return;
			}
			if (disposing)
			{
				NetworkStream networkStream = stream;
				stream = null;
				if (networkStream != null)
				{
					networkStream.Close();
					networkStream = null;
				}
				else if (client != null)
				{
					client.Close();
				}
				client = null;
			}
			disposed = true;
		}

		public NetworkStream GetStream()
		{
			CheckDisposed();
			if (stream == null)
			{
				stream = new NetworkStream(client, ownsSocket: true);
			}
			return stream;
		}

		private void CheckDisposed()
		{
			if (disposed)
			{
				throw new ObjectDisposedException(GetType().FullName);
			}
		}

		~UnixClient()
		{
			Dispose(disposing: false);
		}
	}
	public sealed class UnixDirectoryInfo : UnixFileSystemInfo
	{
		public override string Name
		{
			get
			{
				string fileName = UnixPath.GetFileName(base.FullPath);
				if (fileName == null || fileName.Length == 0)
				{
					return base.FullPath;
				}
				return fileName;
			}
		}

		public UnixDirectoryInfo Parent
		{
			get
			{
				if (base.FullPath == "/")
				{
					return this;
				}
				string directoryName = UnixPath.GetDirectoryName(base.FullPath);
				if (directoryName == "")
				{
					throw new InvalidOperationException("Do not know parent directory for path `" + base.FullPath + "'");
				}
				return new UnixDirectoryInfo(directoryName);
			}
		}

		public UnixDirectoryInfo Root
		{
			get
			{
				string pathRoot = UnixPath.GetPathRoot(base.FullPath);
				if (pathRoot == null)
				{
					return null;
				}
				return new UnixDirectoryInfo(pathRoot);
			}
		}

		public UnixDirectoryInfo(string path)
			: base(path)
		{
		}

		internal UnixDirectoryInfo(string path, Stat stat)
			: base(path, stat)
		{
		}

		[CLSCompliant(false)]
		public void Create(FilePermissions mode)
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.mkdir(base.FullPath, mode));
			Refresh();
		}

		public void Create(FileAccessPermissions mode)
		{
			Create((FilePermissions)mode);
		}

		public void Create()
		{
			FilePermissions mode = FilePermissions.ACCESSPERMS;
			Create(mode);
		}

		public override void Delete()
		{
			Delete(recursive: false);
		}

		public void Delete(bool recursive)
		{
			if (recursive)
			{
				UnixFileSystemInfo[] fileSystemEntries = GetFileSystemEntries();
				foreach (UnixFileSystemInfo unixFileSystemInfo in fileSystemEntries)
				{
					if (unixFileSystemInfo is UnixDirectoryInfo unixDirectoryInfo)
					{
						unixDirectoryInfo.Delete(recursive: true);
					}
					else
					{
						unixFileSystemInfo.Delete();
					}
				}
			}
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.rmdir(base.FullPath));
			Refresh();
		}

		public Dirent[] GetEntries()
		{
			IntPtr intPtr = Syscall.opendir(base.FullPath);
			if (intPtr == IntPtr.Zero)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			bool flag = false;
			try
			{
				Dirent[] entries = GetEntries(intPtr);
				flag = true;
				return entries;
			}
			finally
			{
				int retval = Syscall.closedir(intPtr);
				if (flag)
				{
					UnixMarshal.ThrowExceptionForLastErrorIf(retval);
				}
			}
		}

		private static Dirent[] GetEntries(IntPtr dirp)
		{
			ArrayList arrayList = new ArrayList();
			int num;
			IntPtr result;
			do
			{
				Dirent dirent = new Dirent();
				num = Syscall.readdir_r(dirp, dirent, out result);
				if (num == 0 && result != IntPtr.Zero && dirent.d_name != "." && dirent.d_name != "..")
				{
					arrayList.Add(dirent);
				}
			}
			while (num == 0 && result != IntPtr.Zero);
			if (num != 0)
			{
				UnixMarshal.ThrowExceptionForLastErrorIf(num);
			}
			return (Dirent[])arrayList.ToArray(typeof(Dirent));
		}

		public Dirent[] GetEntries(Regex regex)
		{
			IntPtr intPtr = Syscall.opendir(base.FullPath);
			if (intPtr == IntPtr.Zero)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			try
			{
				return GetEntries(intPtr, regex);
			}
			finally
			{
				UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.closedir(intPtr));
			}
		}

		private static Dirent[] GetEntries(IntPtr dirp, Regex regex)
		{
			ArrayList arrayList = new ArrayList();
			int num;
			IntPtr result;
			do
			{
				Dirent dirent = new Dirent();
				num = Syscall.readdir_r(dirp, dirent, out result);
				if (num == 0 && result != IntPtr.Zero && regex.Match(dirent.d_name).Success && dirent.d_name != "." && dirent.d_name != "..")
				{
					arrayList.Add(dirent);
				}
			}
			while (num == 0 && result != IntPtr.Zero);
			if (num != 0)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return (Dirent[])arrayList.ToArray(typeof(Dirent));
		}

		public Dirent[] GetEntries(string regex)
		{
			Regex regex2 = new Regex(regex);
			return GetEntries(regex2);
		}

		public UnixFileSystemInfo[] GetFileSystemEntries()
		{
			Dirent[] entries = GetEntries();
			return GetFileSystemEntries(entries);
		}

		private UnixFileSystemInfo[] GetFileSystemEntries(Dirent[] dentries)
		{
			UnixFileSystemInfo[] array = new UnixFileSystemInfo[dentries.Length];
			for (int i = 0; i != array.Length; i++)
			{
				array[i] = UnixFileSystemInfo.GetFileSystemEntry(UnixPath.Combine(base.FullPath, dentries[i].d_name));
			}
			return array;
		}

		public UnixFileSystemInfo[] GetFileSystemEntries(Regex regex)
		{
			Dirent[] entries = GetEntries(regex);
			return GetFileSystemEntries(entries);
		}

		public UnixFileSystemInfo[] GetFileSystemEntries(string regex)
		{
			Regex regex2 = new Regex(regex);
			return GetFileSystemEntries(regex2);
		}

		public static string GetCurrentDirectory()
		{
			StringBuilder stringBuilder = new StringBuilder(16);
			IntPtr zero = IntPtr.Zero;
			do
			{
				stringBuilder.Capacity *= 2;
				zero = Syscall.getcwd(stringBuilder, (ulong)stringBuilder.Capacity);
			}
			while (zero == IntPtr.Zero && Stdlib.GetLastError() == Errno.ERANGE);
			if (zero == IntPtr.Zero)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return stringBuilder.ToString();
		}

		public static void SetCurrentDirectory(string path)
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.chdir(path));
		}
	}
	public enum UnixDriveType
	{
		Unknown,
		NoRootDirectory,
		Removable,
		Fixed,
		Network,
		CDRom,
		Ram
	}
	public sealed class UnixDriveInfo
	{
		private Statvfs stat;

		private string fstype;

		private string mount_point;

		private string block_device;

		public long AvailableFreeSpace
		{
			get
			{
				Refresh();
				return Convert.ToInt64(stat.f_bavail * stat.f_frsize);
			}
		}

		public string DriveFormat => fstype;

		public UnixDriveType DriveType => UnixDriveType.Unknown;

		public bool IsReady
		{
			get
			{
				bool flag = Refresh(throwException: false);
				if (mount_point == "/" || !flag)
				{
					return flag;
				}
				if (Syscall.statvfs(RootDirectory.Parent.FullName, out var buf) != 0)
				{
					return false;
				}
				return buf.f_fsid != stat.f_fsid;
			}
		}

		public string Name => mount_point;

		public UnixDirectoryInfo RootDirectory => new UnixDirectoryInfo(mount_point);

		public long TotalFreeSpace
		{
			get
			{
				Refresh();
				return (long)(stat.f_bfree * stat.f_frsize);
			}
		}

		public long TotalSize
		{
			get
			{
				Refresh();
				return (long)(stat.f_frsize * stat.f_blocks);
			}
		}

		public string VolumeLabel => block_device;

		public long MaximumFilenameLength
		{
			get
			{
				Refresh();
				return Convert.ToInt64(stat.f_namemax);
			}
		}

		public UnixDriveInfo(string mountPoint)
		{
			if (mountPoint == null)
			{
				throw new ArgumentNullException("mountPoint");
			}
			Fstab fstab = Syscall.getfsfile(mountPoint);
			if (fstab != null)
			{
				FromFstab(fstab);
				return;
			}
			mount_point = mountPoint;
			block_device = "";
			fstype = "Unknown";
		}

		private void FromFstab(Fstab fstab)
		{
			fstype = fstab.fs_vfstype;
			mount_point = fstab.fs_file;
			block_device = fstab.fs_spec;
		}

		public static UnixDriveInfo GetForSpecialFile(string specialFile)
		{
			if (specialFile == null)
			{
				throw new ArgumentNullException("specialFile");
			}
			Fstab fstab = Syscall.getfsspec(specialFile);
			if (fstab == null)
			{
				throw new ArgumentException("specialFile isn't valid: " + specialFile);
			}
			return new UnixDriveInfo(fstab);
		}

		private UnixDriveInfo(Fstab fstab)
		{
			FromFstab(fstab);
		}

		public static UnixDriveInfo[] GetDrives()
		{
			ArrayList arrayList = new ArrayList();
			lock (Syscall.fstab_lock)
			{
				if (Syscall.setfsent() != 1)
				{
					throw new IOException("Error calling setfsent(3)", new UnixIOException());
				}
				try
				{
					Fstab fstab;
					while ((fstab = Syscall.getfsent()) != null)
					{
						if (fstab.fs_file != null && fstab.fs_file.StartsWith("/"))
						{
							arrayList.Add(new UnixDriveInfo(fstab));
						}
					}
				}
				finally
				{
					Syscall.endfsent();
				}
			}
			return (UnixDriveInfo[])arrayList.ToArray(typeof(UnixDriveInfo));
		}

		public override string ToString()
		{
			return VolumeLabel;
		}

		private void Refresh()
		{
			Refresh(throwException: true);
		}

		private bool Refresh(bool throwException)
		{
			int num = Syscall.statvfs(mount_point, out stat);
			if (num == -1 && throwException)
			{
				Errno lastError = Stdlib.GetLastError();
				throw new InvalidOperationException(UnixMarshal.GetErrorDescription(lastError), new UnixIOException(lastError));
			}
			if (num == -1)
			{
				return false;
			}
			return true;
		}
	}
	[Serializable]
	public class UnixEncoding : Encoding
	{
		[Serializable]
		private class UnixDecoder : Decoder
		{
			private uint leftOverBits;

			private uint leftOverCount;

			public UnixDecoder()
			{
				leftOverBits = 0u;
				leftOverCount = 0u;
			}

			public override int GetCharCount(byte[] bytes, int index, int count)
			{
				return InternalGetCharCount(bytes, index, count, leftOverBits, leftOverCount, throwOnInvalid: true, flush: false);
			}

			public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
			{
				return InternalGetChars(bytes, byteIndex, byteCount, chars, charIndex, ref leftOverBits, ref leftOverCount, throwOnInvalid: true, flush: false);
			}
		}

		[Serializable]
		private class UnixEncoder : Encoder
		{
			private uint leftOver;

			public UnixEncoder()
			{
				leftOver = 0u;
			}

			public override int GetByteCount(char[] chars, int index, int count, bool flush)
			{
				return InternalGetByteCount(chars, index, count, leftOver, flush);
			}

			public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteCount, bool flush)
			{
				return InternalGetBytes(chars, charIndex, charCount, bytes, byteCount, ref leftOver, flush);
			}
		}

		public static readonly Encoding Instance = new UnixEncoding();

		public static readonly char EscapeByte = '\0';

		private static int InternalGetByteCount(char[] chars, int index, int count, uint leftOver, bool flush)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (index < 0 || index > chars.Length)
			{
				throw new ArgumentOutOfRangeException("index", _("ArgRange_Array"));
			}
			if (count < 0 || count > chars.Length - index)
			{
				throw new ArgumentOutOfRangeException("count", _("ArgRange_Array"));
			}
			int num = 0;
			uint num2 = leftOver;
			while (count > 0)
			{
				char c = chars[index];
				if (num2 == 0)
				{
					if (c == EscapeByte && count > 1)
					{
						num++;
						index++;
						count--;
					}
					else if (c < '\u0080')
					{
						num++;
					}
					else if (c < 'ࠀ')
					{
						num += 2;
					}
					else if (c >= '\ud800' && c <= '\udbff')
					{
						num2 = c;
					}
					else
					{
						num += 3;
					}
				}
				else
				{
					if (c < '\udc00' || c > '\udfff')
					{
						num += 3;
						num2 = 0u;
						continue;
					}
					num += 4;
					num2 = 0u;
				}
				index++;
				count--;
			}
			if (flush && num2 != 0)
			{
				num += 3;
			}
			return num;
		}

		public override int GetByteCount(char[] chars, int index, int count)
		{
			return InternalGetByteCount(chars, index, count, 0u, flush: true);
		}

		public override int GetByteCount(string s)
		{
			if (s == null)
			{
				throw new ArgumentNullException("s");
			}
			int num = 0;
			int num2 = s.Length;
			int num3 = 0;
			while (num2 > 0)
			{
				char c = s[num++];
				if (c == EscapeByte && num2 > 1)
				{
					num3++;
					num++;
					num2--;
				}
				else if (c < '\u0080')
				{
					num3++;
				}
				else if (c < 'ࠀ')
				{
					num3 += 2;
				}
				else if (c >= '\ud800' && c <= '\udbff' && num2 > 1)
				{
					uint num4 = s[num];
					if (num4 >= 56320 && num4 <= 57343)
					{
						num3 += 4;
						num++;
						num2--;
					}
					else
					{
						num3 += 3;
					}
				}
				else
				{
					num3 += 3;
				}
				num2--;
			}
			return num3;
		}

		private static int InternalGetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, ref uint leftOver, bool flush)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (charIndex < 0 || charIndex > chars.Length)
			{
				throw new ArgumentOutOfRangeException("charIndex", _("ArgRange_Array"));
			}
			if (charCount < 0 || charCount > chars.Length - charIndex)
			{
				throw new ArgumentOutOfRangeException("charCount", _("ArgRange_Array"));
			}
			if (byteIndex < 0 || byteIndex > bytes.Length)
			{
				throw new ArgumentOutOfRangeException("byteIndex", _("ArgRange_Array"));
			}
			int num = bytes.Length;
			uint num2 = leftOver;
			int num3 = byteIndex;
			while (charCount > 0)
			{
				char c = chars[charIndex++];
				charCount--;
				uint num4;
				if (num2 == 0)
				{
					if (c >= '\ud800' && c <= '\udbff')
					{
						num2 = c;
						continue;
					}
					if (c == EscapeByte)
					{
						if (num3 >= num)
						{
							throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
						}
						if (--charCount >= 0)
						{
							bytes[num3++] = (byte)chars[charIndex++];
						}
						continue;
					}
					num4 = c;
				}
				else if (c >= '\udc00' && c <= '\udfff')
				{
					num4 = (uint)((int)(num2 - 55296 << 10) + (c - 56320) + 65536);
					num2 = 0u;
				}
				else
				{
					num4 = num2;
					num2 = 0u;
					charIndex--;
					charCount++;
				}
				if (num4 < 128)
				{
					if (num3 >= num)
					{
						throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
					}
					bytes[num3++] = (byte)num4;
					continue;
				}
				if (num4 < 2048)
				{
					if (num3 + 2 > num)
					{
						throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
					}
					bytes[num3++] = (byte)(0xC0u | (num4 >> 6));
					bytes[num3++] = (byte)(0x80u | (num4 & 0x3Fu));
					continue;
				}
				if (num4 < 65536)
				{
					if (num3 + 3 > num)
					{
						throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
					}
					bytes[num3++] = (byte)(0xE0u | (num4 >> 12));
					bytes[num3++] = (byte)(0x80u | ((num4 >> 6) & 0x3Fu));
					bytes[num3++] = (byte)(0x80u | (num4 & 0x3Fu));
					continue;
				}
				if (num3 + 4 > num)
				{
					throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
				}
				bytes[num3++] = (byte)(0xF0u | (num4 >> 18));
				bytes[num3++] = (byte)(0x80u | ((num4 >> 12) & 0x3Fu));
				bytes[num3++] = (byte)(0x80u | ((num4 >> 6) & 0x3Fu));
				bytes[num3++] = (byte)(0x80u | (num4 & 0x3Fu));
			}
			if (flush && num2 != 0)
			{
				if (num3 + 3 > num)
				{
					throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
				}
				bytes[num3++] = (byte)(0xE0u | (num2 >> 12));
				bytes[num3++] = (byte)(0x80u | ((num2 >> 6) & 0x3Fu));
				bytes[num3++] = (byte)(0x80u | (num2 & 0x3Fu));
				num2 = 0u;
			}
			leftOver = num2;
			return num3 - byteIndex;
		}

		public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			uint leftOver = 0u;
			return InternalGetBytes(chars, charIndex, charCount, bytes, byteIndex, ref leftOver, flush: true);
		}

		public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			if (s == null)
			{
				throw new ArgumentNullException("s");
			}
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (charIndex < 0 || charIndex > s.Length)
			{
				throw new ArgumentOutOfRangeException("charIndex", _("ArgRange_StringIndex"));
			}
			if (charCount < 0 || charCount > s.Length - charIndex)
			{
				throw new ArgumentOutOfRangeException("charCount", _("ArgRange_StringRange"));
			}
			if (byteIndex < 0 || byteIndex > bytes.Length)
			{
				throw new ArgumentOutOfRangeException("byteIndex", _("ArgRange_Array"));
			}
			fixed (char* ptr = s)
			{
				fixed (byte* ptr2 = bytes)
				{
					return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, bytes.Length - byteIndex);
				}
			}
		}

		public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount)
		{
			if ((bytes == null && byteCount != 0) || (chars == null && charCount != 0))
			{
				throw new ArgumentNullException((bytes == null && byteCount != 0) ? "bytes" : "chars");
			}
			if (charCount < 0 || byteCount < 0)
			{
				throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount");
			}
			int num = 0;
			int num2 = 0;
			while (charCount > 0)
			{
				char c = chars[num2++];
				uint num3;
				if (c >= '\ud800' && c <= '\udbff' && charCount > 1)
				{
					num3 = chars[num2];
					if (num3 >= 56320 && num3 <= 57343)
					{
						num3 = (uint)((int)(num3 - 56320) + (c - 55296 << 10) + 65536);
						num2++;
						charCount--;
					}
					else
					{
						num3 = c;
					}
				}
				else
				{
					if (c == EscapeByte && charCount > 1)
					{
						if (num >= byteCount)
						{
							throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
						}
						charCount -= 2;
						if (charCount >= 0)
						{
							bytes[num++] = (byte)chars[num2++];
						}
						continue;
					}
					num3 = c;
				}
				charCount--;
				if (num3 < 128)
				{
					if (num >= byteCount)
					{
						throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
					}
					bytes[num++] = (byte)num3;
					continue;
				}
				if (num3 < 2048)
				{
					if (num + 2 > byteCount)
					{
						throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
					}
					bytes[num++] = (byte)(0xC0u | (num3 >> 6));
					bytes[num++] = (byte)(0x80u | (num3 & 0x3Fu));
					continue;
				}
				if (num3 < 65536)
				{
					if (num + 3 > byteCount)
					{
						throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
					}
					bytes[num++] = (byte)(0xE0u | (num3 >> 12));
					bytes[num++] = (byte)(0x80u | ((num3 >> 6) & 0x3Fu));
					bytes[num++] = (byte)(0x80u | (num3 & 0x3Fu));
					continue;
				}
				if (num + 4 > byteCount)
				{
					throw new ArgumentException(_("Arg_InsufficientSpace"), "bytes");
				}
				bytes[num++] = (byte)(0xF0u | (num3 >> 18));
				bytes[num++] = (byte)(0x80u | ((num3 >> 12) & 0x3Fu));
				bytes[num++] = (byte)(0x80u | ((num3 >> 6) & 0x3Fu));
				bytes[num++] = (byte)(0x80u | (num3 & 0x3Fu));
			}
			return num;
		}

		private static int InternalGetCharCount(byte[] bytes, int index, int count, uint leftOverBits, uint leftOverCount, bool throwOnInvalid, bool flush)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (index < 0 || index > bytes.Length)
			{
				throw new ArgumentOutOfRangeException("index", _("ArgRange_Array"));
			}
			if (count < 0 || count > bytes.Length - index)
			{
				throw new ArgumentOutOfRangeException("count", _("ArgRange_Array"));
			}
			int num = 0;
			int num2 = 0;
			uint num3 = leftOverBits;
			uint num4 = leftOverCount & 0xFu;
			uint num5 = (leftOverCount >> 4) & 0xFu;
			while (count > 0)
			{
				uint num6 = bytes[index++];
				num++;
				count--;
				if (num5 == 0)
				{
					if (num6 < 128)
					{
						num2++;
						num = 0;
					}
					else if ((num6 & 0xE0) == 192)
					{
						num3 = num6 & 0x1Fu;
						num4 = 1u;
						num5 = 2u;
					}
					else if ((num6 & 0xF0) == 224)
					{
						num3 = num6 & 0xFu;
						num4 = 1u;
						num5 = 3u;
					}
					else if ((num6 & 0xF8) == 240)
					{
						num3 = num6 & 7u;
						num4 = 1u;
						num5 = 4u;
					}
					else if ((num6 & 0xFC) == 248)
					{
						num3 = num6 & 3u;
						num4 = 1u;
						num5 = 5u;
					}
					else if ((num6 & 0xFE) == 252)
					{
						num3 = num6 & 3u;
						num4 = 1u;
						num5 = 6u;
					}
					else
					{
						num2 += num * 2;
						num = 0;
					}
				}
				else if ((num6 & 0xC0) == 128)
				{
					num3 = (num3 << 6) | (num6 & 0x3Fu);
					if (++num4 < num5)
					{
						continue;
					}
					if (num3 < 65536)
					{
						bool flag = false;
						switch (num5)
						{
						case 2u:
							flag = num3 <= 127;
							break;
						case 3u:
							flag = num3 <= 2047;
							break;
						case 4u:
							flag = num3 <= 65535;
							break;
						case 5u:
							flag = num3 <= 2097151;
							break;
						case 6u:
							flag = num3 <= 67108863;
							break;
						}
						num2 = ((!flag) ? (num2 + 1) : (num2 + num * 2));
					}
					else if (num3 < 1114112)
					{
						num2 += 2;
					}
					else if (throwOnInvalid)
					{
						num2 += num * 2;
					}
					num5 = 0u;
					num = 0;
				}
				else
				{
					if (num6 < 128)
					{
						index--;
						count++;
						num--;
					}
					num2 += num * 2;
					num5 = 0u;
					num = 0;
				}
			}
			if (flush && num5 != 0 && throwOnInvalid)
			{
				num2 += num * 2;
			}
			return num2;
		}

		public override int GetCharCount(byte[] bytes, int index, int count)
		{
			return InternalGetCharCount(bytes, index, count, 0u, 0u, throwOnInvalid: true, flush: true);
		}

		private static int InternalGetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, ref uint leftOverBits, ref uint leftOverCount, bool throwOnInvalid, bool flush)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (byteIndex < 0 || byteIndex > bytes.Length)
			{
				throw new ArgumentOutOfRangeException("byteIndex", _("ArgRange_Array"));
			}
			if (byteCount < 0 || byteCount > bytes.Length - byteIndex)
			{
				throw new ArgumentOutOfRangeException("byteCount", _("ArgRange_Array"));
			}
			if (charIndex < 0 || charIndex > chars.Length)
			{
				throw new ArgumentOutOfRangeException("charIndex", _("ArgRange_Array"));
			}
			if (charIndex == chars.Length)
			{
				return 0;
			}
			byte[] array = new byte[6];
			int next_raw = 0;
			int num = chars.Length;
			int posn = charIndex;
			uint num2 = leftOverBits;
			uint num3 = leftOverCount & 0xFu;
			uint num4 = (leftOverCount >> 4) & 0xFu;
			while (byteCount > 0)
			{
				uint num5 = bytes[byteIndex++];
				array[next_raw++] = (byte)num5;
				byteCount--;
				if (num4 == 0)
				{
					if (num5 < 128)
					{
						if (posn >= num)
						{
							throw new ArgumentException(_("Arg_InsufficientSpace"), "chars");
						}
						next_raw = 0;
						chars[posn++] = (char)num5;
					}
					else if ((num5 & 0xE0) == 192)
					{
						num2 = num5 & 0x1Fu;
						num3 = 1u;
						num4 = 2u;
					}
					else if ((num5 & 0xF0) == 224)
					{
						num2 = num5 & 0xFu;
						num3 = 1u;
						num4 = 3u;
					}
					else if ((num5 & 0xF8) == 240)
					{
						num2 = num5 & 7u;
						num3 = 1u;
						num4 = 4u;
					}
					else if ((num5 & 0xFC) == 248)
					{
						num2 = num5 & 3u;
						num3 = 1u;
						num4 = 5u;
					}
					else if ((num5 & 0xFE) == 252)
					{
						num2 = num5 & 3u;
						num3 = 1u;
						num4 = 6u;
					}
					else
					{
						next_raw = 0;
						chars[posn++] = EscapeByte;
						chars[posn++] = (char)num5;
					}
				}
				else if ((num5 & 0xC0) == 128)
				{
					num2 = (num2 << 6) | (num5 & 0x3Fu);
					if (++num3 < num4)
					{
						continue;
					}
					if (num2 < 65536)
					{
						bool flag = false;
						switch (num4)
						{
						case 2u:
							flag = num2 <= 127;
							break;
						case 3u:
							flag = num2 <= 2047;
							break;
						case 4u:
							flag = num2 <= 65535;
							break;
						case 5u:
							flag = num2 <= 2097151;
							break;
						case 6u:
							flag = num2 <= 67108863;
							break;
						}
						if (flag)
						{
							CopyRaw(array, ref next_raw, chars, ref posn, num);
						}
						else
						{
							if (posn >= num)
							{
								throw new ArgumentException(_("Arg_InsufficientSpace"), "chars");
							}
							chars[posn++] = (char)num2;
						}
					}
					else if (num2 < 1114112)
					{
						if (posn + 2 > num)
						{
							throw new ArgumentException(_("Arg_InsufficientSpace"), "chars");
						}
						num2 -= 65536;
						chars[posn++] = (char)((num2 >> 10) + 55296);
						chars[posn++] = (char)((num2 & 0x3FF) + 56320);
					}
					else if (throwOnInvalid)
					{
						CopyRaw(array, ref next_raw, chars, ref posn, num);
					}
					num4 = 0u;
					next_raw = 0;
				}
				else
				{
					if (num5 < 128)
					{
						byteIndex--;
						byteCount++;
						next_raw--;
					}
					CopyRaw(array, ref next_raw, chars, ref posn, num);
					num4 = 0u;
					next_raw = 0;
				}
			}
			if (flush && num4 != 0 && throwOnInvalid)
			{
				CopyRaw(array, ref next_raw, chars, ref posn, num);
			}
			leftOverBits = num2;
			leftOverCount = num3 | (num4 << 4);
			return posn - charIndex;
		}

		private static void CopyRaw(byte[] raw, ref int next_raw, char[] chars, ref int posn, int length)
		{
			if (posn + next_raw * 2 > length)
			{
				throw new ArgumentException(_("Arg_InsufficientSpace"), "chars");
			}
			for (int i = 0; i < next_raw; i++)
			{
				chars[posn++] = EscapeByte;
				chars[posn++] = (char)raw[i];
			}
			next_raw = 0;
		}

		public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
		{
			uint leftOverBits = 0u;
			uint leftOverCount = 0u;
			return InternalGetChars(bytes, byteIndex, byteCount, chars, charIndex, ref leftOverBits, ref leftOverCount, throwOnInvalid: true, flush: true);
		}

		public override int GetMaxByteCount(int charCount)
		{
			if (charCount < 0)
			{
				throw new ArgumentOutOfRangeException("charCount", _("ArgRange_NonNegative"));
			}
			return charCount * 4;
		}

		public override int GetMaxCharCount(int byteCount)
		{
			if (byteCount < 0)
			{
				throw new ArgumentOutOfRangeException("byteCount", _("ArgRange_NonNegative"));
			}
			return byteCount;
		}

		public override Decoder GetDecoder()
		{
			return new UnixDecoder();
		}

		public override Encoder GetEncoder()
		{
			return new UnixEncoder();
		}

		public override byte[] GetPreamble()
		{
			return new byte[0];
		}

		public override bool Equals(object value)
		{
			if (value is UnixEncoding)
			{
				return true;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return base.GetHashCode();
		}

		public override byte[] GetBytes(string s)
		{
			if (s == null)
			{
				throw new ArgumentNullException("s");
			}
			byte[] array = new byte[GetByteCount(s)];
			GetBytes(s, 0, s.Length, array, 0);
			return array;
		}

		private static string _(string arg)
		{
			return arg;
		}
	}
	[Serializable]
	public class UnixEndPoint : EndPoint
	{
		private string filename;

		public string Filename
		{
			get
			{
				return filename;
			}
			set
			{
				filename = value;
			}
		}

		public override AddressFamily AddressFamily => AddressFamily.Unix;

		public UnixEndPoint(string filename)
		{
			if (filename == null)
			{
				throw new ArgumentNullException("filename");
			}
			if (filename == "")
			{
				throw new ArgumentException("Cannot be empty.", "filename");
			}
			this.filename = filename;
		}

		public override EndPoint Create(SocketAddress socketAddress)
		{
			int num = socketAddress.Size - 2;
			byte[] array = new byte[num];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = socketAddress[i + 2];
				if (array[i] == 0)
				{
					num = i;
					break;
				}
			}
			if (num == 0)
			{
				return new UnixEndPoint("dummy")
				{
					filename = ""
				};
			}
			return new UnixEndPoint(Encoding.Default.GetString(array, 0, num));
		}

		public override SocketAddress Serialize()
		{
			byte[] bytes = Encoding.Default.GetBytes(filename);
			SocketAddress socketAddress = new SocketAddress(AddressFamily, 2 + bytes.Length + 1);
			for (int i = 0; i < bytes.Length; i++)
			{
				socketAddress[2 + i] = bytes[i];
			}
			socketAddress[2 + bytes.Length] = 0;
			return socketAddress;
		}

		public override string ToString()
		{
			return filename;
		}

		public override int GetHashCode()
		{
			return filename.GetHashCode();
		}

		public override bool Equals(object o)
		{
			if (!(o is UnixEndPoint unixEndPoint))
			{
				return false;
			}
			return unixEndPoint.filename == filename;
		}
	}
	public sealed class UnixEnvironment
	{
		public static string CurrentDirectory
		{
			get
			{
				return UnixDirectoryInfo.GetCurrentDirectory();
			}
			set
			{
				UnixDirectoryInfo.SetCurrentDirectory(value);
			}
		}

		public static string MachineName
		{
			get
			{
				if (Syscall.uname(out var buf) != 0)
				{
					throw UnixMarshal.CreateExceptionForLastError();
				}
				return buf.nodename;
			}
			set
			{
				UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.sethostname(value));
			}
		}

		public static string UserName => UnixUserInfo.GetRealUser().UserName;

		public static UnixGroupInfo RealGroup => new UnixGroupInfo(RealGroupId);

		public static long RealGroupId => Syscall.getgid();

		public static UnixUserInfo RealUser => new UnixUserInfo(RealUserId);

		public static long RealUserId => Syscall.getuid();

		public static UnixGroupInfo EffectiveGroup
		{
			get
			{
				return new UnixGroupInfo(EffectiveGroupId);
			}
			set
			{
				EffectiveGroupId = value.GroupId;
			}
		}

		public static long EffectiveGroupId
		{
			get
			{
				return Syscall.getegid();
			}
			set
			{
				Syscall.setegid(Convert.ToUInt32(value));
			}
		}

		public static UnixUserInfo EffectiveUser
		{
			get
			{
				return new UnixUserInfo(EffectiveUserId);
			}
			set
			{
				EffectiveUserId = value.UserId;
			}
		}

		public static long EffectiveUserId
		{
			get
			{
				return Syscall.geteuid();
			}
			set
			{
				Syscall.seteuid(Convert.ToUInt32(value));
			}
		}

		public static string Login => UnixUserInfo.GetRealUser().UserName;

		private UnixEnvironment()
		{
		}

		[CLSCompliant(false)]
		public static long GetConfigurationValue(SysconfName name)
		{
			long num = Syscall.sysconf(name);
			if (num == -1 && Stdlib.GetLastError() != 0)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return num;
		}

		[CLSCompliant(false)]
		public static string GetConfigurationString(ConfstrName name)
		{
			ulong num = Syscall.confstr(name, null, 0uL);
			if (num == ulong.MaxValue)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			if (num == 0L)
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder((int)num + 1);
			num = Syscall.confstr(name, stringBuilder, num);
			if (num == ulong.MaxValue)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return stringBuilder.ToString();
		}

		public static void SetNiceValue(int inc)
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.nice(inc));
		}

		public static int CreateSession()
		{
			int num = Syscall.setsid();
			UnixMarshal.ThrowExceptionForLastErrorIf(num);
			return num;
		}

		public static void SetProcessGroup()
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.setpgrp());
		}

		public static int GetProcessGroup()
		{
			return Syscall.getpgrp();
		}

		public static UnixGroupInfo[] GetSupplementaryGroups()
		{
			uint[] array = _GetSupplementaryGroupIds();
			UnixGroupInfo[] array2 = new UnixGroupInfo[array.Length];
			for (int i = 0; i < array2.Length; i++)
			{
				array2[i] = new UnixGroupInfo(array[i]);
			}
			return array2;
		}

		private static uint[] _GetSupplementaryGroupIds()
		{
			int num = Syscall.getgroups(0, new uint[0]);
			if (num == -1)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			uint[] array = new uint[num];
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.getgroups(array));
			return array;
		}

		public static void SetSupplementaryGroups(UnixGroupInfo[] groups)
		{
			uint[] array = new uint[groups.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Convert.ToUInt32(groups[i].GroupId);
			}
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.setgroups(array));
		}

		public static long[] GetSupplementaryGroupIds()
		{
			uint[] array = _GetSupplementaryGroupIds();
			long[] array2 = new long[array.Length];
			for (int i = 0; i < array2.Length; i++)
			{
				array2[i] = array[i];
			}
			return array2;
		}

		public static void SetSupplementaryGroupIds(long[] list)
		{
			uint[] array = new uint[list.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = Convert.ToUInt32(list[i]);
			}
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.setgroups(array));
		}

		public static int GetParentProcessId()
		{
			return Syscall.getppid();
		}

		public static UnixProcess GetParentProcess()
		{
			return new UnixProcess(GetParentProcessId());
		}

		public static string[] GetUserShells()
		{
			ArrayList arrayList = new ArrayList();
			lock (Syscall.usershell_lock)
			{
				try
				{
					if (Syscall.setusershell() != 0)
					{
						UnixMarshal.ThrowExceptionForLastError();
					}
					string value;
					while ((value = Syscall.getusershell()) != null)
					{
						arrayList.Add(value);
					}
				}
				finally
				{
					Syscall.endusershell();
				}
			}
			return (string[])arrayList.ToArray(typeof(string));
		}
	}
	public sealed class UnixFileInfo : UnixFileSystemInfo
	{
		public override string Name => UnixPath.GetFileName(base.FullPath);

		public string DirectoryName => UnixPath.GetDirectoryName(base.FullPath);

		public UnixDirectoryInfo Directory => new UnixDirectoryInfo(DirectoryName);

		public UnixFileInfo(string path)
			: base(path)
		{
		}

		internal UnixFileInfo(string path, Stat stat)
			: base(path, stat)
		{
		}

		public override void Delete()
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.unlink(base.FullPath));
			Refresh();
		}

		public UnixStream Create()
		{
			FilePermissions mode = FilePermissions.S_IRUSR | FilePermissions.S_IWUSR | FilePermissions.S_IRGRP | FilePermissions.S_IROTH;
			return Create(mode);
		}

		[CLSCompliant(false)]
		public UnixStream Create(FilePermissions mode)
		{
			int num = Syscall.creat(base.FullPath, mode);
			if (num < 0)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			Refresh();
			return new UnixStream(num);
		}

		public UnixStream Create(FileAccessPermissions mode)
		{
			return Create((FilePermissions)mode);
		}

		[CLSCompliant(false)]
		public UnixStream Open(OpenFlags flags)
		{
			if ((flags & OpenFlags.O_CREAT) != 0)
			{
				throw new ArgumentException("Cannot specify OpenFlags.O_CREAT without providing FilePermissions.  Use the Open(OpenFlags, FilePermissions) method instead");
			}
			int num = Syscall.open(base.FullPath, flags);
			if (num < 0)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return new UnixStream(num);
		}

		[CLSCompliant(false)]
		public UnixStream Open(OpenFlags flags, FilePermissions mode)
		{
			int num = Syscall.open(base.FullPath, flags, mode);
			if (num < 0)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return new UnixStream(num);
		}

		public UnixStream Open(FileMode mode)
		{
			OpenFlags flags = NativeConvert.ToOpenFlags(mode, FileAccess.ReadWrite);
			return Open(flags);
		}

		public UnixStream Open(FileMode mode, FileAccess access)
		{
			OpenFlags flags = NativeConvert.ToOpenFlags(mode, access);
			return Open(flags);
		}

		[CLSCompliant(false)]
		public UnixStream Open(FileMode mode, FileAccess access, FilePermissions perms)
		{
			OpenFlags flags = NativeConvert.ToOpenFlags(mode, access);
			int num = Syscall.open(base.FullPath, flags, perms);
			if (num < 0)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return new UnixStream(num);
		}

		public UnixStream OpenRead()
		{
			return Open(FileMode.Open, FileAccess.Read);
		}

		public UnixStream OpenWrite()
		{
			return Open(FileMode.OpenOrCreate, FileAccess.Write);
		}
	}
	public abstract class UnixFileSystemInfo
	{
		private Stat stat;

		private string fullPath;

		private string originalPath;

		private bool valid;

		internal const FileSpecialAttributes AllSpecialAttributes = FileSpecialAttributes.SetUserId | FileSpecialAttributes.SetGroupId | FileSpecialAttributes.Sticky;

		internal const FileTypes AllFileTypes = (FileTypes)61440;

		protected string FullPath
		{
			get
			{
				return fullPath;
			}
			set
			{
				if (fullPath != value)
				{
					UnixPath.CheckPath(value);
					valid = false;
					fullPath = value;
				}
			}
		}

		protected string OriginalPath
		{
			get
			{
				return originalPath;
			}
			set
			{
				originalPath = value;
			}
		}

		public virtual string FullName => FullPath;

		public abstract string Name { get; }

		public bool Exists
		{
			get
			{
				Refresh(force: true);
				return valid;
			}
		}

		public long Device
		{
			get
			{
				AssertValid();
				return Convert.ToInt64(stat.st_dev);
			}
		}

		public long Inode
		{
			get
			{
				AssertValid();
				return Convert.ToInt64(stat.st_ino);
			}
		}

		[CLSCompliant(false)]
		public FilePermissions Protection
		{
			get
			{
				AssertValid();
				return stat.st_mode;
			}
			set
			{
				UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.chmod(FullPath, value));
			}
		}

		public FileTypes FileType
		{
			get
			{
				AssertValid();
				return (FileTypes)(stat.st_mode & FilePermissions.S_IFMT);
			}
		}

		public FileAccessPermissions FileAccessPermissions
		{
			get
			{
				AssertValid();
				return (FileAccessPermissions)(stat.st_mode & FilePermissions.ACCESSPERMS);
			}
			set
			{
				AssertValid();
				int st_mode = (int)stat.st_mode;
				st_mode &= -512;
				st_mode |= (int)value;
				Protection = (FilePermissions)st_mode;
			}
		}

		public FileSpecialAttributes FileSpecialAttributes
		{
			get
			{
				AssertValid();
				return (FileSpecialAttributes)(stat.st_mode & (FilePermissions.S_ISUID | FilePermissions.S_ISGID | FilePermissions.S_ISVTX));
			}
			set
			{
				AssertValid();
				int st_mode = (int)stat.st_mode;
				st_mode &= -3585;
				st_mode |= (int)value;
				Protection = (FilePermissions)st_mode;
			}
		}

		public long LinkCount
		{
			get
			{
				AssertValid();
				return Convert.ToInt64(stat.st_nlink);
			}
		}

		public UnixUserInfo OwnerUser
		{
			get
			{
				AssertValid();
				return new UnixUserInfo(stat.st_uid);
			}
		}

		public long OwnerUserId
		{
			get
			{
				AssertValid();
				return stat.st_uid;
			}
		}

		public UnixGroupInfo OwnerGroup
		{
			get
			{
				AssertValid();
				return new UnixGroupInfo(stat.st_gid);
			}
		}

		public long OwnerGroupId
		{
			get
			{
				AssertValid();
				return stat.st_gid;
			}
		}

		public long DeviceType
		{
			get
			{
				AssertValid();
				return Convert.ToInt64(stat.st_rdev);
			}
		}

		public long Length
		{
			get
			{
				AssertValid();
				return stat.st_size;
			}
		}

		public long BlockSize
		{
			get
			{
				AssertValid();
				return stat.st_blksize;
			}
		}

		public long BlocksAllocated
		{
			get
			{
				AssertValid();
				return stat.st_blocks;
			}
		}

		public DateTime LastAccessTime
		{
			get
			{
				AssertValid();
				return NativeConvert.ToDateTime(stat.st_atime, stat.st_atime_nsec);
			}
		}

		public DateTime LastAccessTimeUtc => LastAccessTime.ToUniversalTime();

		public DateTime LastWriteTime
		{
			get
			{
				AssertValid();
				return NativeConvert.ToDateTime(stat.st_mtime, stat.st_mtime_nsec);
			}
		}

		public DateTime LastWriteTimeUtc => LastWriteTime.ToUniversalTime();

		public DateTime LastStatusChangeTime
		{
			get
			{
				AssertValid();
				return NativeConvert.ToDateTime(stat.st_ctime, stat.st_ctime_nsec);
			}
		}

		public DateTime LastStatusChangeTimeUtc => LastStatusChangeTime.ToUniversalTime();

		public bool IsDirectory
		{
			get
			{
				AssertValid();
				return IsFileType(stat.st_mode, FilePermissions.S_IFDIR);
			}
		}

		public bool IsCharacterDevice
		{
			get
			{
				AssertValid();
				return IsFileType(stat.st_mode, FilePermissions.S_IFCHR);
			}
		}

		public bool IsBlockDevice
		{
			get
			{
				AssertValid();
				return IsFileType(stat.st_mode, FilePermissions.S_IFBLK);
			}
		}

		public bool IsRegularFile
		{
			get
			{
				AssertValid();
				return IsFileType(stat.st_mode, FilePermissions.S_IFREG);
			}
		}

		public bool IsFifo
		{
			get
			{
				AssertValid();
				return IsFileType(stat.st_mode, FilePermissions.S_IFIFO);
			}
		}

		public bool IsSymbolicLink
		{
			get
			{
				AssertValid();
				return IsFileType(stat.st_mode, FilePermissions.S_IFLNK);
			}
		}

		public bool IsSocket
		{
			get
			{
				AssertValid();
				return IsFileType(stat.st_mode, FilePermissions.S_IFSOCK);
			}
		}

		public bool IsSetUser
		{
			get
			{
				AssertValid();
				return IsSet(stat.st_mode, FilePermissions.S_ISUID);
			}
		}

		public bool IsSetGroup
		{
			get
			{
				AssertValid();
				return IsSet(stat.st_mode, FilePermissions.S_ISGID);
			}
		}

		public bool IsSticky
		{
			get
			{
				AssertValid();
				return IsSet(stat.st_mode, FilePermissions.S_ISVTX);
			}
		}

		protected UnixFileSystemInfo(string path)
		{
			UnixPath.CheckPath(path);
			originalPath = path;
			fullPath = UnixPath.GetFullPath(path);
			Refresh(force: true);
		}

		internal UnixFileSystemInfo(string path, Stat stat)
		{
			originalPath = path;
			fullPath = UnixPath.GetFullPath(path);
			this.stat = stat;
			valid = true;
		}

		private void AssertValid()
		{
			Refresh(force: false);
			if (!valid)
			{
				throw new InvalidOperationException("Path doesn't exist!");
			}
		}

		internal static bool IsFileType(FilePermissions mode, FilePermissions type)
		{
			return (mode & FilePermissions.S_IFMT) == type;
		}

		internal static bool IsSet(FilePermissions mode, FilePermissions type)
		{
			return (mode & type) == type;
		}

		[CLSCompliant(false)]
		public bool CanAccess(AccessModes mode)
		{
			return Syscall.access(FullPath, mode) == 0;
		}

		public UnixFileSystemInfo CreateLink(string path)
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.link(FullName, path));
			return GetFileSystemEntry(path);
		}

		public UnixSymbolicLinkInfo CreateSymbolicLink(string path)
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.symlink(FullName, path));
			return new UnixSymbolicLinkInfo(path);
		}

		public abstract void Delete();

		[CLSCompliant(false)]
		public long GetConfigurationValue(PathconfName name)
		{
			long num = Syscall.pathconf(FullPath, name);
			if (num == -1 && Stdlib.GetLastError() != 0)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return num;
		}

		public void Refresh()
		{
			Refresh(force: true);
		}

		internal void Refresh(bool force)
		{
			if (!valid || force)
			{
				valid = GetFileStatus(FullPath, out stat);
			}
		}

		protected virtual bool GetFileStatus(string path, out Stat stat)
		{
			return Syscall.stat(path, out stat) == 0;
		}

		public void SetLength(long length)
		{
			int num;
			do
			{
				num = Syscall.truncate(FullPath, length);
			}
			while (UnixMarshal.ShouldRetrySyscall(num));
			UnixMarshal.ThrowExceptionForLastErrorIf(num);
		}

		public virtual void SetOwner(long owner, long group)
		{
			int owner2 = Convert.ToInt32(owner);
			int group2 = Convert.ToInt32(group);
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.chown(FullPath, owner2, group2));
		}

		public void SetOwner(string owner)
		{
			Passwd passwd = Syscall.getpwnam(owner);
			if (passwd == null)
			{
				throw new ArgumentException(Locale.GetText("invalid username"), "owner");
			}
			uint pw_uid = passwd.pw_uid;
			uint pw_gid = passwd.pw_gid;
			SetOwner(pw_uid, pw_gid);
		}

		public void SetOwner(string owner, string group)
		{
			long owner2 = -1L;
			if (owner != null)
			{
				owner2 = new UnixUserInfo(owner).UserId;
			}
			long group2 = -1L;
			if (group != null)
			{
				group2 = new UnixGroupInfo(group).GroupId;
			}
			SetOwner(owner2, group2);
		}

		public void SetOwner(UnixUserInfo owner)
		{
			long group;
			long owner2 = (group = -1L);
			if (owner != null)
			{
				owner2 = owner.UserId;
				group = owner.GroupId;
			}
			SetOwner(owner2, group);
		}

		public void SetOwner(UnixUserInfo owner, UnixGroupInfo group)
		{
			long group2;
			long owner2 = (group2 = -1L);
			if (owner != null)
			{
				owner2 = owner.UserId;
			}
			if (group != null)
			{
				group2 = owner.GroupId;
			}
			SetOwner(owner2, group2);
		}

		public override string ToString()
		{
			return FullPath;
		}

		public Stat ToStat()
		{
			AssertValid();
			return stat;
		}

		public static UnixFileSystemInfo GetFileSystemEntry(string path)
		{
			if (TryGetFileSystemEntry(path, out var entry))
			{
				return entry;
			}
			UnixMarshal.ThrowExceptionForLastError();
			throw new DirectoryNotFoundException("UnixMarshal.ThrowExceptionForLastError didn't throw?!");
		}

		public static bool TryGetFileSystemEntry(string path, out UnixFileSystemInfo entry)
		{
			if (Syscall.lstat(path, out var buf) == -1)
			{
				if (Stdlib.GetLastError() == Errno.ENOENT)
				{
					entry = new UnixFileInfo(path);
					return true;
				}
				entry = null;
				return false;
			}
			if (IsFileType(buf.st_mode, FilePermissions.S_IFDIR))
			{
				entry = new UnixDirectoryInfo(path, buf);
			}
			else if (IsFileType(buf.st_mode, FilePermissions.S_IFLNK))
			{
				entry = new UnixSymbolicLinkInfo(path, buf);
			}
			else
			{
				entry = new UnixFileInfo(path, buf);
			}
			return true;
		}
	}
	public sealed class UnixGroupInfo
	{
		private Mono.Unix.Native.Group group;

		public string GroupName => group.gr_name;

		public string Password => group.gr_passwd;

		public long GroupId => group.gr_gid;

		public UnixGroupInfo(string group)
		{
			this.group = new Mono.Unix.Native.Group();
			if (Syscall.getgrnam_r(group, this.group, out var grbufp) != 0 || grbufp == null)
			{
				throw new ArgumentException(Locale.GetText("invalid group name"), "group");
			}
		}

		public UnixGroupInfo(long group)
		{
			this.group = new Mono.Unix.Native.Group();
			if (Syscall.getgrgid_r(Convert.ToUInt32(group), this.group, out var grbufp) != 0 || grbufp == null)
			{
				throw new ArgumentException(Locale.GetText("invalid group id"), "group");
			}
		}

		public UnixGroupInfo(Mono.Unix.Native.Group group)
		{
			this.group = CopyGroup(group);
		}

		private static Mono.Unix.Native.Group CopyGroup(Mono.Unix.Native.Group group)
		{
			return new Mono.Unix.Native.Group
			{
				gr_gid = group.gr_gid,
				gr_mem = group.gr_mem,
				gr_name = group.gr_name,
				gr_passwd = group.gr_passwd
			};
		}

		public UnixUserInfo[] GetMembers()
		{
			ArrayList arrayList = new ArrayList(group.gr_mem.Length);
			for (int i = 0; i < group.gr_mem.Length; i++)
			{
				try
				{
					arrayList.Add(new UnixUserInfo(group.gr_mem[i]));
				}
				catch (ArgumentException)
				{
				}
			}
			return (UnixUserInfo[])arrayList.ToArray(typeof(UnixUserInfo));
		}

		public string[] GetMemberNames()
		{
			return (string[])group.gr_mem.Clone();
		}

		public override int GetHashCode()
		{
			return group.GetHashCode();
		}

		public override bool Equals(object obj)
		{
			if (obj == null || GetType() != obj.GetType())
			{
				return false;
			}
			return group.Equals(((UnixGroupInfo)obj).group);
		}

		public override string ToString()
		{
			return group.ToString();
		}

		public Mono.Unix.Native.Group ToGroup()
		{
			return CopyGroup(group);
		}

		public static UnixGroupInfo[] GetLocalGroups()
		{
			ArrayList arrayList = new ArrayList();
			lock (Syscall.grp_lock)
			{
				if (Syscall.setgrent() != 0)
				{
					UnixMarshal.ThrowExceptionForLastError();
				}
				try
				{
					Mono.Unix.Native.Group group;
					while ((group = Syscall.getgrent()) != null)
					{
						arrayList.Add(new UnixGroupInfo(group));
					}
					if (Stdlib.GetLastError() != 0)
					{
						UnixMarshal.ThrowExceptionForLastError();
					}
				}
				finally
				{
					Syscall.endgrent();
				}
			}
			return (UnixGroupInfo[])arrayList.ToArray(typeof(UnixGroupInfo));
		}
	}
	[Serializable]
	public class UnixIOException : IOException
	{
		private int errno;

		public int NativeErrorCode => errno;

		public Errno ErrorCode => NativeConvert.ToErrno(errno);

		public UnixIOException()
			: this(Marshal.GetLastWin32Error())
		{
		}

		public UnixIOException(int errno)
			: base(GetMessage(NativeConvert.ToErrno(errno)))
		{
			this.errno = errno;
		}

		public UnixIOException(int errno, Exception inner)
			: base(GetMessage(NativeConvert.ToErrno(errno)), inner)
		{
			this.errno = errno;
		}

		public UnixIOException(Errno errno)
			: base(GetMessage(errno))
		{
			this.errno = NativeConvert.FromErrno(errno);
		}

		public UnixIOException(Errno errno, Exception inner)
			: base(GetMessage(errno), inner)
		{
			this.errno = NativeConvert.FromErrno(errno);
		}

		public UnixIOException(string message)
			: base(message)
		{
			errno = 0;
		}

		public UnixIOException(string message, Exception inner)
			: base(message, inner)
		{
			errno = 0;
		}

		protected UnixIOException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		private static string GetMessage(Errno errno)
		{
			return $"{UnixMarshal.GetErrorDescription(errno)} [{errno}].";
		}
	}
	public class UnixListener : MarshalByRefObject, IDisposable
	{
		private bool disposed;

		private bool listening;

		private Socket server;

		private EndPoint savedEP;

		public EndPoint LocalEndpoint => savedEP;

		protected Socket Server => server;

		private void Init(UnixEndPoint ep)
		{
			listening = false;
			string filename = ep.Filename;
			if (File.Exists(filename))
			{
				Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
				try
				{
					socket.Connect(ep);
					socket.Close();
					throw new InvalidOperationException("There's already a server listening on " + filename);
				}
				catch (SocketException)
				{
				}
				File.Delete(filename);
			}
			server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP);
			server.Bind(ep);
			savedEP = server.LocalEndPoint;
		}

		public UnixListener(string path)
		{
			if (!Directory.Exists(Path.GetDirectoryName(path)))
			{
				Directory.CreateDirectory(Path.GetDirectoryName(path));
			}
			Init(new UnixEndPoint(path));
		}

		public UnixListener(UnixEndPoint localEndPoint)
		{
			if (localEndPoint == null)
			{
				throw new ArgumentNullException("localendPoint");
			}
			Init(localEndPoint);
		}

		public Socket AcceptSocket()
		{
			CheckDisposed();
			if (!listening)
			{
				throw new InvalidOperationException("Socket is not listening");
			}
			return server.Accept();
		}

		public UnixClient AcceptUnixClient()
		{
			CheckDisposed();
			if (!listening)
			{
				throw new InvalidOperationException("Socket is not listening");
			}
			return new UnixClient(AcceptSocket());
		}

		~UnixListener()
		{
			Dispose(disposing: false);
		}

		public bool Pending()
		{
			CheckDisposed();
			if (!listening)
			{
				throw new InvalidOperationException("Socket is not listening");
			}
			return server.Poll(1000, SelectMode.SelectRead);
		}

		public void Start()
		{
			Start(5);
		}

		public void Start(int backlog)
		{
			CheckDisposed();
			if (!listening)
			{
				server.Listen(backlog);
				listening = true;
			}
		}

		public void Stop()
		{
			CheckDisposed();
			Dispose(disposing: true);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected void Dispose(bool disposing)
		{
			if (disposed)
			{
				return;
			}
			if (disposing)
			{
				try
				{
					File.Delete(((UnixEndPoint)savedEP).Filename);
				}
				catch
				{
				}
				if (server != null)
				{
					server.Close();
				}
				server = null;
			}
			disposed = true;
		}

		private void CheckDisposed()
		{
			if (disposed)
			{
				throw new ObjectDisposedException(GetType().FullName);
			}
		}
	}
	internal class ErrorMarshal
	{
		internal delegate string ErrorTranslator(Errno errno);

		internal static readonly ErrorTranslator Translate;

		static ErrorMarshal()
		{
			try
			{
				Translate = strerror_r;
				Translate(Errno.ERANGE);
			}
			catch (EntryPointNotFoundException)
			{
				Translate = strerror;
			}
		}

		private static string strerror(Errno errno)
		{
			return Stdlib.strerror(errno);
		}

		private static string strerror_r(Errno errno)
		{
			StringBuilder stringBuilder = new StringBuilder(16);
			int num = 0;
			do
			{
				stringBuilder.Capacity *= 2;
				num = Syscall.strerror_r(errno, stringBuilder);
			}
			while (num == -1 && Stdlib.GetLastError() == Errno.ERANGE);
			if (num == -1)
			{
				int num2 = (int)errno;
				return "** Unknown error code: " + num2 + "**";
			}
			return stringBuilder.ToString();
		}
	}
	public sealed class UnixMarshal
	{
		private UnixMarshal()
		{
		}

		[CLSCompliant(false)]
		public static string GetErrorDescription(Errno errno)
		{
			return ErrorMarshal.Translate(errno);
		}

		public static IntPtr AllocHeap(long size)
		{
			if (size < 0)
			{
				throw new ArgumentOutOfRangeException("size", "< 0");
			}
			return Stdlib.malloc((ulong)size);
		}

		public static IntPtr ReAllocHeap(IntPtr ptr, long size)
		{
			if (size < 0)
			{
				throw new ArgumentOutOfRangeException("size", "< 0");
			}
			return Stdlib.realloc(ptr, (ulong)size);
		}

		public static void FreeHeap(IntPtr ptr)
		{
			Stdlib.free(ptr);
		}

		public unsafe static string PtrToStringUnix(IntPtr p)
		{
			if (p == IntPtr.Zero)
			{
				return null;
			}
			int length = checked((int)Stdlib.strlen(p));
			return new string((sbyte*)(void*)p, 0, length, UnixEncoding.Instance);
		}

		public static string PtrToString(IntPtr p)
		{
			if (p == IntPtr.Zero)
			{
				return null;
			}
			return PtrToString(p, UnixEncoding.Instance);
		}

		public unsafe static string PtrToString(IntPtr p, Encoding encoding)
		{
			if (p == IntPtr.Zero)
			{
				return null;
			}
			if (encoding == null)
			{
				throw new ArgumentNullException("encoding");
			}
			int stringByteLength = GetStringByteLength(p, encoding);
			string text = new string((sbyte*)(void*)p, 0, stringByteLength, encoding);
			stringByteLength = text.Length;
			while (stringByteLength > 0 && text[stringByteLength - 1] == '\0')
			{
				stringByteLength--;
			}
			if (stringByteLength == text.Length)
			{
				return text;
			}
			return text.Substring(0, stringByteLength);
		}

		private static int GetStringByteLength(IntPtr p, Encoding encoding)
		{
			Type type = encoding.GetType();
			int num = -1;
			num = ((typeof(UTF8Encoding).IsAssignableFrom(type) || typeof(UTF7Encoding).IsAssignableFrom(type) || typeof(UnixEncoding).IsAssignableFrom(type) || typeof(ASCIIEncoding).IsAssignableFrom(type)) ? checked((int)Stdlib.strlen(p)) : (typeof(UnicodeEncoding).IsAssignableFrom(type) ? GetInt16BufferLength(p) : ((!typeof(UTF32Encoding).IsAssignableFrom(type)) ? GetRandomBufferLength(p, encoding.GetMaxByteCount(1)) : GetInt32BufferLength(p))));
			if (num == -1)
			{
				throw new NotSupportedException("Unable to determine native string buffer length");
			}
			return num;
		}

		private static int GetInt16BufferLength(IntPtr p)
		{
			int i;
			for (i = 0; Marshal.ReadInt16(p, i * 2) != 0; i = checked(i + 1))
			{
			}
			return checked(i * 2);
		}

		private static int GetInt32BufferLength(IntPtr p)
		{
			int i;
			for (i = 0; Marshal.ReadInt32(p, i * 4) != 0; i = checked(i + 1))
			{
			}
			return checked(i * 4);
		}

		private static int GetRandomBufferLength(IntPtr p, int nullLength)
		{
			switch (nullLength)
			{
			case 1:
				return checked((int)Stdlib.strlen(p));
			case 2:
				return GetInt16BufferLength(p);
			case 4:
				return GetInt32BufferLength(p);
			default:
			{
				int result = 0;
				int num = 0;
				do
				{
					num = ((Marshal.ReadByte(p, result++) == 0) ? (num + 1) : 0);
				}
				while (num != nullLength);
				return result;
			}
			}
		}

		public static string[] PtrToStringArray(IntPtr stringArray)
		{
			return PtrToStringArray(stringArray, UnixEncoding.Instance);
		}

		public static string[] PtrToStringArray(IntPtr stringArray, Encoding encoding)
		{
			if (stringArray == IntPtr.Zero)
			{
				return new string[0];
			}
			return PtrToStringArray(CountStrings(stringArray), stringArray, encoding);
		}

		private static int CountStrings(IntPtr stringArray)
		{
			int i;
			for (i = 0; Marshal.ReadIntPtr(stringArray, i * IntPtr.Size) != IntPtr.Zero; i++)
			{
			}
			return i;
		}

		public static string[] PtrToStringArray(int count, IntPtr stringArray)
		{
			return PtrToStringArray(count, stringArray, UnixEncoding.Instance);
		}

		public static string[] PtrToStringArray(int count, IntPtr stringArray, Encoding encoding)
		{
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count", "< 0");
			}
			if (encoding == null)
			{
				throw new ArgumentNullException("encoding");
			}
			if (stringArray == IntPtr.Zero)
			{
				return new string[count];
			}
			string[] array = new string[count];
			for (int i = 0; i < count; i++)
			{
				IntPtr p = Marshal.ReadIntPtr(stringArray, i * IntPtr.Size);
				array[i] = PtrToString(p, encoding);
			}
			return array;
		}

		public static IntPtr StringToHeap(string s)
		{
			return StringToHeap(s, UnixEncoding.Instance);
		}

		public static IntPtr StringToHeap(string s, Encoding encoding)
		{
			if (s == null)
			{
				return IntPtr.Zero;
			}
			return StringToHeap(s, 0, s.Length, encoding);
		}

		public static IntPtr StringToHeap(string s, int index, int count)
		{
			return StringToHeap(s, index, count, UnixEncoding.Instance);
		}

		public unsafe static IntPtr StringToHeap(string s, int index, int count, Encoding encoding)
		{
			if (s == null)
			{
				return IntPtr.Zero;
			}
			if (encoding == null)
			{
				throw new ArgumentNullException("encoding");
			}
			if (index < 0 || count < 0)
			{
				throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", "Non - negative number required.");
			}
			if (s.Length - index < count)
			{
				throw new ArgumentOutOfRangeException("s", "Index and count must refer to a location within the string.");
			}
			int maxByteCount = encoding.GetMaxByteCount(1);
			int byteCount = encoding.GetByteCount(s);
			int num = checked(byteCount + maxByteCount);
			IntPtr intPtr = AllocHeap(num);
			if (intPtr == IntPtr.Zero)
			{
				throw new UnixIOException(Errno.ENOMEM);
			}
			fixed (char* ptr2 = s)
			{
				byte* ptr = (byte*)(void*)intPtr;
				int bytes;
				try
				{
					bytes = encoding.GetBytes(ptr2 + index, count, ptr, num);
				}
				catch
				{
					FreeHeap(intPtr);
					throw;
				}
				if (bytes != byteCount)
				{
					FreeHeap(intPtr);
					throw new NotSupportedException("encoding.GetBytes() doesn't equal encoding.GetByteCount()!");
				}
				ptr += byteCount;
				for (int i = 0; i < maxByteCount; i++)
				{
					ptr[i] = 0;
				}
			}
			return intPtr;
		}

		public static bool ShouldRetrySyscall(int r)
		{
			if (r == -1 && Stdlib.GetLastError() == Errno.EINTR)
			{
				return true;
			}
			return false;
		}

		[CLSCompliant(false)]
		public static bool ShouldRetrySyscall(int r, out Errno errno)
		{
			errno = (Errno)0;
			if (r == -1 && (errno = Stdlib.GetLastError()) == Errno.EINTR)
			{
				return true;
			}
			return false;
		}

		internal static string EscapeFormatString(string message, char[] permitted)
		{
			if (message == null)
			{
				return "";
			}
			StringBuilder stringBuilder = new StringBuilder(message.Length);
			for (int i = 0; i < message.Length; i++)
			{
				char c = message[i];
				stringBuilder.Append(c);
				if (c == '%' && i + 1 < message.Length)
				{
					char c2 = message[i + 1];
					if (c2 == '%' || IsCharPresent(permitted, c2))
					{
						stringBuilder.Append(c2);
					}
					else
					{
						stringBuilder.Append('%').Append(c2);
					}
					i++;
				}
				else if (c == '%')
				{
					stringBuilder.Append('%');
				}
			}
			return stringBuilder.ToString();
		}

		private static bool IsCharPresent(char[] array, char c)
		{
			if (array == null)
			{
				return false;
			}
			for (int i = 0; i < array.Length; i++)
			{
				if (array[i] == c)
				{
					return true;
				}
			}
			return false;
		}

		internal static Exception CreateExceptionForError(Errno errno)
		{
			string errorDescription = GetErrorDescription(errno);
			UnixIOException ex = new UnixIOException(errno);
			switch (errno)
			{
			case Errno.EBADF:
			case Errno.EINVAL:
				return new ArgumentException(errorDescription, ex);
			case Errno.ERANGE:
				return new ArgumentOutOfRangeException(errorDescription);
			case Errno.ENOTDIR:
				return new DirectoryNotFoundException(errorDescription, ex);
			case Errno.ENOENT:
				return new FileNotFoundException(errorDescription, ex);
			case Errno.EPERM:
			case Errno.EOPNOTSUPP:
				return new InvalidOperationException(errorDescription, ex);
			case Errno.ENOEXEC:
				return new InvalidProgramException(errorDescription, ex);
			case Errno.EIO:
			case Errno.ENXIO:
			case Errno.ENOSPC:
			case Errno.ESPIPE:
			case Errno.EROFS:
			case Errno.ENOTEMPTY:
				return new IOException(errorDescription, ex);
			case Errno.EFAULT:
				return new NullReferenceException(errorDescription, ex);
			case Errno.EOVERFLOW:
				return new OverflowException(errorDescription, ex);
			case Errno.ENAMETOOLONG:
				return new PathTooLongException(errorDescription, ex);
			case Errno.EACCES:
			case Errno.EISDIR:
				return new UnauthorizedAccessException(errorDescription, ex);
			default:
				return ex;
			}
		}

		internal static Exception CreateExceptionForLastError()
		{
			return CreateExceptionForError(Stdlib.GetLastError());
		}

		[CLSCompliant(false)]
		public static void ThrowExceptionForError(Errno errno)
		{
			throw CreateExceptionForError(errno);
		}

		public static void ThrowExceptionForLastError()
		{
			throw CreateExceptionForLastError();
		}

		[CLSCompliant(false)]
		public static void ThrowExceptionForErrorIf(int retval, Errno errno)
		{
			if (retval == -1)
			{
				ThrowExceptionForError(errno);
			}
		}

		public static void ThrowExceptionForLastErrorIf(int retval)
		{
			if (retval == -1)
			{
				ThrowExceptionForLastError();
			}
		}
	}
	public sealed class UnixPath
	{
		public static readonly char DirectorySeparatorChar = '/';

		public static readonly char AltDirectorySeparatorChar = '/';

		public static readonly char PathSeparator = ':';

		public static readonly char VolumeSeparatorChar = '/';

		private static readonly char[] _InvalidPathChars = new char[0];

		private UnixPath()
		{
		}

		public static char[] GetInvalidPathChars()
		{
			return (char[])_InvalidPathChars.Clone();
		}

		public static string Combine(string path1, params string[] paths)
		{
			if (path1 == null)
			{
				throw new ArgumentNullException("path1");
			}
			if (paths == null)
			{
				throw new ArgumentNullException("paths");
			}
			if (path1.IndexOfAny(_InvalidPathChars) != -1)
			{
				throw new ArgumentException("Illegal characters in path", "path1");
			}
			int num = path1.Length;
			int num2 = -1;
			for (int i = 0; i < paths.Length; i++)
			{
				if (paths[i] == null)
				{
					throw new ArgumentNullException("paths[" + i + "]");
				}
				if (paths[i].IndexOfAny(_InvalidPathChars) != -1)
				{
					throw new ArgumentException("Illegal characters in path", "paths[" + i + "]");
				}
				if (IsPathRooted(paths[i]))
				{
					num = 0;
					num2 = i;
				}
				num += paths[i].Length + 1;
			}
			StringBuilder stringBuilder = new StringBuilder(num);
			if (num2 == -1)
			{
				stringBuilder.Append(path1);
				num2 = 0;
			}
			for (int j = num2; j < paths.Length; j++)
			{
				Combine(stringBuilder, paths[j]);
			}
			return stringBuilder.ToString();
		}

		private static void Combine(StringBuilder path, string part)
		{
			if (path.Length > 0 && part.Length > 0)
			{
				char c = path[path.Length - 1];
				if (c != DirectorySeparatorChar && c != AltDirectorySeparatorChar && c != VolumeSeparatorChar)
				{
					path.Append(DirectorySeparatorChar);
				}
			}
			path.Append(part);
		}

		public static string GetDirectoryName(string path)
		{
			CheckPath(path);
			int num = path.LastIndexOf(DirectorySeparatorChar);
			if (num > 0)
			{
				return path.Substring(0, num);
			}
			if (num == 0)
			{
				return "/";
			}
			return "";
		}

		public static string GetFileName(string path)
		{
			if (path == null || path.Length == 0)
			{
				return path;
			}
			int num = path.LastIndexOf(DirectorySeparatorChar);
			if (num >= 0)
			{
				return path.Substring(num + 1);
			}
			return path;
		}

		public static string GetFullPath(string path)
		{
			path = _GetFullPath(path);
			return GetCanonicalPath(path);
		}

		private static string _GetFullPath(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			if (!IsPathRooted(path))
			{
				path = UnixDirectoryInfo.GetCurrentDirectory() + DirectorySeparatorChar + path;
			}
			return path;
		}

		public static string GetCanonicalPath(string path)
		{
			GetPathComponents(path, out var components, out var lastIndex);
			string text = string.Join("/", components, 0, lastIndex);
			if (!IsPathRooted(path))
			{
				return text;
			}
			return "/" + text;
		}

		private static void GetPathComponents(string path, out string[] components, out int lastIndex)
		{
			string[] array = path.Split(DirectorySeparatorChar);
			int num = 0;
			for (int i = 0; i < array.Length; i++)
			{
				if (!(array[i] == ".") && !(array[i] == string.Empty))
				{
					if (array[i] == "..")
					{
						num = ((num == 0) ? (num + 1) : (num - 1));
					}
					else
					{
						array[num++] = array[i];
					}
				}
			}
			components = array;
			lastIndex = num;
		}

		public static string GetPathRoot(string path)
		{
			if (path == null)
			{
				return null;
			}
			if (!IsPathRooted(path))
			{
				return "";
			}
			return "/";
		}

		public static string GetCompleteRealPath(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException("path");
			}
			GetPathComponents(path, out var components, out var lastIndex);
			StringBuilder stringBuilder = new StringBuilder();
			if (components.Length != 0)
			{
				string text = (IsPathRooted(path) ? "/" : "");
				text += components[0];
				stringBuilder.Append(GetRealPath(text));
			}
			for (int i = 1; i < lastIndex; i++)
			{
				stringBuilder.Append("/").Append(components[i]);
				string realPath = GetRealPath(stringBuilder.ToString());
				stringBuilder.Remove(0, stringBuilder.Length);
				stringBuilder.Append(realPath);
			}
			return stringBuilder.ToString();
		}

		public static string GetRealPath(string path)
		{
			while (true)
			{
				string text = ReadSymbolicLink(path);
				if (text == null)
				{
					break;
				}
				if (IsPathRooted(text))
				{
					path = text;
					continue;
				}
				path = GetDirectoryName(path) + DirectorySeparatorChar + text;
				path = GetCanonicalPath(path);
			}
			return path;
		}

		internal static string ReadSymbolicLink(string path)
		{
			string text = TryReadLink(path);
			if (text == null)
			{
				Errno lastError = Stdlib.GetLastError();
				if (lastError != Errno.EINVAL)
				{
					UnixMarshal.ThrowExceptionForError(lastError);
				}
			}
			return text;
		}

		public static string TryReadLink(string path)
		{
			byte[] array = new byte[256];
			checked
			{
				long num;
				while (true)
				{
					num = Syscall.readlink(path, array);
					if (num < 0)
					{
						return null;
					}
					if (num != array.Length)
					{
						break;
					}
					array = new byte[array.LongLength * 2];
				}
				return UnixEncoding.Instance.GetString(array, 0, (int)num);
			}
		}

		public static string TryReadLinkAt(int dirfd, string path)
		{
			byte[] array = new byte[256];
			checked
			{
				long num;
				while (true)
				{
					num = Syscall.readlinkat(dirfd, path, array);
					if (num < 0)
					{
						return null;
					}
					if (num != array.Length)
					{
						break;
					}
					array = new byte[array.LongLength * 2];
				}
				return UnixEncoding.Instance.GetString(array, 0, (int)num);
			}
		}

		public static string ReadLink(string path)
		{
			string text = TryReadLink(path);
			if (text == null)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return text;
		}

		public static string ReadLinkAt(int dirfd, string path)
		{
			string text = TryReadLinkAt(dirfd, path);
			if (text == null)
			{
				UnixMarshal.ThrowExceptionForLastError();
			}
			return text;
		}

		public static bool IsPathRooted(string path)
		{
			if (path == null || path.Length == 0)
			{
				return false;
			}
			return path[0] == DirectorySeparatorChar;
		}

		internal static void CheckPath(string path)
		{
			if (path == null)
			{
				throw new ArgumentNullException();
			}
			if (path.Length == 0)
			{
				throw new ArgumentException("Path cannot contain a zero-length string", "path");
			}
			if (path.IndexOfAny(_InvalidPathChars) != -1)
			{
				throw new ArgumentException("Invalid characters in path.", "path");
			}
		}
	}
	public struct UnixPipes : IEquatable<UnixPipes>
	{
		public UnixStream Reading;

		public UnixStream Writing;

		public UnixPipes(UnixStream reading, UnixStream writing)
		{
			Reading = reading;
			Writing = writing;
		}

		public static UnixPipes CreatePipes()
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.pipe(out var reading, out var writing));
			return new UnixPipes(new UnixStream(reading), new UnixStream(writing));
		}

		public override bool Equals(object value)
		{
			if (value == null || value.GetType() != GetType())
			{
				return false;
			}
			UnixPipes unixPipes = (UnixPipes)value;
			if (Reading.Handle == unixPipes.Reading.Handle)
			{
				return Writing.Handle == unixPipes.Writing.Handle;
			}
			return false;
		}

		public bool Equals(UnixPipes value)
		{
			if (Reading.Handle == value.Reading.Handle)
			{
				return Writing.Handle == value.Writing.Handle;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return Reading.Handle.GetHashCode() ^ Writing.Handle.GetHashCode();
		}

		public static bool operator ==(UnixPipes lhs, UnixPipes rhs)
		{
			return lhs.Equals(rhs);
		}

		public static bool operator !=(UnixPipes lhs, UnixPipes rhs)
		{
			return !lhs.Equals(rhs);
		}
	}
	public sealed class UnixProcess
	{
		private int pid;

		public int Id => pid;

		public bool HasExited => Syscall.WIFEXITED(GetProcessStatus());

		public int ExitCode
		{
			get
			{
				if (!HasExited)
				{
					throw new InvalidOperationException(Locale.GetText("Process hasn't exited"));
				}
				return Syscall.WEXITSTATUS(GetProcessStatus());
			}
		}

		public bool HasSignaled => Syscall.WIFSIGNALED(GetProcessStatus());

		public Signum TerminationSignal
		{
			get
			{
				if (!HasSignaled)
				{
					throw new InvalidOperationException(Locale.GetText("Process wasn't terminated by a signal"));
				}
				return Syscall.WTERMSIG(GetProcessStatus());
			}
		}

		public bool HasStopped => Syscall.WIFSTOPPED(GetProcessStatus());

		public Signum StopSignal
		{
			get
			{
				if (!HasStopped)
				{
					throw new InvalidOperationException(Locale.GetText("Process isn't stopped"));
				}
				return Syscall.WSTOPSIG(GetProcessStatus());
			}
		}

		public int ProcessGroupId
		{
			get
			{
				return Syscall.getpgid(pid);
			}
			set
			{
				UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.setpgid(pid, value));
			}
		}

		public int SessionId
		{
			get
			{
				int num = Syscall.getsid(pid);
				UnixMarshal.ThrowExceptionForLastErrorIf(num);
				return num;
			}
		}

		internal UnixProcess(int pid)
		{
			this.pid = pid;
		}

		private int GetProcessStatus()
		{
			int status;
			int num = Syscall.waitpid(pid, out status, WaitOptions.WNOHANG | WaitOptions.WUNTRACED);
			UnixMarshal.ThrowExceptionForLastErrorIf(num);
			return num;
		}

		public static UnixProcess GetCurrentProcess()
		{
			return new UnixProcess(GetCurrentProcessId());
		}

		public static int GetCurrentProcessId()
		{
			return Syscall.getpid();
		}

		public void Kill()
		{
			Signal(Signum.SIGKILL);
		}

		[CLSCompliant(false)]
		public void Signal(Signum signal)
		{
			UnixMarshal.ThrowExceptionForLastErrorIf(Syscall.kill(pid, signal));
		}

		public void WaitForExit()
		{
			int num;
			do
			{
				num = Syscall.waitpid(pid, out var _, (WaitOptions)0);
			}
			while (UnixMarshal.ShouldRetrySyscall(num));
			UnixMarshal.ThrowExceptionForLastErrorIf(num);
		}
	}
	public class UnixSignal : WaitHandle
	{
		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		private delegate int Mono_Posix_RuntimeIsShuttingDown();

		[Map]
		private struct SignalInfo
		{
			public int signum;

			public int count;

			public int read_fd;

			public int write_fd;

			public int pipecnt;

			public int pipelock;

			public int have_handler;

			public IntPtr handler;
		}

		private int signum;

		private IntPtr signal_info;

		private static Mono_Posix_RuntimeIsShuttingDown ShuttingDown;

		public Signum Signum
		{
			get
			{
				if (IsRealTimeSignal)
				{
					throw new InvalidOperationException("This signal is a RealTimeSignum");
				}
				return NativeConvert.ToSignum(signum);
			}
		}

		public RealTimeSignum RealTimeSignum
		{
			get
			{
				if (!IsRealTimeSignal)
				{
					throw new InvalidOperationException("This signal is not a RealTimeSignum");
				}
				return NativeConvert.ToRealTimeSignum(signum - GetSIGRTMIN());
			}
		}

		public bool IsRealTimeSignal
		{
			get
			{
				AssertValid();
				int sIGRTMIN = GetSIGRTMIN();
				if (sIGRTMIN == -1)
				{
					return false;
				}
				return signum >= sIGRTMIN;
			}
		}

		private unsafe SignalInfo* Info
		{
			get
			{
				AssertValid();
				return (SignalInfo*)(void*)signal_info;
			}
		}

		public bool IsSet => Count > 0;

		public unsafe int Count
		{
			get
			{
				return Info->count;
			}
			set
			{
				Interlocked.Exchange(ref Info->count, value);
			}
		}

		static UnixSignal()
		{
			ShuttingDown = RuntimeShuttingDownCallback;
			Stdlib.VersionCheck();
		}

		public UnixSignal(Signum signum)
		{
			this.signum = NativeConvert.FromSignum(signum);
			signal_info = install(this.signum);
			if (signal_info == IntPtr.Zero)
			{
				throw new ArgumentException("Unable to handle signal", "signum");
			}
		}

		public UnixSignal(RealTimeSignum rtsig)
		{
			signum = NativeConvert.FromRealTimeSignum(rtsig);
			signal_info = install(signum);
			Errno lastError = Stdlib.GetLastError();
			if (signal_info == IntPtr.Zero)
			{
				if (lastError == Errno.EADDRINUSE)
				{
					throw new ArgumentException("Signal registered outside of Mono.Posix", "signum");
				}
				throw new ArgumentException("Unable to handle signal", "signum");
			}
		}

		[DllImport("MonoPosixHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Mono_Unix_UnixSignal_install", SetLastError = true)]
		private static extern IntPtr install(int signum);

		[DllImport("MonoPosixHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Mono_Unix_UnixSignal_uninstall")]
		private static extern int uninstall(IntPtr info);

		private static int RuntimeShuttingDownCallback()
		{
			if (!Environment.HasShutdownStarted)
			{
				return 0;
			}
			return 1;
		}

		[DllImport("MonoPosixHelper", CallingConvention = CallingConvention.Cdecl, EntryPoint = "Mono_Unix_UnixSignal_WaitAny")]
		private static extern int WaitAny(IntPtr[] infos, int count, int timeout, Mono_Posix_RuntimeIsShuttingDown shutting_down);

		[DllImport("MonoPosixHelper", CallingConvention = CallingConvention.Cd

BepInEx/core/Mono.Security.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration.Assemblies;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Mono.Math;
using Mono.Math.Prime;
using Mono.Math.Prime.Generator;
using Mono.Net.Security;
using Mono.Security.Cryptography;
using Mono.Security.X509;
using Mono.Security.X509.Extensions;
using Mono.Xml;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyCompany("MONO development team")]
[assembly: AssemblyCopyright("(c) 2003-2004 Various Authors")]
[assembly: AssemblyDescription("Mono.Security.dll")]
[assembly: AssemblyProduct("MONO CLI")]
[assembly: AssemblyTitle("Mono.Security.dll")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyDelaySign(true)]
[assembly: InternalsVisibleTo("System, PublicKey=00000000000000000400000000000000")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class AssemblyRef
{
	internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string EcmaPublicKey = "b77a5c561934e089";

	public const string FrameworkPublicKeyFull = "00000000000000000400000000000000";

	public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000";

	public const string MicrosoftPublicKey = "b03f5f7f11d50a3a";

	public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal sealed class Locale
{
	private Locale()
	{
	}

	public static string GetText(string msg)
	{
		return msg;
	}

	public static string GetText(string fmt, params object[] args)
	{
		return string.Format(fmt, args);
	}
}
namespace Mono.Xml
{
	[CLSCompliant(false)]
	public class MiniParser
	{
		public interface IReader
		{
			int Read();
		}

		public interface IAttrList
		{
			int Length { get; }

			bool IsEmpty { get; }

			string[] Names { get; }

			string[] Values { get; }

			string GetName(int i);

			string GetValue(int i);

			string GetValue(string name);

			void ChangeValue(string name, string newValue);
		}

		public interface IMutableAttrList : IAttrList
		{
			void Clear();

			void Add(string name, string value);

			void CopyFrom(IAttrList attrs);

			void Remove(int i);

			void Remove(string name);
		}

		public interface IHandler
		{
			void OnStartParsing(MiniParser parser);

			void OnStartElement(string name, IAttrList attrs);

			void OnEndElement(string name);

			void OnChars(string ch);

			void OnEndParsing(MiniParser parser);
		}

		public class HandlerAdapter : IHandler
		{
			public void OnStartParsing(MiniParser parser)
			{
			}

			public void OnStartElement(string name, IAttrList attrs)
			{
			}

			public void OnEndElement(string name)
			{
			}

			public void OnChars(string ch)
			{
			}

			public void OnEndParsing(MiniParser parser)
			{
			}
		}

		private enum CharKind : byte
		{
			LEFT_BR = 0,
			RIGHT_BR = 1,
			SLASH = 2,
			PI_MARK = 3,
			EQ = 4,
			AMP = 5,
			SQUOTE = 6,
			DQUOTE = 7,
			BANG = 8,
			LEFT_SQBR = 9,
			SPACE = 10,
			RIGHT_SQBR = 11,
			TAB = 12,
			CR = 13,
			EOL = 14,
			CHARS = 15,
			UNKNOWN = 31
		}

		private enum ActionCode : byte
		{
			START_ELEM = 0,
			END_ELEM = 1,
			END_NAME = 2,
			SET_ATTR_NAME = 3,
			SET_ATTR_VAL = 4,
			SEND_CHARS = 5,
			START_CDATA = 6,
			END_CDATA = 7,
			ERROR = 8,
			STATE_CHANGE = 9,
			FLUSH_CHARS_STATE_CHANGE = 10,
			ACC_CHARS_STATE_CHANGE = 11,
			ACC_CDATA = 12,
			PROC_CHAR_REF = 13,
			UNKNOWN = 15
		}

		public class AttrListImpl : IMutableAttrList, IAttrList
		{
			protected ArrayList names;

			protected ArrayList values;

			public int Length => names.Count;

			public bool IsEmpty => Length != 0;

			public string[] Names => names.ToArray(typeof(string)) as string[];

			public string[] Values => values.ToArray(typeof(string)) as string[];

			public AttrListImpl()
				: this(0)
			{
			}

			public AttrListImpl(int initialCapacity)
			{
				if (initialCapacity <= 0)
				{
					names = new ArrayList();
					values = new ArrayList();
				}
				else
				{
					names = new ArrayList(initialCapacity);
					values = new ArrayList(initialCapacity);
				}
			}

			public AttrListImpl(IAttrList attrs)
				: this(attrs?.Length ?? 0)
			{
				if (attrs != null)
				{
					CopyFrom(attrs);
				}
			}

			public string GetName(int i)
			{
				string result = null;
				if (i >= 0 && i < Length)
				{
					result = names[i] as string;
				}
				return result;
			}

			public string GetValue(int i)
			{
				string result = null;
				if (i >= 0 && i < Length)
				{
					result = values[i] as string;
				}
				return result;
			}

			public string GetValue(string name)
			{
				return GetValue(names.IndexOf(name));
			}

			public void ChangeValue(string name, string newValue)
			{
				int num = names.IndexOf(name);
				if (num >= 0 && num < Length)
				{
					values[num] = newValue;
				}
			}

			public void Clear()
			{
				names.Clear();
				values.Clear();
			}

			public void Add(string name, string value)
			{
				names.Add(name);
				values.Add(value);
			}

			public void Remove(int i)
			{
				if (i >= 0)
				{
					names.RemoveAt(i);
					values.RemoveAt(i);
				}
			}

			public void Remove(string name)
			{
				Remove(names.IndexOf(name));
			}

			public void CopyFrom(IAttrList attrs)
			{
				if (attrs != null && this == attrs)
				{
					Clear();
					int length = attrs.Length;
					for (int i = 0; i < length; i++)
					{
						Add(attrs.GetName(i), attrs.GetValue(i));
					}
				}
			}
		}

		public class XMLError : Exception
		{
			protected string descr;

			protected int line;

			protected int column;

			public int Line => line;

			public int Column => column;

			public XMLError()
				: this("Unknown")
			{
			}

			public XMLError(string descr)
				: this(descr, -1, -1)
			{
			}

			public XMLError(string descr, int line, int column)
				: base(descr)
			{
				this.descr = descr;
				this.line = line;
				this.column = column;
			}

			public override string ToString()
			{
				return $"{descr} @ (line = {line}, col = {column})";
			}
		}

		private static readonly int INPUT_RANGE = 13;

		private static readonly ushort[] tbl = new ushort[262]
		{
			2305, 43264, 63616, 10368, 6272, 14464, 18560, 22656, 26752, 34944,
			39040, 47232, 30848, 2177, 10498, 6277, 14595, 18561, 22657, 26753,
			35088, 39041, 43137, 47233, 30849, 64004, 4352, 43266, 64258, 2177,
			10369, 14465, 18561, 22657, 26753, 34945, 39041, 47233, 30849, 14597,
			2307, 10499, 6403, 18691, 22787, 26883, 35075, 39171, 43267, 47363,
			30979, 63747, 64260, 8710, 4615, 41480, 2177, 14465, 18561, 22657,
			26753, 34945, 39041, 47233, 30849, 6400, 2307, 10499, 14595, 18691,
			22787, 26883, 35075, 39171, 43267, 47363, 30979, 63747, 6400, 2177,
			10369, 14465, 18561, 22657, 26753, 34945, 39041, 43137, 47233, 30849,
			63617, 2561, 23818, 11274, 7178, 15370, 19466, 27658, 35850, 39946,
			43783, 48138, 31754, 64522, 64265, 8198, 4103, 43272, 2177, 14465,
			18561, 22657, 26753, 34945, 39041, 47233, 30849, 64265, 17163, 43276,
			2178, 10370, 6274, 14466, 22658, 26754, 34946, 39042, 47234, 30850,
			2317, 23818, 11274, 7178, 15370, 19466, 27658, 35850, 39946, 44042,
			48138, 31754, 64522, 26894, 30991, 43275, 2180, 10372, 6276, 14468,
			18564, 22660, 34948, 39044, 47236, 63620, 17163, 43276, 2178, 10370,
			6274, 14466, 22658, 26754, 34946, 39042, 47234, 30850, 63618, 9474,
			35088, 2182, 6278, 14470, 18566, 22662, 26758, 39046, 43142, 47238,
			30854, 63622, 25617, 23822, 2830, 11022, 6926, 15118, 19214, 35598,
			39694, 43790, 47886, 31502, 64270, 29713, 23823, 2831, 11023, 6927,
			15119, 19215, 27407, 35599, 39695, 43791, 47887, 64271, 38418, 6400,
			1555, 9747, 13843, 17939, 22035, 26131, 34323, 42515, 46611, 30227,
			62995, 8198, 4103, 43281, 64265, 2177, 14465, 18561, 22657, 26753,
			34945, 39041, 47233, 30849, 46858, 3090, 11282, 7186, 15378, 19474,
			23570, 27666, 35858, 39954, 44050, 31762, 64530, 3091, 11283, 7187,
			15379, 19475, 23571, 27667, 35859, 39955, 44051, 48147, 31763, 64531,
			65535, 65535
		};

		protected static string[] errors = new string[8] { "Expected element", "Invalid character in tag", "No '='", "Invalid character entity", "Invalid attr value", "Empty tag", "No end tag", "Bad entity ref" };

		protected int line;

		protected int col;

		protected int[] twoCharBuff;

		protected bool splitCData;

		public MiniParser()
		{
			twoCharBuff = new int[2];
			splitCData = false;
			Reset();
		}

		public void Reset()
		{
			line = 0;
			col = 0;
		}

		protected static bool StrEquals(string str, StringBuilder sb, int sbStart, int len)
		{
			if (len != str.Length)
			{
				return false;
			}
			for (int i = 0; i < len; i++)
			{
				if (str[i] != sb[sbStart + i])
				{
					return false;
				}
			}
			return true;
		}

		protected void FatalErr(string descr)
		{
			throw new XMLError(descr, line, col);
		}

		protected static int Xlat(int charCode, int state)
		{
			int num = state * INPUT_RANGE;
			int num2 = System.Math.Min(tbl.Length - num, INPUT_RANGE);
			while (--num2 >= 0)
			{
				ushort num3 = tbl[num];
				if (charCode == num3 >> 12)
				{
					return num3 & 0xFFF;
				}
				num++;
			}
			return 4095;
		}

		public void Parse(IReader reader, IHandler handler)
		{
			if (reader == null)
			{
				throw new ArgumentNullException("reader");
			}
			if (handler == null)
			{
				handler = new HandlerAdapter();
			}
			AttrListImpl attrListImpl = new AttrListImpl();
			string text = null;
			Stack stack = new Stack();
			string text2 = null;
			line = 1;
			col = 0;
			int num = 0;
			int num2 = 0;
			StringBuilder stringBuilder = new StringBuilder();
			bool flag = false;
			bool flag2 = false;
			bool flag3 = false;
			int num3 = 0;
			handler.OnStartParsing(this);
			while (true)
			{
				col++;
				num = reader.Read();
				if (num == -1)
				{
					break;
				}
				int num4 = "<>/?=&'\"![ ]\t\r\n".IndexOf((char)num) & 0xF;
				switch (num4)
				{
				case 13:
					continue;
				case 12:
					num4 = 10;
					break;
				}
				if (num4 == 14)
				{
					col = 0;
					line++;
					num4 = 10;
				}
				int num5 = Xlat(num4, num2);
				num2 = num5 & 0xFF;
				if (num == 10 && (num2 == 14 || num2 == 15))
				{
					continue;
				}
				num5 >>= 8;
				if (num2 >= 128)
				{
					if (num2 == 255)
					{
						FatalErr("State dispatch error.");
					}
					else
					{
						FatalErr(errors[num2 ^ 0x80]);
					}
				}
				switch (num5)
				{
				case 9:
					break;
				case 0:
					handler.OnStartElement(text2, attrListImpl);
					if (num != 47)
					{
						stack.Push(text2);
					}
					else
					{
						handler.OnEndElement(text2);
					}
					attrListImpl.Clear();
					break;
				case 1:
				{
					text2 = stringBuilder.ToString();
					stringBuilder = new StringBuilder();
					string text6 = null;
					if (stack.Count == 0 || text2 != (text6 = stack.Pop() as string))
					{
						if (text6 == null)
						{
							FatalErr("Tag stack underflow");
						}
						else
						{
							FatalErr($"Expected end tag '{text2}' but found '{text6}'");
						}
					}
					handler.OnEndElement(text2);
					break;
				}
				case 2:
					text2 = stringBuilder.ToString();
					stringBuilder = new StringBuilder();
					if (num != 47 && num != 62)
					{
						break;
					}
					goto case 0;
				case 3:
					text = stringBuilder.ToString();
					stringBuilder = new StringBuilder();
					break;
				case 4:
					if (text == null)
					{
						FatalErr("Internal error.");
					}
					attrListImpl.Add(text, stringBuilder.ToString());
					stringBuilder = new StringBuilder();
					text = null;
					break;
				case 5:
					handler.OnChars(stringBuilder.ToString());
					stringBuilder = new StringBuilder();
					break;
				case 6:
				{
					string text5 = "CDATA[";
					flag2 = false;
					flag3 = false;
					switch (num)
					{
					case 45:
						num = reader.Read();
						if (num != 45)
						{
							FatalErr("Invalid comment");
						}
						col++;
						flag2 = true;
						twoCharBuff[0] = -1;
						twoCharBuff[1] = -1;
						break;
					default:
						flag3 = true;
						num3 = 0;
						break;
					case 91:
					{
						for (int i = 0; i < text5.Length; i++)
						{
							if (reader.Read() != text5[i])
							{
								col += i + 1;
								break;
							}
						}
						col += text5.Length;
						flag = true;
						break;
					}
					}
					break;
				}
				case 7:
				{
					int num20 = 0;
					num = 93;
					while (true)
					{
						switch (num)
						{
						case 93:
							goto IL_033d;
						default:
						{
							for (int k = 0; k < num20; k++)
							{
								stringBuilder.Append(']');
							}
							stringBuilder.Append((char)num);
							num2 = 18;
							break;
						}
						case 62:
						{
							for (int j = 0; j < num20 - 2; j++)
							{
								stringBuilder.Append(']');
							}
							flag = false;
							break;
						}
						}
						break;
						IL_033d:
						num = reader.Read();
						num20++;
					}
					col += num20;
					break;
				}
				case 8:
					FatalErr($"Error {num2}");
					break;
				case 10:
					stringBuilder = new StringBuilder();
					if (num == 60)
					{
						break;
					}
					goto case 11;
				case 11:
					stringBuilder.Append((char)num);
					break;
				case 12:
					if (flag2)
					{
						if (num == 62 && twoCharBuff[0] == 45 && twoCharBuff[1] == 45)
						{
							flag2 = false;
							num2 = 0;
						}
						else
						{
							twoCharBuff[0] = twoCharBuff[1];
							twoCharBuff[1] = num;
						}
					}
					else if (flag3)
					{
						if (num == 60 || num == 62)
						{
							num3 ^= 1;
						}
						if (num == 62 && num3 != 0)
						{
							flag3 = false;
							num2 = 0;
						}
					}
					else
					{
						if (splitCData && stringBuilder.Length > 0 && flag)
						{
							handler.OnChars(stringBuilder.ToString());
							stringBuilder = new StringBuilder();
						}
						flag = false;
						stringBuilder.Append((char)num);
					}
					break;
				case 13:
				{
					num = reader.Read();
					int num6 = col + 1;
					if (num == 35)
					{
						int num7 = 10;
						int num8 = 0;
						int num9 = 0;
						num = reader.Read();
						num6++;
						if (num == 120)
						{
							num = reader.Read();
							num6++;
							num7 = 16;
						}
						NumberStyles style = ((num7 == 16) ? NumberStyles.HexNumber : NumberStyles.Integer);
						while (true)
						{
							int num10 = -1;
							if (char.IsNumber((char)num) || "abcdef".IndexOf(char.ToLower((char)num)) != -1)
							{
								try
								{
									num10 = int.Parse(new string((char)num, 1), style);
								}
								catch (FormatException)
								{
									num10 = -1;
								}
							}
							if (num10 == -1)
							{
								break;
							}
							num8 *= num7;
							num8 += num10;
							num9++;
							num = reader.Read();
							num6++;
						}
						if (num == 59 && num9 > 0)
						{
							stringBuilder.Append((char)num8);
						}
						else
						{
							FatalErr("Bad char ref");
						}
					}
					else
					{
						string text3 = "aglmopqstu";
						string text4 = "&'\"><";
						int num11 = 0;
						int num12 = 15;
						int num13 = 0;
						int length = stringBuilder.Length;
						while (true)
						{
							if (num11 != 15)
							{
								num11 = text3.IndexOf((char)num) & 0xF;
							}
							if (num11 == 15)
							{
								FatalErr(errors[7]);
							}
							stringBuilder.Append((char)num);
							int num14 = "U㾏侏ཟク\ue1f4⊙\ueeff\ueeffo"[num11];
							int num15 = (num14 >> 4) & 0xF;
							int num16 = num14 & 0xF;
							int num17 = num14 >> 12;
							int num18 = (num14 >> 8) & 0xF;
							num = reader.Read();
							num6++;
							num11 = 15;
							if (num15 != 15 && num == text3[num15])
							{
								if (num17 < 14)
								{
									num12 = num17;
								}
								num13 = 12;
							}
							else if (num16 != 15 && num == text3[num16])
							{
								if (num18 < 14)
								{
									num12 = num18;
								}
								num13 = 8;
							}
							else if (num == 59)
							{
								if (num12 != 15 && num13 != 0 && ((num14 >> num13) & 0xF) == 14)
								{
									break;
								}
								continue;
							}
							num11 = 0;
						}
						int num19 = num6 - col - 1;
						if (num19 > 0 && num19 < 5 && (StrEquals("amp", stringBuilder, length, num19) || StrEquals("apos", stringBuilder, length, num19) || StrEquals("quot", stringBuilder, length, num19) || StrEquals("lt", stringBuilder, length, num19) || StrEquals("gt", stringBuilder, length, num19)))
						{
							stringBuilder.Length = length;
							stringBuilder.Append(text4[num12]);
						}
						else
						{
							FatalErr(errors[7]);
						}
					}
					col = num6;
					break;
				}
				default:
					FatalErr($"Unexpected action code - {num5}.");
					break;
				}
			}
			if (num2 != 0)
			{
				FatalErr("Unexpected EOF");
			}
			handler.OnEndParsing(this);
		}
	}
	[CLSCompliant(false)]
	public class SecurityParser : MiniParser, MiniParser.IHandler, MiniParser.IReader
	{
		private SecurityElement root;

		private string xmldoc;

		private int pos;

		private SecurityElement current;

		private Stack stack;

		public SecurityParser()
		{
			stack = new Stack();
		}

		public void LoadXml(string xml)
		{
			root = null;
			xmldoc = xml;
			pos = 0;
			stack.Clear();
			Parse(this, this);
		}

		public SecurityElement ToXml()
		{
			return root;
		}

		public int Read()
		{
			if (pos >= xmldoc.Length)
			{
				return -1;
			}
			return xmldoc[pos++];
		}

		public void OnStartParsing(MiniParser parser)
		{
		}

		public void OnStartElement(string name, IAttrList attrs)
		{
			SecurityElement securityElement = new SecurityElement(name);
			if (root == null)
			{
				root = securityElement;
				current = securityElement;
			}
			else
			{
				((SecurityElement)stack.Peek()).AddChild(securityElement);
			}
			stack.Push(securityElement);
			current = securityElement;
			int length = attrs.Length;
			for (int i = 0; i < length; i++)
			{
				current.AddAttribute(attrs.GetName(i), SecurityElement.Escape(attrs.GetValue(i)));
			}
		}

		public void OnEndElement(string name)
		{
			current = (SecurityElement)stack.Pop();
		}

		public void OnChars(string ch)
		{
			current.Text = SecurityElement.Escape(ch);
		}

		public void OnEndParsing(MiniParser parser)
		{
		}
	}
}
namespace Mono.Security
{
	public class ASN1
	{
		private byte m_nTag;

		private byte[] m_aValue;

		private ArrayList elist;

		public int Count
		{
			get
			{
				if (elist == null)
				{
					return 0;
				}
				return elist.Count;
			}
		}

		public byte Tag => m_nTag;

		public int Length
		{
			get
			{
				if (m_aValue != null)
				{
					return m_aValue.Length;
				}
				return 0;
			}
		}

		public byte[] Value
		{
			get
			{
				if (m_aValue == null)
				{
					GetBytes();
				}
				return (byte[])m_aValue.Clone();
			}
			set
			{
				if (value != null)
				{
					m_aValue = (byte[])value.Clone();
				}
			}
		}

		public ASN1 this[int index]
		{
			get
			{
				try
				{
					if (elist == null || index >= elist.Count)
					{
						return null;
					}
					return (ASN1)elist[index];
				}
				catch (ArgumentOutOfRangeException)
				{
					return null;
				}
			}
		}

		public ASN1()
			: this(0, null)
		{
		}

		public ASN1(byte tag)
			: this(tag, null)
		{
		}

		public ASN1(byte tag, byte[] data)
		{
			m_nTag = tag;
			m_aValue = data;
		}

		public ASN1(byte[] data)
		{
			m_nTag = data[0];
			int num = 0;
			int num2 = data[1];
			if (num2 > 128)
			{
				num = num2 - 128;
				num2 = 0;
				for (int i = 0; i < num; i++)
				{
					num2 *= 256;
					num2 += data[i + 2];
				}
			}
			else if (num2 == 128)
			{
				throw new NotSupportedException("Undefined length encoding.");
			}
			m_aValue = new byte[num2];
			Buffer.BlockCopy(data, 2 + num, m_aValue, 0, num2);
			if ((m_nTag & 0x20) == 32)
			{
				int anPos = 0;
				Decode(m_aValue, ref anPos, m_aValue.Length);
			}
		}

		private bool CompareArray(byte[] array1, byte[] array2)
		{
			bool flag = array1.Length == array2.Length;
			if (flag)
			{
				for (int i = 0; i < array1.Length; i++)
				{
					if (array1[i] != array2[i])
					{
						return false;
					}
				}
			}
			return flag;
		}

		public bool Equals(byte[] asn1)
		{
			return CompareArray(GetBytes(), asn1);
		}

		public bool CompareValue(byte[] value)
		{
			return CompareArray(m_aValue, value);
		}

		public ASN1 Add(ASN1 asn1)
		{
			if (asn1 != null)
			{
				if (elist == null)
				{
					elist = new ArrayList();
				}
				elist.Add(asn1);
			}
			return asn1;
		}

		public virtual byte[] GetBytes()
		{
			byte[] array = null;
			if (Count > 0)
			{
				int num = 0;
				ArrayList arrayList = new ArrayList();
				foreach (ASN1 item in elist)
				{
					byte[] bytes = item.GetBytes();
					arrayList.Add(bytes);
					num += bytes.Length;
				}
				array = new byte[num];
				int num2 = 0;
				for (int i = 0; i < elist.Count; i++)
				{
					byte[] array2 = (byte[])arrayList[i];
					Buffer.BlockCopy(array2, 0, array, num2, array2.Length);
					num2 += array2.Length;
				}
			}
			else if (m_aValue != null)
			{
				array = m_aValue;
			}
			int num3 = 0;
			byte[] array3;
			if (array != null)
			{
				int num4 = array.Length;
				if (num4 > 127)
				{
					if (num4 <= 255)
					{
						array3 = new byte[3 + num4];
						Buffer.BlockCopy(array, 0, array3, 3, num4);
						num3 = 129;
						array3[2] = (byte)num4;
					}
					else if (num4 <= 65535)
					{
						array3 = new byte[4 + num4];
						Buffer.BlockCopy(array, 0, array3, 4, num4);
						num3 = 130;
						array3[2] = (byte)(num4 >> 8);
						array3[3] = (byte)num4;
					}
					else if (num4 <= 16777215)
					{
						array3 = new byte[5 + num4];
						Buffer.BlockCopy(array, 0, array3, 5, num4);
						num3 = 131;
						array3[2] = (byte)(num4 >> 16);
						array3[3] = (byte)(num4 >> 8);
						array3[4] = (byte)num4;
					}
					else
					{
						array3 = new byte[6 + num4];
						Buffer.BlockCopy(array, 0, array3, 6, num4);
						num3 = 132;
						array3[2] = (byte)(num4 >> 24);
						array3[3] = (byte)(num4 >> 16);
						array3[4] = (byte)(num4 >> 8);
						array3[5] = (byte)num4;
					}
				}
				else
				{
					array3 = new byte[2 + num4];
					Buffer.BlockCopy(array, 0, array3, 2, num4);
					num3 = num4;
				}
				if (m_aValue == null)
				{
					m_aValue = array;
				}
			}
			else
			{
				array3 = new byte[2];
			}
			array3[0] = m_nTag;
			array3[1] = (byte)num3;
			return array3;
		}

		protected void Decode(byte[] asn1, ref int anPos, int anLength)
		{
			while (anPos < anLength - 1)
			{
				DecodeTLV(asn1, ref anPos, out var tag, out var length, out var content);
				if (tag != 0)
				{
					ASN1 aSN = Add(new ASN1(tag, content));
					if ((tag & 0x20) == 32)
					{
						int anPos2 = anPos;
						aSN.Decode(asn1, ref anPos2, anPos2 + length);
					}
					anPos += length;
				}
			}
		}

		protected void DecodeTLV(byte[] asn1, ref int pos, out byte tag, out int length, out byte[] content)
		{
			tag = asn1[pos++];
			length = asn1[pos++];
			if ((length & 0x80) == 128)
			{
				int num = length & 0x7F;
				length = 0;
				for (int i = 0; i < num; i++)
				{
					length = length * 256 + asn1[pos++];
				}
			}
			content = new byte[length];
			Buffer.BlockCopy(asn1, pos, content, 0, length);
		}

		public ASN1 Element(int index, byte anTag)
		{
			try
			{
				if (elist == null || index >= elist.Count)
				{
					return null;
				}
				ASN1 aSN = (ASN1)elist[index];
				if (aSN.Tag == anTag)
				{
					return aSN;
				}
				return null;
			}
			catch (ArgumentOutOfRangeException)
			{
				return null;
			}
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendFormat("Tag: {0} {1}", m_nTag.ToString("X2"), Environment.NewLine);
			stringBuilder.AppendFormat("Length: {0} {1}", Value.Length, Environment.NewLine);
			stringBuilder.Append("Value: ");
			stringBuilder.Append(Environment.NewLine);
			for (int i = 0; i < Value.Length; i++)
			{
				stringBuilder.AppendFormat("{0} ", Value[i].ToString("X2"));
				if ((i + 1) % 16 == 0)
				{
					stringBuilder.AppendFormat(Environment.NewLine);
				}
			}
			return stringBuilder.ToString();
		}

		public void SaveToFile(string filename)
		{
			if (filename == null)
			{
				throw new ArgumentNullException("filename");
			}
			using FileStream fileStream = File.Create(filename);
			byte[] bytes = GetBytes();
			fileStream.Write(bytes, 0, bytes.Length);
		}
	}
	public static class ASN1Convert
	{
		public static ASN1 FromDateTime(DateTime dt)
		{
			if (dt.Year < 2050)
			{
				return new ASN1(23, Encoding.ASCII.GetBytes(dt.ToUniversalTime().ToString("yyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"));
			}
			return new ASN1(24, Encoding.ASCII.GetBytes(dt.ToUniversalTime().ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + "Z"));
		}

		public static ASN1 FromInt32(int value)
		{
			byte[] bytes = BitConverterLE.GetBytes(value);
			Array.Reverse(bytes);
			int i;
			for (i = 0; i < bytes.Length && bytes[i] == 0; i++)
			{
			}
			ASN1 aSN = new ASN1(2);
			switch (i)
			{
			case 0:
				aSN.Value = bytes;
				break;
			case 4:
				aSN.Value = new byte[1];
				break;
			default:
			{
				byte[] array = new byte[4 - i];
				Buffer.BlockCopy(bytes, i, array, 0, array.Length);
				aSN.Value = array;
				break;
			}
			}
			return aSN;
		}

		public static ASN1 FromOid(string oid)
		{
			if (oid == null)
			{
				throw new ArgumentNullException("oid");
			}
			return new ASN1(CryptoConfig.EncodeOID(oid));
		}

		public static ASN1 FromUnsignedBigInteger(byte[] big)
		{
			if (big == null)
			{
				throw new ArgumentNullException("big");
			}
			if (big[0] >= 128)
			{
				int num = big.Length + 1;
				byte[] array = new byte[num];
				Buffer.BlockCopy(big, 0, array, 1, num - 1);
				big = array;
			}
			return new ASN1(2, big);
		}

		public static int ToInt32(ASN1 asn1)
		{
			if (asn1 == null)
			{
				throw new ArgumentNullException("asn1");
			}
			if (asn1.Tag != 2)
			{
				throw new FormatException("Only integer can be converted");
			}
			int num = 0;
			for (int i = 0; i < asn1.Value.Length; i++)
			{
				num = (num << 8) + asn1.Value[i];
			}
			return num;
		}

		public static string ToOid(ASN1 asn1)
		{
			if (asn1 == null)
			{
				throw new ArgumentNullException("asn1");
			}
			byte[] value = asn1.Value;
			StringBuilder stringBuilder = new StringBuilder();
			byte b = (byte)(value[0] / 40);
			byte b2 = (byte)(value[0] % 40);
			if (b > 2)
			{
				b2 += (byte)((b - 2) * 40);
				b = 2;
			}
			stringBuilder.Append(b.ToString(CultureInfo.InvariantCulture));
			stringBuilder.Append(".");
			stringBuilder.Append(b2.ToString(CultureInfo.InvariantCulture));
			ulong num = 0uL;
			for (b = 1; b < value.Length; b++)
			{
				num = (num << 7) | (byte)(value[b] & 0x7Fu);
				if ((value[b] & 0x80) != 128)
				{
					stringBuilder.Append(".");
					stringBuilder.Append(num.ToString(CultureInfo.InvariantCulture));
					num = 0uL;
				}
			}
			return stringBuilder.ToString();
		}

		public static DateTime ToDateTime(ASN1 time)
		{
			if (time == null)
			{
				throw new ArgumentNullException("time");
			}
			string text = Encoding.ASCII.GetString(time.Value);
			string format = null;
			switch (text.Length)
			{
			case 11:
				format = "yyMMddHHmmZ";
				break;
			case 13:
				text = ((Convert.ToInt16(text.Substring(0, 2), CultureInfo.InvariantCulture) < 50) ? ("20" + text) : ("19" + text));
				format = "yyyyMMddHHmmssZ";
				break;
			case 15:
				format = "yyyyMMddHHmmssZ";
				break;
			case 17:
			{
				string text2 = ((Convert.ToInt16(text.Substring(0, 2), CultureInfo.InvariantCulture) >= 50) ? "19" : "20");
				char c = ((text[12] == '+') ? '-' : '+');
				text = $"{text2}{text.Substring(0, 12)}{c}{text[13]}{text[14]}:{text[15]}{text[16]}";
				format = "yyyyMMddHHmmsszzz";
				break;
			}
			}
			return DateTime.ParseExact(text, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);
		}
	}
	internal sealed class BitConverterLE
	{
		private BitConverterLE()
		{
		}

		private unsafe static byte[] GetUShortBytes(byte* bytes)
		{
			if (!BitConverter.IsLittleEndian)
			{
				return new byte[2]
				{
					bytes[1],
					*bytes
				};
			}
			return new byte[2]
			{
				*bytes,
				bytes[1]
			};
		}

		private unsafe static byte[] GetUIntBytes(byte* bytes)
		{
			if (!BitConverter.IsLittleEndian)
			{
				return new byte[4]
				{
					bytes[3],
					bytes[2],
					bytes[1],
					*bytes
				};
			}
			return new byte[4]
			{
				*bytes,
				bytes[1],
				bytes[2],
				bytes[3]
			};
		}

		private unsafe static byte[] GetULongBytes(byte* bytes)
		{
			if (!BitConverter.IsLittleEndian)
			{
				return new byte[8]
				{
					bytes[7],
					bytes[6],
					bytes[5],
					bytes[4],
					bytes[3],
					bytes[2],
					bytes[1],
					*bytes
				};
			}
			return new byte[8]
			{
				*bytes,
				bytes[1],
				bytes[2],
				bytes[3],
				bytes[4],
				bytes[5],
				bytes[6],
				bytes[7]
			};
		}

		internal static byte[] GetBytes(bool value)
		{
			return new byte[1] { (byte)(value ? 1 : 0) };
		}

		internal unsafe static byte[] GetBytes(char value)
		{
			return GetUShortBytes((byte*)(&value));
		}

		internal unsafe static byte[] GetBytes(short value)
		{
			return GetUShortBytes((byte*)(&value));
		}

		internal unsafe static byte[] GetBytes(int value)
		{
			return GetUIntBytes((byte*)(&value));
		}

		internal unsafe static byte[] GetBytes(long value)
		{
			return GetULongBytes((byte*)(&value));
		}

		internal unsafe static byte[] GetBytes(ushort value)
		{
			return GetUShortBytes((byte*)(&value));
		}

		internal unsafe static byte[] GetBytes(uint value)
		{
			return GetUIntBytes((byte*)(&value));
		}

		internal unsafe static byte[] GetBytes(ulong value)
		{
			return GetULongBytes((byte*)(&value));
		}

		internal unsafe static byte[] GetBytes(float value)
		{
			return GetUIntBytes((byte*)(&value));
		}

		internal unsafe static byte[] GetBytes(double value)
		{
			return GetULongBytes((byte*)(&value));
		}

		private unsafe static void UShortFromBytes(byte* dst, byte[] src, int startIndex)
		{
			if (BitConverter.IsLittleEndian)
			{
				*dst = src[startIndex];
				dst[1] = src[startIndex + 1];
			}
			else
			{
				*dst = src[startIndex + 1];
				dst[1] = src[startIndex];
			}
		}

		private unsafe static void UIntFromBytes(byte* dst, byte[] src, int startIndex)
		{
			if (BitConverter.IsLittleEndian)
			{
				*dst = src[startIndex];
				dst[1] = src[startIndex + 1];
				dst[2] = src[startIndex + 2];
				dst[3] = src[startIndex + 3];
			}
			else
			{
				*dst = src[startIndex + 3];
				dst[1] = src[startIndex + 2];
				dst[2] = src[startIndex + 1];
				dst[3] = src[startIndex];
			}
		}

		private unsafe static void ULongFromBytes(byte* dst, byte[] src, int startIndex)
		{
			if (BitConverter.IsLittleEndian)
			{
				for (int i = 0; i < 8; i++)
				{
					dst[i] = src[startIndex + i];
				}
			}
			else
			{
				for (int j = 0; j < 8; j++)
				{
					dst[j] = src[startIndex + (7 - j)];
				}
			}
		}

		internal static bool ToBoolean(byte[] value, int startIndex)
		{
			return value[startIndex] != 0;
		}

		internal unsafe static char ToChar(byte[] value, int startIndex)
		{
			char result = default(char);
			UShortFromBytes((byte*)(&result), value, startIndex);
			return result;
		}

		internal unsafe static short ToInt16(byte[] value, int startIndex)
		{
			short result = default(short);
			UShortFromBytes((byte*)(&result), value, startIndex);
			return result;
		}

		internal unsafe static int ToInt32(byte[] value, int startIndex)
		{
			int result = default(int);
			UIntFromBytes((byte*)(&result), value, startIndex);
			return result;
		}

		internal unsafe static long ToInt64(byte[] value, int startIndex)
		{
			long result = default(long);
			ULongFromBytes((byte*)(&result), value, startIndex);
			return result;
		}

		internal unsafe static ushort ToUInt16(byte[] value, int startIndex)
		{
			ushort result = default(ushort);
			UShortFromBytes((byte*)(&result), value, startIndex);
			return result;
		}

		internal unsafe static uint ToUInt32(byte[] value, int startIndex)
		{
			uint result = default(uint);
			UIntFromBytes((byte*)(&result), value, startIndex);
			return result;
		}

		internal unsafe static ulong ToUInt64(byte[] value, int startIndex)
		{
			ulong result = default(ulong);
			ULongFromBytes((byte*)(&result), value, startIndex);
			return result;
		}

		internal unsafe static float ToSingle(byte[] value, int startIndex)
		{
			float result = default(float);
			UIntFromBytes((byte*)(&result), value, startIndex);
			return result;
		}

		internal unsafe static double ToDouble(byte[] value, int startIndex)
		{
			double result = default(double);
			ULongFromBytes((byte*)(&result), value, startIndex);
			return result;
		}
	}
	public sealed class PKCS7
	{
		public class Oid
		{
			public const string rsaEncryption = "1.2.840.113549.1.1.1";

			public const string data = "1.2.840.113549.1.7.1";

			public const string signedData = "1.2.840.113549.1.7.2";

			public const string envelopedData = "1.2.840.113549.1.7.3";

			public const string signedAndEnvelopedData = "1.2.840.113549.1.7.4";

			public const string digestedData = "1.2.840.113549.1.7.5";

			public const string encryptedData = "1.2.840.113549.1.7.6";

			public const string contentType = "1.2.840.113549.1.9.3";

			public const string messageDigest = "1.2.840.113549.1.9.4";

			public const string signingTime = "1.2.840.113549.1.9.5";

			public const string countersignature = "1.2.840.113549.1.9.6";
		}

		public class ContentInfo
		{
			private string contentType;

			private ASN1 content;

			public ASN1 ASN1 => GetASN1();

			public ASN1 Content
			{
				get
				{
					return content;
				}
				set
				{
					content = value;
				}
			}

			public string ContentType
			{
				get
				{
					return contentType;
				}
				set
				{
					contentType = value;
				}
			}

			public ContentInfo()
			{
				content = new ASN1(160);
			}

			public ContentInfo(string oid)
				: this()
			{
				contentType = oid;
			}

			public ContentInfo(byte[] data)
				: this(new ASN1(data))
			{
			}

			public ContentInfo(ASN1 asn1)
			{
				if (asn1.Tag != 48 || (asn1.Count < 1 && asn1.Count > 2))
				{
					throw new ArgumentException("Invalid ASN1");
				}
				if (asn1[0].Tag != 6)
				{
					throw new ArgumentException("Invalid contentType");
				}
				contentType = ASN1Convert.ToOid(asn1[0]);
				if (asn1.Count > 1)
				{
					if (asn1[1].Tag != 160)
					{
						throw new ArgumentException("Invalid content");
					}
					content = asn1[1];
				}
			}

			internal ASN1 GetASN1()
			{
				ASN1 aSN = new ASN1(48);
				aSN.Add(ASN1Convert.FromOid(contentType));
				if (content != null && content.Count > 0)
				{
					aSN.Add(content);
				}
				return aSN;
			}

			public byte[] GetBytes()
			{
				return GetASN1().GetBytes();
			}
		}

		public class EncryptedData
		{
			private byte _version;

			private ContentInfo _content;

			private ContentInfo _encryptionAlgorithm;

			private byte[] _encrypted;

			public ASN1 ASN1 => GetASN1();

			public ContentInfo ContentInfo => _content;

			public ContentInfo EncryptionAlgorithm => _encryptionAlgorithm;

			public byte[] EncryptedContent
			{
				get
				{
					if (_encrypted == null)
					{
						return null;
					}
					return (byte[])_encrypted.Clone();
				}
			}

			public byte Version
			{
				get
				{
					return _version;
				}
				set
				{
					_version = value;
				}
			}

			public EncryptedData()
			{
				_version = 0;
			}

			public EncryptedData(byte[] data)
				: this(new ASN1(data))
			{
			}

			public EncryptedData(ASN1 asn1)
				: this()
			{
				if (asn1.Tag != 48 || asn1.Count < 2)
				{
					throw new ArgumentException("Invalid EncryptedData");
				}
				if (asn1[0].Tag != 2)
				{
					throw new ArgumentException("Invalid version");
				}
				_version = asn1[0].Value[0];
				ASN1 aSN = asn1[1];
				if (aSN.Tag != 48)
				{
					throw new ArgumentException("missing EncryptedContentInfo");
				}
				ASN1 aSN2 = aSN[0];
				if (aSN2.Tag != 6)
				{
					throw new ArgumentException("missing EncryptedContentInfo.ContentType");
				}
				_content = new ContentInfo(ASN1Convert.ToOid(aSN2));
				ASN1 aSN3 = aSN[1];
				if (aSN3.Tag != 48)
				{
					throw new ArgumentException("missing EncryptedContentInfo.ContentEncryptionAlgorithmIdentifier");
				}
				_encryptionAlgorithm = new ContentInfo(ASN1Convert.ToOid(aSN3[0]));
				_encryptionAlgorithm.Content = aSN3[1];
				ASN1 aSN4 = aSN[2];
				if (aSN4.Tag != 128)
				{
					throw new ArgumentException("missing EncryptedContentInfo.EncryptedContent");
				}
				_encrypted = aSN4.Value;
			}

			internal ASN1 GetASN1()
			{
				return null;
			}

			public byte[] GetBytes()
			{
				return GetASN1().GetBytes();
			}
		}

		public class EnvelopedData
		{
			private byte _version;

			private ContentInfo _content;

			private ContentInfo _encryptionAlgorithm;

			private ArrayList _recipientInfos;

			private byte[] _encrypted;

			public ArrayList RecipientInfos => _recipientInfos;

			public ASN1 ASN1 => GetASN1();

			public ContentInfo ContentInfo => _content;

			public ContentInfo EncryptionAlgorithm => _encryptionAlgorithm;

			public byte[] EncryptedContent
			{
				get
				{
					if (_encrypted == null)
					{
						return null;
					}
					return (byte[])_encrypted.Clone();
				}
			}

			public byte Version
			{
				get
				{
					return _version;
				}
				set
				{
					_version = value;
				}
			}

			public EnvelopedData()
			{
				_version = 0;
				_content = new ContentInfo();
				_encryptionAlgorithm = new ContentInfo();
				_recipientInfos = new ArrayList();
			}

			public EnvelopedData(byte[] data)
				: this(new ASN1(data))
			{
			}

			public EnvelopedData(ASN1 asn1)
				: this()
			{
				if (asn1[0].Tag != 48 || asn1[0].Count < 3)
				{
					throw new ArgumentException("Invalid EnvelopedData");
				}
				if (asn1[0][0].Tag != 2)
				{
					throw new ArgumentException("Invalid version");
				}
				_version = asn1[0][0].Value[0];
				ASN1 aSN = asn1[0][1];
				if (aSN.Tag != 49)
				{
					throw new ArgumentException("missing RecipientInfos");
				}
				for (int i = 0; i < aSN.Count; i++)
				{
					ASN1 data = aSN[i];
					_recipientInfos.Add(new RecipientInfo(data));
				}
				ASN1 aSN2 = asn1[0][2];
				if (aSN2.Tag != 48)
				{
					throw new ArgumentException("missing EncryptedContentInfo");
				}
				ASN1 aSN3 = aSN2[0];
				if (aSN3.Tag != 6)
				{
					throw new ArgumentException("missing EncryptedContentInfo.ContentType");
				}
				_content = new ContentInfo(ASN1Convert.ToOid(aSN3));
				ASN1 aSN4 = aSN2[1];
				if (aSN4.Tag != 48)
				{
					throw new ArgumentException("missing EncryptedContentInfo.ContentEncryptionAlgorithmIdentifier");
				}
				_encryptionAlgorithm = new ContentInfo(ASN1Convert.ToOid(aSN4[0]));
				_encryptionAlgorithm.Content = aSN4[1];
				ASN1 aSN5 = aSN2[2];
				if (aSN5.Tag != 128)
				{
					throw new ArgumentException("missing EncryptedContentInfo.EncryptedContent");
				}
				_encrypted = aSN5.Value;
			}

			internal ASN1 GetASN1()
			{
				return new ASN1(48);
			}

			public byte[] GetBytes()
			{
				return GetASN1().GetBytes();
			}
		}

		public class RecipientInfo
		{
			private int _version;

			private string _oid;

			private byte[] _key;

			private byte[] _ski;

			private string _issuer;

			private byte[] _serial;

			public string Oid => _oid;

			public byte[] Key
			{
				get
				{
					if (_key == null)
					{
						return null;
					}
					return (byte[])_key.Clone();
				}
			}

			public byte[] SubjectKeyIdentifier
			{
				get
				{
					if (_ski == null)
					{
						return null;
					}
					return (byte[])_ski.Clone();
				}
			}

			public string Issuer => _issuer;

			public byte[] Serial
			{
				get
				{
					if (_serial == null)
					{
						return null;
					}
					return (byte[])_serial.Clone();
				}
			}

			public int Version => _version;

			public RecipientInfo()
			{
			}

			public RecipientInfo(ASN1 data)
			{
				if (data.Tag != 48)
				{
					throw new ArgumentException("Invalid RecipientInfo");
				}
				ASN1 aSN = data[0];
				if (aSN.Tag != 2)
				{
					throw new ArgumentException("missing Version");
				}
				_version = aSN.Value[0];
				ASN1 aSN2 = data[1];
				if (aSN2.Tag == 128 && _version == 3)
				{
					_ski = aSN2.Value;
				}
				else
				{
					_issuer = X501.ToString(aSN2[0]);
					_serial = aSN2[1].Value;
				}
				ASN1 aSN3 = data[2];
				_oid = ASN1Convert.ToOid(aSN3[0]);
				ASN1 aSN4 = data[3];
				_key = aSN4.Value;
			}
		}

		public class SignedData
		{
			private byte version;

			private string hashAlgorithm;

			private ContentInfo contentInfo;

			private Mono.Security.X509.X509CertificateCollection certs;

			private ArrayList crls;

			private SignerInfo signerInfo;

			private bool mda;

			private bool signed;

			public ASN1 ASN1 => GetASN1();

			public Mono.Security.X509.X509CertificateCollection Certificates => certs;

			public ContentInfo ContentInfo => contentInfo;

			public ArrayList Crls => crls;

			public string HashName
			{
				get
				{
					return hashAlgorithm;
				}
				set
				{
					hashAlgorithm = value;
					signerInfo.HashName = value;
				}
			}

			public SignerInfo SignerInfo => signerInfo;

			public byte Version
			{
				get
				{
					return version;
				}
				set
				{
					version = value;
				}
			}

			public bool UseAuthenticatedAttributes
			{
				get
				{
					return mda;
				}
				set
				{
					mda = value;
				}
			}

			public SignedData()
			{
				version = 1;
				contentInfo = new ContentInfo();
				certs = new Mono.Security.X509.X509CertificateCollection();
				crls = new ArrayList();
				signerInfo = new SignerInfo();
				mda = true;
				signed = false;
			}

			public SignedData(byte[] data)
				: this(new ASN1(data))
			{
			}

			public SignedData(ASN1 asn1)
			{
				if (asn1[0].Tag != 48 || asn1[0].Count < 4)
				{
					throw new ArgumentException("Invalid SignedData");
				}
				if (asn1[0][0].Tag != 2)
				{
					throw new ArgumentException("Invalid version");
				}
				version = asn1[0][0].Value[0];
				contentInfo = new ContentInfo(asn1[0][2]);
				int num = 3;
				certs = new Mono.Security.X509.X509CertificateCollection();
				if (asn1[0][num].Tag == 160)
				{
					for (int i = 0; i < asn1[0][num].Count; i++)
					{
						certs.Add(new Mono.Security.X509.X509Certificate(asn1[0][num][i].GetBytes()));
					}
					num++;
				}
				crls = new ArrayList();
				if (asn1[0][num].Tag == 161)
				{
					for (int j = 0; j < asn1[0][num].Count; j++)
					{
						crls.Add(asn1[0][num][j].GetBytes());
					}
					num++;
				}
				if (asn1[0][num].Count > 0)
				{
					signerInfo = new SignerInfo(asn1[0][num]);
				}
				else
				{
					signerInfo = new SignerInfo();
				}
				if (signerInfo.HashName != null)
				{
					HashName = OidToName(signerInfo.HashName);
				}
				mda = signerInfo.AuthenticatedAttributes.Count > 0;
			}

			public bool VerifySignature(AsymmetricAlgorithm aa)
			{
				if (aa == null)
				{
					return false;
				}
				RSAPKCS1SignatureDeformatter rSAPKCS1SignatureDeformatter = new RSAPKCS1SignatureDeformatter(aa);
				rSAPKCS1SignatureDeformatter.SetHashAlgorithm(this.hashAlgorithm);
				HashAlgorithm hashAlgorithm = HashAlgorithm.Create(this.hashAlgorithm);
				byte[] signature = signerInfo.Signature;
				byte[] array = null;
				if (mda)
				{
					ASN1 aSN = new ASN1(49);
					foreach (ASN1 authenticatedAttribute in signerInfo.AuthenticatedAttributes)
					{
						aSN.Add(authenticatedAttribute);
					}
					array = hashAlgorithm.ComputeHash(aSN.GetBytes());
				}
				else
				{
					array = hashAlgorithm.ComputeHash(contentInfo.Content[0].Value);
				}
				if (array != null && signature != null)
				{
					return rSAPKCS1SignatureDeformatter.VerifySignature(array, signature);
				}
				return false;
			}

			internal string OidToName(string oid)
			{
				return oid switch
				{
					"1.3.14.3.2.26" => "SHA1", 
					"1.2.840.113549.2.2" => "MD2", 
					"1.2.840.113549.2.5" => "MD5", 
					"2.16.840.1.101.3.4.1" => "SHA256", 
					"2.16.840.1.101.3.4.2" => "SHA384", 
					"2.16.840.1.101.3.4.3" => "SHA512", 
					_ => oid, 
				};
			}

			internal ASN1 GetASN1()
			{
				ASN1 aSN = new ASN1(48);
				byte[] data = new byte[1] { version };
				aSN.Add(new ASN1(2, data));
				ASN1 aSN2 = aSN.Add(new ASN1(49));
				if (hashAlgorithm != null)
				{
					string oid = CryptoConfig.MapNameToOID(hashAlgorithm);
					aSN2.Add(AlgorithmIdentifier(oid));
				}
				ASN1 aSN3 = contentInfo.ASN1;
				aSN.Add(aSN3);
				if (!signed && hashAlgorithm != null)
				{
					if (mda)
					{
						ASN1 value = Attribute("1.2.840.113549.1.9.3", aSN3[0]);
						signerInfo.AuthenticatedAttributes.Add(value);
						byte[] data2 = HashAlgorithm.Create(hashAlgorithm).ComputeHash(aSN3[1][0].Value);
						ASN1 aSN4 = new ASN1(48);
						ASN1 value2 = Attribute("1.2.840.113549.1.9.4", aSN4.Add(new ASN1(4, data2)));
						signerInfo.AuthenticatedAttributes.Add(value2);
					}
					else
					{
						RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(signerInfo.Key);
						rSAPKCS1SignatureFormatter.SetHashAlgorithm(hashAlgorithm);
						byte[] rgbHash = HashAlgorithm.Create(hashAlgorithm).ComputeHash(aSN3[1][0].Value);
						signerInfo.Signature = rSAPKCS1SignatureFormatter.CreateSignature(rgbHash);
					}
					signed = true;
				}
				if (certs.Count > 0)
				{
					ASN1 aSN5 = aSN.Add(new ASN1(160));
					foreach (Mono.Security.X509.X509Certificate cert in certs)
					{
						aSN5.Add(new ASN1(cert.RawData));
					}
				}
				if (crls.Count > 0)
				{
					ASN1 aSN6 = aSN.Add(new ASN1(161));
					foreach (byte[] crl in crls)
					{
						aSN6.Add(new ASN1(crl));
					}
				}
				ASN1 aSN7 = aSN.Add(new ASN1(49));
				if (signerInfo.Key != null)
				{
					aSN7.Add(signerInfo.ASN1);
				}
				return aSN;
			}

			public byte[] GetBytes()
			{
				return GetASN1().GetBytes();
			}
		}

		public class SignerInfo
		{
			private byte version;

			private Mono.Security.X509.X509Certificate x509;

			private string hashAlgorithm;

			private AsymmetricAlgorithm key;

			private ArrayList authenticatedAttributes;

			private ArrayList unauthenticatedAttributes;

			private byte[] signature;

			private string issuer;

			private byte[] serial;

			private byte[] ski;

			public string IssuerName => issuer;

			public byte[] SerialNumber
			{
				get
				{
					if (serial == null)
					{
						return null;
					}
					return (byte[])serial.Clone();
				}
			}

			public byte[] SubjectKeyIdentifier
			{
				get
				{
					if (ski == null)
					{
						return null;
					}
					return (byte[])ski.Clone();
				}
			}

			public ASN1 ASN1 => GetASN1();

			public ArrayList AuthenticatedAttributes => authenticatedAttributes;

			public Mono.Security.X509.X509Certificate Certificate
			{
				get
				{
					return x509;
				}
				set
				{
					x509 = value;
				}
			}

			public string HashName
			{
				get
				{
					return hashAlgorithm;
				}
				set
				{
					hashAlgorithm = value;
				}
			}

			public AsymmetricAlgorithm Key
			{
				get
				{
					return key;
				}
				set
				{
					key = value;
				}
			}

			public byte[] Signature
			{
				get
				{
					if (signature == null)
					{
						return null;
					}
					return (byte[])signature.Clone();
				}
				set
				{
					if (value != null)
					{
						signature = (byte[])value.Clone();
					}
				}
			}

			public ArrayList UnauthenticatedAttributes => unauthenticatedAttributes;

			public byte Version
			{
				get
				{
					return version;
				}
				set
				{
					version = value;
				}
			}

			public SignerInfo()
			{
				version = 1;
				authenticatedAttributes = new ArrayList();
				unauthenticatedAttributes = new ArrayList();
			}

			public SignerInfo(byte[] data)
				: this(new ASN1(data))
			{
			}

			public SignerInfo(ASN1 asn1)
				: this()
			{
				if (asn1[0].Tag != 48 || asn1[0].Count < 5)
				{
					throw new ArgumentException("Invalid SignedData");
				}
				if (asn1[0][0].Tag != 2)
				{
					throw new ArgumentException("Invalid version");
				}
				version = asn1[0][0].Value[0];
				ASN1 aSN = asn1[0][1];
				if (aSN.Tag == 128 && version == 3)
				{
					ski = aSN.Value;
				}
				else
				{
					issuer = X501.ToString(aSN[0]);
					serial = aSN[1].Value;
				}
				ASN1 aSN2 = asn1[0][2];
				hashAlgorithm = ASN1Convert.ToOid(aSN2[0]);
				int num = 3;
				ASN1 aSN3 = asn1[0][num];
				if (aSN3.Tag == 160)
				{
					num++;
					for (int i = 0; i < aSN3.Count; i++)
					{
						authenticatedAttributes.Add(aSN3[i]);
					}
				}
				num++;
				ASN1 aSN4 = asn1[0][num++];
				if (aSN4.Tag == 4)
				{
					signature = aSN4.Value;
				}
				ASN1 aSN5 = asn1[0][num];
				if (aSN5 != null && aSN5.Tag == 161)
				{
					for (int j = 0; j < aSN5.Count; j++)
					{
						unauthenticatedAttributes.Add(aSN5[j]);
					}
				}
			}

			internal ASN1 GetASN1()
			{
				if (key == null || hashAlgorithm == null)
				{
					return null;
				}
				byte[] data = new byte[1] { version };
				ASN1 aSN = new ASN1(48);
				aSN.Add(new ASN1(2, data));
				aSN.Add(IssuerAndSerialNumber(x509));
				string oid = CryptoConfig.MapNameToOID(hashAlgorithm);
				aSN.Add(AlgorithmIdentifier(oid));
				ASN1 aSN2 = null;
				if (authenticatedAttributes.Count > 0)
				{
					aSN2 = aSN.Add(new ASN1(160));
					authenticatedAttributes.Sort(new SortedSet());
					foreach (ASN1 authenticatedAttribute in authenticatedAttributes)
					{
						aSN2.Add(authenticatedAttribute);
					}
				}
				if (key is RSA)
				{
					aSN.Add(AlgorithmIdentifier("1.2.840.113549.1.1.1"));
					if (aSN2 != null)
					{
						RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(key);
						rSAPKCS1SignatureFormatter.SetHashAlgorithm(hashAlgorithm);
						byte[] bytes = aSN2.GetBytes();
						bytes[0] = 49;
						byte[] rgbHash = HashAlgorithm.Create(hashAlgorithm).ComputeHash(bytes);
						signature = rSAPKCS1SignatureFormatter.CreateSignature(rgbHash);
					}
					aSN.Add(new ASN1(4, signature));
					if (unauthenticatedAttributes.Count > 0)
					{
						ASN1 aSN3 = aSN.Add(new ASN1(161));
						unauthenticatedAttributes.Sort(new SortedSet());
						foreach (ASN1 unauthenticatedAttribute in unauthenticatedAttributes)
						{
							aSN3.Add(unauthenticatedAttribute);
						}
					}
					return aSN;
				}
				if (key is DSA)
				{
					throw new NotImplementedException("not yet");
				}
				throw new CryptographicException("Unknown assymetric algorithm");
			}

			public byte[] GetBytes()
			{
				return GetASN1().GetBytes();
			}
		}

		internal class SortedSet : IComparer
		{
			public int Compare(object x, object y)
			{
				if (x == null)
				{
					if (y != null)
					{
						return -1;
					}
					return 0;
				}
				if (y == null)
				{
					return 1;
				}
				ASN1 obj = x as ASN1;
				ASN1 aSN = y as ASN1;
				if (obj == null || aSN == null)
				{
					throw new ArgumentException(Locale.GetText("Invalid objects."));
				}
				byte[] bytes = obj.GetBytes();
				byte[] bytes2 = aSN.GetBytes();
				for (int i = 0; i < bytes.Length && i != bytes2.Length; i++)
				{
					if (bytes[i] != bytes2[i])
					{
						if (bytes[i] >= bytes2[i])
						{
							return 1;
						}
						return -1;
					}
				}
				if (bytes.Length > bytes2.Length)
				{
					return 1;
				}
				if (bytes.Length < bytes2.Length)
				{
					return -1;
				}
				return 0;
			}
		}

		private PKCS7()
		{
		}

		public static ASN1 Attribute(string oid, ASN1 value)
		{
			ASN1 aSN = new ASN1(48);
			aSN.Add(ASN1Convert.FromOid(oid));
			aSN.Add(new ASN1(49)).Add(value);
			return aSN;
		}

		public static ASN1 AlgorithmIdentifier(string oid)
		{
			ASN1 aSN = new ASN1(48);
			aSN.Add(ASN1Convert.FromOid(oid));
			aSN.Add(new ASN1(5));
			return aSN;
		}

		public static ASN1 AlgorithmIdentifier(string oid, ASN1 parameters)
		{
			ASN1 aSN = new ASN1(48);
			aSN.Add(ASN1Convert.FromOid(oid));
			aSN.Add(parameters);
			return aSN;
		}

		public static ASN1 IssuerAndSerialNumber(Mono.Security.X509.X509Certificate x509)
		{
			ASN1 asn = null;
			ASN1 asn2 = null;
			ASN1 aSN = new ASN1(x509.RawData);
			int num = 0;
			bool flag = false;
			while (num < aSN[0].Count)
			{
				ASN1 aSN2 = aSN[0][num++];
				if (aSN2.Tag == 2)
				{
					asn2 = aSN2;
				}
				else if (aSN2.Tag == 48)
				{
					if (flag)
					{
						asn = aSN2;
						break;
					}
					flag = true;
				}
			}
			ASN1 aSN3 = new ASN1(48);
			aSN3.Add(asn);
			aSN3.Add(asn2);
			return aSN3;
		}
	}
	public sealed class StrongName
	{
		internal class StrongNameSignature
		{
			private byte[] hash;

			private byte[] signature;

			private uint signaturePosition;

			private uint signatureLength;

			private uint metadataPosition;

			private uint metadataLength;

			private byte cliFlag;

			private uint cliFlagPosition;

			public byte[] Hash
			{
				get
				{
					return hash;
				}
				set
				{
					hash = value;
				}
			}

			public byte[] Signature
			{
				get
				{
					return signature;
				}
				set
				{
					signature = value;
				}
			}

			public uint MetadataPosition
			{
				get
				{
					return metadataPosition;
				}
				set
				{
					metadataPosition = value;
				}
			}

			public uint MetadataLength
			{
				get
				{
					return metadataLength;
				}
				set
				{
					metadataLength = value;
				}
			}

			public uint SignaturePosition
			{
				get
				{
					return signaturePosition;
				}
				set
				{
					signaturePosition = value;
				}
			}

			public uint SignatureLength
			{
				get
				{
					return signatureLength;
				}
				set
				{
					signatureLength = value;
				}
			}

			public byte CliFlag
			{
				get
				{
					return cliFlag;
				}
				set
				{
					cliFlag = value;
				}
			}

			public uint CliFlagPosition
			{
				get
				{
					return cliFlagPosition;
				}
				set
				{
					cliFlagPosition = value;
				}
			}
		}

		internal enum StrongNameOptions
		{
			Metadata,
			Signature
		}

		private RSA rsa;

		private byte[] publicKey;

		private byte[] keyToken;

		private string tokenAlgorithm;

		public bool CanSign
		{
			get
			{
				if (rsa == null)
				{
					return false;
				}
				if (RSA is RSAManaged)
				{
					return !(rsa as RSAManaged).PublicOnly;
				}
				try
				{
					RSAParameters rSAParameters = rsa.ExportParameters(includePrivateParameters: true);
					return rSAParameters.D != null && rSAParameters.P != null && rSAParameters.Q != null;
				}
				catch (CryptographicException)
				{
					return false;
				}
			}
		}

		public RSA RSA
		{
			get
			{
				if (rsa == null)
				{
					rsa = RSA.Create();
				}
				return rsa;
			}
			set
			{
				rsa = value;
				InvalidateCache();
			}
		}

		public byte[] PublicKey
		{
			get
			{
				if (publicKey == null)
				{
					byte[] array = CryptoConvert.ToCapiKeyBlob(rsa, includePrivateKey: false);
					publicKey = new byte[32 + (rsa.KeySize >> 3)];
					publicKey[0] = array[4];
					publicKey[1] = array[5];
					publicKey[2] = array[6];
					publicKey[3] = array[7];
					publicKey[4] = 4;
					publicKey[5] = 128;
					publicKey[6] = 0;
					publicKey[7] = 0;
					byte[] bytes = BitConverterLE.GetBytes(publicKey.Length - 12);
					publicKey[8] = bytes[0];
					publicKey[9] = bytes[1];
					publicKey[10] = bytes[2];
					publicKey[11] = bytes[3];
					publicKey[12] = 6;
					Buffer.BlockCopy(array, 1, publicKey, 13, publicKey.Length - 13);
					publicKey[23] = 49;
				}
				return (byte[])publicKey.Clone();
			}
		}

		public byte[] PublicKeyToken
		{
			get
			{
				if (keyToken == null)
				{
					byte[] array = PublicKey;
					if (array == null)
					{
						return null;
					}
					byte[] array2 = GetHashAlgorithm(TokenAlgorithm).ComputeHash(array);
					keyToken = new byte[8];
					Buffer.BlockCopy(array2, array2.Length - 8, keyToken, 0, 8);
					Array.Reverse(keyToken, 0, 8);
				}
				return (byte[])keyToken.Clone();
			}
		}

		public string TokenAlgorithm
		{
			get
			{
				if (tokenAlgorithm == null)
				{
					tokenAlgorithm = "SHA1";
				}
				return tokenAlgorithm;
			}
			set
			{
				string text = value.ToUpper(CultureInfo.InvariantCulture);
				if (text == "SHA1" || text == "MD5")
				{
					tokenAlgorithm = value;
					InvalidateCache();
					return;
				}
				throw new ArgumentException("Unsupported hash algorithm for token");
			}
		}

		public StrongName()
		{
		}

		public StrongName(int keySize)
		{
			rsa = new RSAManaged(keySize);
		}

		public StrongName(byte[] data)
		{
			if (data == null)
			{
				throw new ArgumentNullException("data");
			}
			if (data.Length == 16)
			{
				int num = 0;
				int num2 = 0;
				while (num < data.Length)
				{
					num2 += data[num++];
				}
				if (num2 == 4)
				{
					publicKey = (byte[])data.Clone();
				}
			}
			else
			{
				RSA = CryptoConvert.FromCapiKeyBlob(data);
				if (rsa == null)
				{
					throw new ArgumentException("data isn't a correctly encoded RSA public key");
				}
			}
		}

		public StrongName(RSA rsa)
		{
			if (rsa == null)
			{
				throw new ArgumentNullException("rsa");
			}
			RSA = rsa;
		}

		private void InvalidateCache()
		{
			publicKey = null;
			keyToken = null;
		}

		private static HashAlgorithm GetHashAlgorithm(string algorithm)
		{
			return HashAlgorithm.Create(algorithm);
		}

		public byte[] GetBytes()
		{
			return CryptoConvert.ToCapiPrivateKeyBlob(RSA);
		}

		private uint RVAtoPosition(uint r, int sections, byte[] headers)
		{
			for (int i = 0; i < sections; i++)
			{
				uint num = BitConverterLE.ToUInt32(headers, i * 40 + 20);
				uint num2 = BitConverterLE.ToUInt32(headers, i * 40 + 12);
				int num3 = (int)BitConverterLE.ToUInt32(headers, i * 40 + 8);
				if (num2 <= r && r < num2 + num3)
				{
					return num + r - num2;
				}
			}
			return 0u;
		}

		private static StrongNameSignature Error(string a)
		{
			return null;
		}

		private static byte[] ReadMore(Stream stream, byte[] a, int newSize)
		{
			int num = a.Length;
			Array.Resize(ref a, newSize);
			if (newSize <= num)
			{
				return a;
			}
			int num2 = newSize - num;
			if (stream.Read(a, num, num2) != num2)
			{
				return null;
			}
			return a;
		}

		internal StrongNameSignature StrongHash(Stream stream, StrongNameOptions options)
		{
			byte[] array = new byte[64];
			int num = 0;
			int num2 = stream.Read(array, 0, 64);
			if (num2 == 64 && array[0] == 77 && array[1] == 90)
			{
				num = BitConverterLE.ToInt32(array, 60);
				if (num < 64)
				{
					return Error("peHeader_lt_64");
				}
				array = ReadMore(stream, array, num);
				if (array == null)
				{
					return Error("read_mz2_failed");
				}
			}
			else
			{
				if (num2 < 4 || array[0] != 80 || array[1] != 69 || array[2] != 0 || array[3] != 0)
				{
					return Error("read_mz_or_mzsig_failed");
				}
				stream.Position = 0L;
				array = new byte[0];
			}
			int num3 = 2;
			int num4 = 24 + num3;
			byte[] array2 = new byte[num4];
			if (stream.Read(array2, 0, num4) != num4 || array2[0] != 80 || array2[1] != 69 || array2[2] != 0 || array2[3] != 0)
			{
				return Error("read_minimumHeadersSize_or_pesig_failed");
			}
			num3 = BitConverterLE.ToUInt16(array2, 20);
			if (num3 < 2)
			{
				return Error($"sizeOfOptionalHeader_lt_2 ${num3}");
			}
			int num5 = 24 + num3;
			if (num5 < 24)
			{
				return Error("headers_overflow");
			}
			array2 = ReadMore(stream, array2, num5);
			if (array2 == null)
			{
				return Error("read_pe2_failed");
			}
			uint num6 = BitConverterLE.ToUInt16(array2, 24);
			int num7 = 0;
			bool flag = false;
			switch (num6)
			{
			case 523u:
				num7 = 16;
				break;
			case 263u:
				flag = true;
				break;
			default:
				return Error("bad_magic_value");
			case 267u:
				break;
			}
			uint num8 = 0u;
			if (!flag)
			{
				if (num3 >= 116 + num7 + 4)
				{
					num8 = BitConverterLE.ToUInt32(array2, 116 + num7);
				}
				for (int i = 64; i < num3 && i < 68; i++)
				{
					array2[24 + i] = 0;
				}
				for (int j = 128 + num7; j < num3 && j < 136 + num7; j++)
				{
					array2[24 + j] = 0;
				}
			}
			int num9 = BitConverterLE.ToUInt16(array2, 6);
			byte[] array3 = new byte[num9 * 40];
			if (stream.Read(array3, 0, array3.Length) != array3.Length)
			{
				return Error("read_section_headers_failed");
			}
			uint num10 = 0u;
			uint num11 = 0u;
			uint num12 = 0u;
			uint num13 = 0u;
			if (15 < num8 && num3 >= 216 + num7)
			{
				uint r = BitConverterLE.ToUInt32(array2, 232 + num7);
				uint num14 = RVAtoPosition(r, num9, array3);
				int num15 = BitConverterLE.ToInt32(array2, 236 + num7);
				byte[] array4 = new byte[num15];
				stream.Position = num14;
				if (stream.Read(array4, 0, num15) != num15)
				{
					return Error("read_cli_header_failed");
				}
				uint r2 = BitConverterLE.ToUInt32(array4, 32);
				num10 = RVAtoPosition(r2, num9, array3);
				num11 = BitConverterLE.ToUInt32(array4, 36);
				uint r3 = BitConverterLE.ToUInt32(array4, 8);
				num12 = RVAtoPosition(r3, num9, array3);
				num13 = BitConverterLE.ToUInt32(array4, 12);
			}
			StrongNameSignature strongNameSignature = new StrongNameSignature();
			strongNameSignature.SignaturePosition = num10;
			strongNameSignature.SignatureLength = num11;
			strongNameSignature.MetadataPosition = num12;
			strongNameSignature.MetadataLength = num13;
			using HashAlgorithm hashAlgorithm = HashAlgorithm.Create(TokenAlgorithm);
			if (options == StrongNameOptions.Metadata)
			{
				hashAlgorithm.Initialize();
				byte[] buffer = new byte[num13];
				stream.Position = num12;
				if (stream.Read(buffer, 0, (int)num13) != (int)num13)
				{
					return Error("read_cli_metadata_failed");
				}
				strongNameSignature.Hash = hashAlgorithm.ComputeHash(buffer);
				return strongNameSignature;
			}
			using (CryptoStream cryptoStream = new CryptoStream(Stream.Null, hashAlgorithm, CryptoStreamMode.Write))
			{
				cryptoStream.Write(array, 0, array.Length);
				cryptoStream.Write(array2, 0, array2.Length);
				cryptoStream.Write(array3, 0, array3.Length);
				for (int k = 0; k < num9; k++)
				{
					uint num16 = BitConverterLE.ToUInt32(array3, k * 40 + 20);
					int num17 = BitConverterLE.ToInt32(array3, k * 40 + 16);
					byte[] array5 = new byte[num17];
					stream.Position = num16;
					if (stream.Read(array5, 0, num17) != num17)
					{
						return Error("read_section_failed");
					}
					if (num16 <= num10 && num10 < (uint)((int)num16 + num17))
					{
						int num18 = (int)(num10 - num16);
						if (num18 > 0)
						{
							cryptoStream.Write(array5, 0, num18);
						}
						strongNameSignature.Signature = new byte[num11];
						Buffer.BlockCopy(array5, num18, strongNameSignature.Signature, 0, (int)num11);
						Array.Reverse(strongNameSignature.Signature);
						int num19 = (int)(num18 + num11);
						int num20 = num17 - num19;
						if (num20 > 0)
						{
							cryptoStream.Write(array5, num19, num20);
						}
					}
					else
					{
						cryptoStream.Write(array5, 0, num17);
					}
				}
			}
			strongNameSignature.Hash = hashAlgorithm.Hash;
			return strongNameSignature;
		}

		public byte[] Hash(string fileName)
		{
			using FileStream stream = File.OpenRead(fileName);
			return StrongHash(stream, StrongNameOptions.Metadata).Hash;
		}

		public bool Sign(string fileName)
		{
			StrongNameSignature strongNameSignature;
			using (FileStream stream = File.OpenRead(fileName))
			{
				strongNameSignature = StrongHash(stream, StrongNameOptions.Signature);
			}
			if (strongNameSignature.Hash == null)
			{
				return false;
			}
			byte[] array = null;
			try
			{
				RSAPKCS1SignatureFormatter rSAPKCS1SignatureFormatter = new RSAPKCS1SignatureFormatter(rsa);
				rSAPKCS1SignatureFormatter.SetHashAlgorithm(TokenAlgorithm);
				array = rSAPKCS1SignatureFormatter.CreateSignature(strongNameSignature.Hash);
				Array.Reverse(array);
			}
			catch (CryptographicException)
			{
				return false;
			}
			using (FileStream fileStream = File.OpenWrite(fileName))
			{
				fileStream.Position = strongNameSignature.SignaturePosition;
				fileStream.Write(array, 0, array.Length);
			}
			return true;
		}

		public bool Verify(string fileName)
		{
			using FileStream stream = File.OpenRead(fileName);
			return Verify(stream);
		}

		public bool Verify(Stream stream)
		{
			StrongNameSignature strongNameSignature = StrongHash(stream, StrongNameOptions.Signature);
			if (strongNameSignature.Hash == null)
			{
				return false;
			}
			try
			{
				AssemblyHashAlgorithm algorithm = AssemblyHashAlgorithm.SHA1;
				if (tokenAlgorithm == "MD5")
				{
					algorithm = AssemblyHashAlgorithm.MD5;
				}
				return Verify(rsa, algorithm, strongNameSignature.Hash, strongNameSignature.Signature);
			}
			catch (CryptographicException)
			{
				return false;
			}
		}

		private static bool Verify(RSA rsa, AssemblyHashAlgorithm algorithm, byte[] hash, byte[] signature)
		{
			RSAPKCS1SignatureDeformatter rSAPKCS1SignatureDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
			switch (algorithm)
			{
			case AssemblyHashAlgorithm.MD5:
				rSAPKCS1SignatureDeformatter.SetHashAlgorithm("MD5");
				break;
			default:
				rSAPKCS1SignatureDeformatter.SetHashAlgorithm("SHA1");
				break;
			}
			return rSAPKCS1SignatureDeformatter.VerifySignature(hash, signature);
		}
	}
}
namespace Mono.Security.X509
{
	public class PKCS5
	{
		public const string pbeWithMD2AndDESCBC = "1.2.840.113549.1.5.1";

		public const string pbeWithMD5AndDESCBC = "1.2.840.113549.1.5.3";

		public const string pbeWithMD2AndRC2CBC = "1.2.840.113549.1.5.4";

		public const string pbeWithMD5AndRC2CBC = "1.2.840.113549.1.5.6";

		public const string pbeWithSHA1AndDESCBC = "1.2.840.113549.1.5.10";

		public const string pbeWithSHA1AndRC2CBC = "1.2.840.113549.1.5.11";
	}
	public class PKCS9
	{
		public const string friendlyName = "1.2.840.113549.1.9.20";

		public const string localKeyId = "1.2.840.113549.1.9.21";
	}
	internal class SafeBag
	{
		private string _bagOID;

		private ASN1 _asn1;

		public string BagOID => _bagOID;

		public ASN1 ASN1 => _asn1;

		public SafeBag(string bagOID, ASN1 asn1)
		{
			_bagOID = bagOID;
			_asn1 = asn1;
		}
	}
	public class PKCS12 : ICloneable
	{
		public class DeriveBytes
		{
			public enum Purpose
			{
				Key,
				IV,
				MAC
			}

			private static byte[] keyDiversifier = new byte[64]
			{
				1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
				1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
				1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
				1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
				1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
				1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
				1, 1, 1, 1
			};

			private static byte[] ivDiversifier = new byte[64]
			{
				2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
				2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
				2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
				2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
				2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
				2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
				2, 2, 2, 2
			};

			private static byte[] macDiversifier = new byte[64]
			{
				3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
				3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
				3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
				3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
				3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
				3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
				3, 3, 3, 3
			};

			private string _hashName;

			private int _iterations;

			private byte[] _password;

			private byte[] _salt;

			public string HashName
			{
				get
				{
					return _hashName;
				}
				set
				{
					_hashName = value;
				}
			}

			public int IterationCount
			{
				get
				{
					return _iterations;
				}
				set
				{
					_iterations = value;
				}
			}

			public byte[] Password
			{
				get
				{
					return (byte[])_password.Clone();
				}
				set
				{
					if (value == null)
					{
						_password = new byte[0];
					}
					else
					{
						_password = (byte[])value.Clone();
					}
				}
			}

			public byte[] Salt
			{
				get
				{
					return (byte[])_salt.Clone();
				}
				set
				{
					if (value != null)
					{
						_salt = (byte[])value.Clone();
					}
					else
					{
						_salt = null;
					}
				}
			}

			private void Adjust(byte[] a, int aOff, byte[] b)
			{
				int num = (b[^1] & 0xFF) + (a[aOff + b.Length - 1] & 0xFF) + 1;
				a[aOff + b.Length - 1] = (byte)num;
				num >>= 8;
				for (int num2 = b.Length - 2; num2 >= 0; num2--)
				{
					num += (b[num2] & 0xFF) + (a[aOff + num2] & 0xFF);
					a[aOff + num2] = (byte)num;
					num >>= 8;
				}
			}

			private byte[] Derive(byte[] diversifier, int n)
			{
				HashAlgorithm hashAlgorithm = PKCS1.CreateFromName(_hashName);
				int num = hashAlgorithm.HashSize >> 3;
				int num2 = 64;
				byte[] array = new byte[n];
				byte[] array2;
				if (_salt != null && _salt.Length != 0)
				{
					array2 = new byte[num2 * ((_salt.Length + num2 - 1) / num2)];
					for (int i = 0; i != array2.Length; i++)
					{
						array2[i] = _salt[i % _salt.Length];
					}
				}
				else
				{
					array2 = new byte[0];
				}
				byte[] array3;
				if (_password != null && _password.Length != 0)
				{
					array3 = new byte[num2 * ((_password.Length + num2 - 1) / num2)];
					for (int j = 0; j != array3.Length; j++)
					{
						array3[j] = _password[j % _password.Length];
					}
				}
				else
				{
					array3 = new byte[0];
				}
				byte[] array4 = new byte[array2.Length + array3.Length];
				Buffer.BlockCopy(array2, 0, array4, 0, array2.Length);
				Buffer.BlockCopy(array3, 0, array4, array2.Length, array3.Length);
				byte[] array5 = new byte[num2];
				int num3 = (n + num - 1) / num;
				for (int k = 1; k <= num3; k++)
				{
					hashAlgorithm.TransformBlock(diversifier, 0, diversifier.Length, diversifier, 0);
					hashAlgorithm.TransformFinalBlock(array4, 0, array4.Length);
					byte[] array6 = hashAlgorithm.Hash;
					hashAlgorithm.Initialize();
					for (int l = 1; l != _iterations; l++)
					{
						array6 = hashAlgorithm.ComputeHash(array6, 0, array6.Length);
					}
					for (int m = 0; m != array5.Length; m++)
					{
						array5[m] = array6[m % array6.Length];
					}
					for (int num4 = 0; num4 != array4.Length / num2; num4++)
					{
						Adjust(array4, num4 * num2, array5);
					}
					if (k == num3)
					{
						Buffer.BlockCopy(array6, 0, array, (k - 1) * num, array.Length - (k - 1) * num);
					}
					else
					{
						Buffer.BlockCopy(array6, 0, array, (k - 1) * num, array6.Length);
					}
				}
				return array;
			}

			public byte[] DeriveKey(int size)
			{
				return Derive(keyDiversifier, size);
			}

			public byte[] DeriveIV(int size)
			{
				return Derive(ivDiversifier, size);
			}

			public byte[] DeriveMAC(int size)
			{
				return Derive(macDiversifier, size);
			}
		}

		public const string pbeWithSHAAnd128BitRC4 = "1.2.840.113549.1.12.1.1";

		public const string pbeWithSHAAnd40BitRC4 = "1.2.840.113549.1.12.1.2";

		public const string pbeWithSHAAnd3KeyTripleDESCBC = "1.2.840.113549.1.12.1.3";

		public const string pbeWithSHAAnd2KeyTripleDESCBC = "1.2.840.113549.1.12.1.4";

		public const string pbeWithSHAAnd128BitRC2CBC = "1.2.840.113549.1.12.1.5";

		public const string pbeWithSHAAnd40BitRC2CBC = "1.2.840.113549.1.12.1.6";

		public const string keyBag = "1.2.840.113549.1.12.10.1.1";

		public const string pkcs8ShroudedKeyBag = "1.2.840.113549.1.12.10.1.2";

		public const string certBag = "1.2.840.113549.1.12.10.1.3";

		public const string crlBag = "1.2.840.113549.1.12.10.1.4";

		public const string secretBag = "1.2.840.113549.1.12.10.1.5";

		public const string safeContentsBag = "1.2.840.113549.1.12.10.1.6";

		public const string x509Certificate = "1.2.840.113549.1.9.22.1";

		public const string sdsiCertificate = "1.2.840.113549.1.9.22.2";

		public const string x509Crl = "1.2.840.113549.1.9.23.1";

		private const int recommendedIterationCount = 2000;

		private byte[] _password;

		private ArrayList _keyBags;

		private ArrayList _secretBags;

		private X509CertificateCollection _certs;

		private bool _keyBagsChanged;

		private bool _secretBagsChanged;

		private bool _certsChanged;

		private int _iterations;

		private ArrayList _safeBags;

		private RandomNumberGenerator _rng;

		public const int CryptoApiPasswordLimit = 32;

		private static int password_max_length = int.MaxValue;

		public string Password
		{
			set
			{
				if (_password != null)
				{
					Array.Clear(_password, 0, _password.Length);
				}
				_password = null;
				if (value == null)
				{
					return;
				}
				if (value.Length > 0)
				{
					int num = value.Length;
					int num2 = 0;
					if (num < MaximumPasswordLength)
					{
						if (value[num - 1] != 0)
						{
							num2 = 1;
						}
					}
					else
					{
						num = MaximumPasswordLength;
					}
					_password = new byte[num + num2 << 1];
					Encoding.BigEndianUnicode.GetBytes(value, 0, num, _password, 0);
				}
				else
				{
					_password = new byte[2];
				}
			}
		}

		public int IterationCount
		{
			get
			{
				return _iterations;
			}
			set
			{
				_iterations = value;
			}
		}

		public ArrayList Keys
		{
			get
			{
				if (_keyBagsChanged)
				{
					_keyBags.Clear();
					foreach (SafeBag safeBag in _safeBags)
					{
						if (safeBag.BagOID.Equals("1.2.840.113549.1.12.10.1.1"))
						{
							byte[] privateKey = new PKCS8.PrivateKeyInfo(safeBag.ASN1[1].Value).PrivateKey;
							switch (privateKey[0])
							{
							case 2:
								_keyBags.Add(PKCS8.PrivateKeyInfo.DecodeDSA(privateKey, default(DSAParameters)));
								break;
							case 48:
								_keyBags.Add(PKCS8.PrivateKeyInfo.DecodeRSA(privateKey));
								break;
							}
							Array.Clear(privateKey, 0, privateKey.Length);
						}
						else if (safeBag.BagOID.Equals("1.2.840.113549.1.12.10.1.2"))
						{
							PKCS8.EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new PKCS8.EncryptedPrivateKeyInfo(safeBag.ASN1[1].Value);
							byte[] array = Decrypt(encryptedPrivateKeyInfo.Algorithm, encryptedPrivateKeyInfo.Salt, encryptedPrivateKeyInfo.IterationCount, encryptedPrivateKeyInfo.EncryptedData);
							byte[] privateKey2 = new PKCS8.PrivateKeyInfo(array).PrivateKey;
							switch (privateKey2[0])
							{
							case 2:
								_keyBags.Add(PKCS8.PrivateKeyInfo.DecodeDSA(privateKey2, default(DSAParameters)));
								break;
							case 48:
								_keyBags.Add(PKCS8.PrivateKeyInfo.DecodeRSA(privateKey2));
								break;
							}
							Array.Clear(privateKey2, 0, privateKey2.Length);
							Array.Clear(array, 0, array.Length);
						}
					}
					_keyBagsChanged = false;
				}
				return ArrayList.ReadOnly(_keyBags);
			}
		}

		public ArrayList Secrets
		{
			get
			{
				if (_secretBagsChanged)
				{
					_secretBags.Clear();
					foreach (SafeBag safeBag in _safeBags)
					{
						if (safeBag.BagOID.Equals("1.2.840.113549.1.12.10.1.5"))
						{
							byte[] value = safeBag.ASN1[1].Value;
							_secretBags.Add(value);
						}
					}
					_secretBagsChanged = false;
				}
				return ArrayList.ReadOnly(_secretBags);
			}
		}

		public X509CertificateCollection Certificates
		{
			get
			{
				if (_certsChanged)
				{
					_certs.Clear();
					foreach (SafeBag safeBag in _safeBags)
					{
						if (safeBag.BagOID.Equals("1.2.840.113549.1.12.10.1.3"))
						{
							PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(safeBag.ASN1[1].Value);
							_certs.Add(new X509Certificate(contentInfo.Content[0].Value));
						}
					}
					_certsChanged = false;
				}
				return _certs;
			}
		}

		internal RandomNumberGenerator RNG
		{
			get
			{
				if (_rng == null)
				{
					_rng = RandomNumberGenerator.Create();
				}
				return _rng;
			}
		}

		public static int MaximumPasswordLength
		{
			get
			{
				return password_max_length;
			}
			set
			{
				if (value < 32)
				{
					throw new ArgumentOutOfRangeException(Locale.GetText("Maximum password length cannot be less than {0}.", 32));
				}
				password_max_length = value;
			}
		}

		public PKCS12()
		{
			_iterations = 2000;
			_keyBags = new ArrayList();
			_secretBags = new ArrayList();
			_certs = new X509CertificateCollection();
			_keyBagsChanged = false;
			_secretBagsChanged = false;
			_certsChanged = false;
			_safeBags = new ArrayList();
		}

		public PKCS12(byte[] data)
			: this()
		{
			Password = null;
			Decode(data);
		}

		public PKCS12(byte[] data, string password)
			: this()
		{
			Password = password;
			Decode(data);
		}

		public PKCS12(byte[] data, byte[] password)
			: this()
		{
			_password = password;
			Decode(data);
		}

		private void Decode(byte[] data)
		{
			ASN1 aSN = new ASN1(data);
			if (aSN.Tag != 48)
			{
				throw new ArgumentException("invalid data");
			}
			if (aSN[0].Tag != 2)
			{
				throw new ArgumentException("invalid PFX version");
			}
			PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(aSN[1]);
			if (contentInfo.ContentType != "1.2.840.113549.1.7.1")
			{
				throw new ArgumentException("invalid authenticated safe");
			}
			if (aSN.Count > 2)
			{
				ASN1 aSN2 = aSN[2];
				if (aSN2.Tag != 48)
				{
					throw new ArgumentException("invalid MAC");
				}
				ASN1 aSN3 = aSN2[0];
				if (aSN3.Tag != 48)
				{
					throw new ArgumentException("invalid MAC");
				}
				if (ASN1Convert.ToOid(aSN3[0][0]) != "1.3.14.3.2.26")
				{
					throw new ArgumentException("unsupported HMAC");
				}
				byte[] value = aSN3[1].Value;
				ASN1 aSN4 = aSN2[1];
				if (aSN4.Tag != 4)
				{
					throw new ArgumentException("missing MAC salt");
				}
				_iterations = 1;
				if (aSN2.Count > 2)
				{
					ASN1 aSN5 = aSN2[2];
					if (aSN5.Tag != 2)
					{
						throw new ArgumentException("invalid MAC iteration");
					}
					_iterations = ASN1Convert.ToInt32(aSN5);
				}
				byte[] value2 = contentInfo.Content[0].Value;
				byte[] actual = MAC(_password, aSN4.Value, _iterations, value2);
				if (!Compare(value, actual))
				{
					byte[] password = new byte[2];
					actual = MAC(password, aSN4.Value, _iterations, value2);
					if (!Compare(value, actual))
					{
						throw new CryptographicException("Invalid MAC - file may have been tampered with!");
					}
					_password = password;
				}
			}
			ASN1 aSN6 = new ASN1(contentInfo.Content[0].Value);
			for (int i = 0; i < aSN6.Count; i++)
			{
				PKCS7.ContentInfo contentInfo2 = new PKCS7.ContentInfo(aSN6[i]);
				switch (contentInfo2.ContentType)
				{
				case "1.2.840.113549.1.7.1":
				{
					ASN1 aSN8 = new ASN1(contentInfo2.Content[0].Value);
					for (int k = 0; k < aSN8.Count; k++)
					{
						ASN1 safeBag2 = aSN8[k];
						ReadSafeBag(safeBag2);
					}
					break;
				}
				case "1.2.840.113549.1.7.6":
				{
					PKCS7.EncryptedData ed = new PKCS7.EncryptedData(contentInfo2.Content[0]);
					ASN1 aSN7 = new ASN1(Decrypt(ed));
					for (int j = 0; j < aSN7.Count; j++)
					{
						ASN1 safeBag = aSN7[j];
						ReadSafeBag(safeBag);
					}
					break;
				}
				case "1.2.840.113549.1.7.3":
					throw new NotImplementedException("public key encrypted");
				default:
					throw new ArgumentException("unknown authenticatedSafe");
				}
			}
		}

		~PKCS12()
		{
			if (_password != null)
			{
				Array.Clear(_password, 0, _password.Length);
			}
			_password = null;
		}

		private bool Compare(byte[] expected, byte[] actual)
		{
			bool result = false;
			if (expected.Length == actual.Length)
			{
				for (int i = 0; i < expected.Length; i++)
				{
					if (expected[i] != actual[i])
					{
						return false;
					}
				}
				result = true;
			}
			return result;
		}

		private SymmetricAlgorithm GetSymmetricAlgorithm(string algorithmOid, byte[] salt, int iterationCount)
		{
			string text = null;
			int size = 8;
			int num = 8;
			DeriveBytes deriveBytes = new DeriveBytes();
			deriveBytes.Password = _password;
			deriveBytes.Salt = salt;
			deriveBytes.IterationCount = iterationCount;
			switch (algorithmOid)
			{
			case "1.2.840.113549.1.5.1":
				deriveBytes.HashName = "MD2";
				text = "DES";
				break;
			case "1.2.840.113549.1.5.3":
				deriveBytes.HashName = "MD5";
				text = "DES";
				break;
			case "1.2.840.113549.1.5.4":
				deriveBytes.HashName = "MD2";
				text = "RC2";
				size = 4;
				break;
			case "1.2.840.113549.1.5.6":
				deriveBytes.HashName = "MD5";
				text = "RC2";
				size = 4;
				break;
			case "1.2.840.113549.1.5.10":
				deriveBytes.HashName = "SHA1";
				text = "DES";
				break;
			case "1.2.840.113549.1.5.11":
				deriveBytes.HashName = "SHA1";
				text = "RC2";
				size = 4;
				break;
			case "1.2.840.113549.1.12.1.1":
				deriveBytes.HashName = "SHA1";
				text = "RC4";
				size = 16;
				num = 0;
				break;
			case "1.2.840.113549.1.12.1.2":
				deriveBytes.HashName = "SHA1";
				text = "RC4";
				size = 5;
				num = 0;
				break;
			case "1.2.840.113549.1.12.1.3":
				deriveBytes.HashName = "SHA1";
				text = "TripleDES";
				size = 24;
				break;
			case "1.2.840.113549.1.12.1.4":
				deriveBytes.HashName = "SHA1";
				text = "TripleDES";
				size = 16;
				break;
			case "1.2.840.113549.1.12.1.5":
				deriveBytes.HashName = "SHA1";
				text = "RC2";
				size = 16;
				break;
			case "1.2.840.113549.1.12.1.6":
				deriveBytes.HashName = "SHA1";
				text = "RC2";
				size = 5;
				break;
			default:
				throw new NotSupportedException("unknown oid " + text);
			}
			SymmetricAlgorithm symmetricAlgorithm = null;
			symmetricAlgorithm = SymmetricAlgorithm.Create(text);
			symmetricAlgorithm.Key = deriveBytes.DeriveKey(size);
			if (num > 0)
			{
				symmetricAlgorithm.IV = deriveBytes.DeriveIV(num);
				symmetricAlgorithm.Mode = CipherMode.CBC;
			}
			return symmetricAlgorithm;
		}

		public byte[] Decrypt(string algorithmOid, byte[] salt, int iterationCount, byte[] encryptedData)
		{
			SymmetricAlgorithm symmetricAlgorithm = null;
			byte[] array = null;
			try
			{
				symmetricAlgorithm = GetSymmetricAlgorithm(algorithmOid, salt, iterationCount);
				return symmetricAlgorithm.CreateDecryptor().TransformFinalBlock(encryptedData, 0, encryptedData.Length);
			}
			finally
			{
				symmetricAlgorithm?.Clear();
			}
		}

		public byte[] Decrypt(PKCS7.EncryptedData ed)
		{
			return Decrypt(ed.EncryptionAlgorithm.ContentType, ed.EncryptionAlgorithm.Content[0].Value, ASN1Convert.ToInt32(ed.EncryptionAlgorithm.Content[1]), ed.EncryptedContent);
		}

		public byte[] Encrypt(string algorithmOid, byte[] salt, int iterationCount, byte[] data)
		{
			byte[] array = null;
			using SymmetricAlgorithm symmetricAlgorithm = GetSymmetricAlgorithm(algorithmOid, salt, iterationCount);
			return symmetricAlgorithm.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
		}

		private DSAParameters GetExistingParameters(out bool found)
		{
			foreach (X509Certificate certificate in Certificates)
			{
				if (certificate.KeyAlgorithmParameters != null)
				{
					DSA dSA = certificate.DSA;
					if (dSA != null)
					{
						found = true;
						return dSA.ExportParameters(includePrivateParameters: false);
					}
				}
			}
			found = false;
			return default(DSAParameters);
		}

		private void AddPrivateKey(PKCS8.PrivateKeyInfo pki)
		{
			byte[] privateKey = pki.PrivateKey;
			try
			{
				switch (pki.Algorithm)
				{
				case "1.2.840.113549.1.1.1":
					_keyBags.Add(PKCS8.PrivateKeyInfo.DecodeRSA(privateKey));
					break;
				case "1.2.840.10040.4.1":
				{
					bool found;
					DSAParameters existingParameters = GetExistingParameters(out found);
					if (found)
					{
						_keyBags.Add(PKCS8.PrivateKeyInfo.DecodeDSA(privateKey, existingParameters));
					}
					break;
				}
				default:
					throw new CryptographicException("Unknown private key format");
				}
			}
			finally
			{
				Array.Clear(privateKey, 0, privateKey.Length);
			}
		}

		private void ReadSafeBag(ASN1 safeBag)
		{
			if (safeBag.Tag != 48)
			{
				throw new ArgumentException("invalid safeBag");
			}
			ASN1 aSN = safeBag[0];
			if (aSN.Tag != 6)
			{
				throw new ArgumentException("invalid safeBag id");
			}
			ASN1 aSN2 = safeBag[1];
			string text = ASN1Convert.ToOid(aSN);
			switch (text)
			{
			case "1.2.840.113549.1.12.10.1.1":
				AddPrivateKey(new PKCS8.PrivateKeyInfo(aSN2.Value));
				break;
			case "1.2.840.113549.1.12.10.1.2":
			{
				PKCS8.EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new PKCS8.EncryptedPrivateKeyInfo(aSN2.Value);
				byte[] array = Decrypt(encryptedPrivateKeyInfo.Algorithm, encryptedPrivateKeyInfo.Salt, encryptedPrivateKeyInfo.IterationCount, encryptedPrivateKeyInfo.EncryptedData);
				AddPrivateKey(new PKCS8.PrivateKeyInfo(array));
				Array.Clear(array, 0, array.Length);
				break;
			}
			case "1.2.840.113549.1.12.10.1.3":
			{
				PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(aSN2.Value);
				if (contentInfo.ContentType != "1.2.840.113549.1.9.22.1")
				{
					throw new NotSupportedException("unsupport certificate type");
				}
				X509Certificate value2 = new X509Certificate(contentInfo.Content[0].Value);
				_certs.Add(value2);
				break;
			}
			case "1.2.840.113549.1.12.10.1.5":
			{
				byte[] value = aSN2.Value;
				_secretBags.Add(value);
				break;
			}
			default:
				throw new ArgumentException("unknown safeBag oid");
			case "1.2.840.113549.1.12.10.1.4":
			case "1.2.840.113549.1.12.10.1.6":
				break;
			}
			if (safeBag.Count > 2)
			{
				ASN1 aSN3 = safeBag[2];
				if (aSN3.Tag != 49)
				{
					throw new ArgumentException("invalid safeBag attributes id");
				}
				for (int i = 0; i < aSN3.Count; i++)
				{
					ASN1 aSN4 = aSN3[i];
					if (aSN4.Tag != 48)
					{
						throw new ArgumentException("invalid PKCS12 attributes id");
					}
					ASN1 aSN5 = aSN4[0];
					if (aSN5.Tag != 6)
					{
						throw new ArgumentException("invalid attribute id");
					}
					string text2 = ASN1Convert.ToOid(aSN5);
					ASN1 aSN6 = aSN4[1];
					for (int j = 0; j < aSN6.Count; j++)
					{
						ASN1 aSN7 = aSN6[j];
						if (!(text2 == "1.2.840.113549.1.9.20"))
						{
							if (text2 == "1.2.840.113549.1.9.21" && aSN7.Tag != 4)
							{
								throw new ArgumentException("invalid attribute value id");
							}
						}
						else if (aSN7.Tag != 30)
						{
							throw new ArgumentException("invalid attribute value id");
						}
					}
				}
			}
			_safeBags.Add(new SafeBag(text, safeBag));
		}

		private ASN1 Pkcs8ShroudedKeyBagSafeBag(AsymmetricAlgorithm aa, IDictionary attributes)
		{
			PKCS8.PrivateKeyInfo privateKeyInfo = new PKCS8.PrivateKeyInfo();
			if (aa is RSA)
			{
				privateKeyInfo.Algorithm = "1.2.840.113549.1.1.1";
				privateKeyInfo.PrivateKey = PKCS8.PrivateKeyInfo.Encode((RSA)aa);
			}
			else
			{
				if (!(aa is DSA))
				{
					throw new CryptographicException("Unknown asymmetric algorithm {0}", aa.ToString());
				}
				privateKeyInfo.Algorithm = null;
				privateKeyInfo.PrivateKey = PKCS8.PrivateKeyInfo.Encode((DSA)aa);
			}
			PKCS8.EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new PKCS8.EncryptedPrivateKeyInfo();
			encryptedPrivateKeyInfo.Algorithm = "1.2.840.113549.1.12.1.3";
			encryptedPrivateKeyInfo.IterationCount = _iterations;
			encryptedPrivateKeyInfo.EncryptedData = Encrypt("1.2.840.113549.1.12.1.3", encryptedPrivateKeyInfo.Salt, _iterations, privateKeyInfo.GetBytes());
			ASN1 aSN = new ASN1(48);
			aSN.Add(ASN1Convert.FromOid("1.2.840.113549.1.12.10.1.2"));
			ASN1 aSN2 = new ASN1(160);
			aSN2.Add(new ASN1(encryptedPrivateKeyInfo.GetBytes()));
			aSN.Add(aSN2);
			if (attributes != null)
			{
				ASN1 aSN3 = new ASN1(49);
				IDictionaryEnumerator enumerator = attributes.GetEnumerator();
				while (enumerator.MoveNext())
				{
					string text = (string)enumerator.Key;
					if (!(text == "1.2.840.113549.1.9.20"))
					{
						if (!(text == "1.2.840.113549.1.9.21"))
						{
							continue;
						}
						ArrayList arrayList = (ArrayList)enumerator.Value;
						if (arrayList.Count <= 0)
						{
							continue;
						}
						ASN1 aSN4 = new ASN1(48);
						aSN4.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.21"));
						ASN1 aSN5 = new ASN1(49);
						foreach (byte[] item in arrayList)
						{
							ASN1 aSN6 = new ASN1(4);
							aSN6.Value = item;
							aSN5.Add(aSN6);
						}
						aSN4.Add(aSN5);
						aSN3.Add(aSN4);
						continue;
					}
					ArrayList arrayList2 = (ArrayList)enumerator.Value;
					if (arrayList2.Count <= 0)
					{
						continue;
					}
					ASN1 aSN7 = new ASN1(48);
					aSN7.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.20"));
					ASN1 aSN8 = new ASN1(49);
					foreach (byte[] item2 in arrayList2)
					{
						ASN1 aSN9 = new ASN1(30);
						aSN9.Value = item2;
						aSN8.Add(aSN9);
					}
					aSN7.Add(aSN8);
					aSN3.Add(aSN7);
				}
				if (aSN3.Count > 0)
				{
					aSN.Add(aSN3);
				}
			}
			return aSN;
		}

		private ASN1 KeyBagSafeBag(AsymmetricAlgorithm aa, IDictionary attributes)
		{
			PKCS8.PrivateKeyInfo privateKeyInfo = new PKCS8.PrivateKeyInfo();
			if (aa is RSA)
			{
				privateKeyInfo.Algorithm = "1.2.840.113549.1.1.1";
				privateKeyInfo.PrivateKey = PKCS8.PrivateKeyInfo.Encode((RSA)aa);
			}
			else
			{
				if (!(aa is DSA))
				{
					throw new CryptographicException("Unknown asymmetric algorithm {0}", aa.ToString());
				}
				privateKeyInfo.Algorithm = null;
				privateKeyInfo.PrivateKey = PKCS8.PrivateKeyInfo.Encode((DSA)aa);
			}
			ASN1 aSN = new ASN1(48);
			aSN.Add(ASN1Convert.FromOid("1.2.840.113549.1.12.10.1.1"));
			ASN1 aSN2 = new ASN1(160);
			aSN2.Add(new ASN1(privateKeyInfo.GetBytes()));
			aSN.Add(aSN2);
			if (attributes != null)
			{
				ASN1 aSN3 = new ASN1(49);
				IDictionaryEnumerator enumerator = attributes.GetEnumerator();
				while (enumerator.MoveNext())
				{
					string text = (string)enumerator.Key;
					if (!(text == "1.2.840.113549.1.9.20"))
					{
						if (!(text == "1.2.840.113549.1.9.21"))
						{
							continue;
						}
						ArrayList arrayList = (ArrayList)enumerator.Value;
						if (arrayList.Count <= 0)
						{
							continue;
						}
						ASN1 aSN4 = new ASN1(48);
						aSN4.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.21"));
						ASN1 aSN5 = new ASN1(49);
						foreach (byte[] item in arrayList)
						{
							ASN1 aSN6 = new ASN1(4);
							aSN6.Value = item;
							aSN5.Add(aSN6);
						}
						aSN4.Add(aSN5);
						aSN3.Add(aSN4);
						continue;
					}
					ArrayList arrayList2 = (ArrayList)enumerator.Value;
					if (arrayList2.Count <= 0)
					{
						continue;
					}
					ASN1 aSN7 = new ASN1(48);
					aSN7.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.20"));
					ASN1 aSN8 = new ASN1(49);
					foreach (byte[] item2 in arrayList2)
					{
						ASN1 aSN9 = new ASN1(30);
						aSN9.Value = item2;
						aSN8.Add(aSN9);
					}
					aSN7.Add(aSN8);
					aSN3.Add(aSN7);
				}
				if (aSN3.Count > 0)
				{
					aSN.Add(aSN3);
				}
			}
			return aSN;
		}

		private ASN1 SecretBagSafeBag(byte[] secret, IDictionary attributes)
		{
			ASN1 aSN = new ASN1(48);
			aSN.Add(ASN1Convert.FromOid("1.2.840.113549.1.12.10.1.5"));
			ASN1 asn = new ASN1(128, secret);
			aSN.Add(asn);
			if (attributes != null)
			{
				ASN1 aSN2 = new ASN1(49);
				IDictionaryEnumerator enumerator = attributes.GetEnumerator();
				while (enumerator.MoveNext())
				{
					string text = (string)enumerator.Key;
					if (!(text == "1.2.840.113549.1.9.20"))
					{
						if (!(text == "1.2.840.113549.1.9.21"))
						{
							continue;
						}
						ArrayList arrayList = (ArrayList)enumerator.Value;
						if (arrayList.Count <= 0)
						{
							continue;
						}
						ASN1 aSN3 = new ASN1(48);
						aSN3.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.21"));
						ASN1 aSN4 = new ASN1(49);
						foreach (byte[] item in arrayList)
						{
							ASN1 aSN5 = new ASN1(4);
							aSN5.Value = item;
							aSN4.Add(aSN5);
						}
						aSN3.Add(aSN4);
						aSN2.Add(aSN3);
						continue;
					}
					ArrayList arrayList2 = (ArrayList)enumerator.Value;
					if (arrayList2.Count <= 0)
					{
						continue;
					}
					ASN1 aSN6 = new ASN1(48);
					aSN6.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.20"));
					ASN1 aSN7 = new ASN1(49);
					foreach (byte[] item2 in arrayList2)
					{
						ASN1 aSN8 = new ASN1(30);
						aSN8.Value = item2;
						aSN7.Add(aSN8);
					}
					aSN6.Add(aSN7);
					aSN2.Add(aSN6);
				}
				if (aSN2.Count > 0)
				{
					aSN.Add(aSN2);
				}
			}
			return aSN;
		}

		private ASN1 CertificateSafeBag(X509Certificate x509, IDictionary attributes)
		{
			ASN1 asn = new ASN1(4, x509.RawData);
			PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo();
			contentInfo.ContentType = "1.2.840.113549.1.9.22.1";
			contentInfo.Content.Add(asn);
			ASN1 aSN = new ASN1(160);
			aSN.Add(contentInfo.ASN1);
			ASN1 aSN2 = new ASN1(48);
			aSN2.Add(ASN1Convert.FromOid("1.2.840.113549.1.12.10.1.3"));
			aSN2.Add(aSN);
			if (attributes != null)
			{
				ASN1 aSN3 = new ASN1(49);
				IDictionaryEnumerator enumerator = attributes.GetEnumerator();
				while (enumerator.MoveNext())
				{
					string text = (string)enumerator.Key;
					if (!(text == "1.2.840.113549.1.9.20"))
					{
						if (!(text == "1.2.840.113549.1.9.21"))
						{
							continue;
						}
						ArrayList arrayList = (ArrayList)enumerator.Value;
						if (arrayList.Count <= 0)
						{
							continue;
						}
						ASN1 aSN4 = new ASN1(48);
						aSN4.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.21"));
						ASN1 aSN5 = new ASN1(49);
						foreach (byte[] item in arrayList)
						{
							ASN1 aSN6 = new ASN1(4);
							aSN6.Value = item;
							aSN5.Add(aSN6);
						}
						aSN4.Add(aSN5);
						aSN3.Add(aSN4);
						continue;
					}
					ArrayList arrayList2 = (ArrayList)enumerator.Value;
					if (arrayList2.Count <= 0)
					{
						continue;
					}
					ASN1 aSN7 = new ASN1(48);
					aSN7.Add(ASN1Convert.FromOid("1.2.840.113549.1.9.20"));
					ASN1 aSN8 = new ASN1(49);
					foreach (byte[] item2 in arrayList2)
					{
						ASN1 aSN9 = new ASN1(30);
						aSN9.Value = item2;
						aSN8.Add(aSN9);
					}
					aSN7.Add(aSN8);
					aSN3.Add(aSN7);
				}
				if (aSN3.Count > 0)
				{
					aSN2.Add(aSN3);
				}
			}
			return aSN2;
		}

		private byte[] MAC(byte[] password, byte[] salt, int iterations, byte[] data)
		{
			DeriveBytes deriveBytes = new DeriveBytes();
			deriveBytes.HashName = "SHA1";
			deriveBytes.Password = password;
			deriveBytes.Salt = salt;
			deriveBytes.IterationCount = iterations;
			HMACSHA1 obj = (HMACSHA1)System.Security.Cryptography.HMAC.Create();
			obj.Key = deriveBytes.DeriveMAC(20);
			return obj.ComputeHash(data, 0, data.Length);
		}

		public byte[] GetBytes()
		{
			ASN1 aSN = new ASN1(48);
			ArrayList arrayList = new ArrayList();
			foreach (SafeBag safeBag5 in _safeBags)
			{
				if (safeBag5.BagOID.Equals("1.2.840.113549.1.12.10.1.3"))
				{
					PKCS7.ContentInfo contentInfo = new PKCS7.ContentInfo(safeBag5.ASN1[1].Value);
					arrayList.Add(new X509Certificate(contentInfo.Content[0].Value));
				}
			}
			ArrayList arrayList2 = new ArrayList();
			ArrayList arrayList3 = new ArrayList();
			foreach (X509Certificate certificate in Certificates)
			{
				bool flag = false;
				foreach (X509Certificate item in arrayList)
				{
					if (Compare(certificate.RawData, item.RawData))
					{
						flag = true;
					}
				}
				if (!flag)
				{
					arrayList2.Add(certificate);
				}
			}
			foreach (X509Certificate item2 in arrayList)
			{
				bool flag2 = false;
				foreach (X509Certificate certificate2 in Certificates)
				{
					if (Compare(item2.RawData, certificate2.RawData))
					{
						flag2 = true;
					}
				}
				if (!flag2)
				{
					arrayList3.Add(item2);
				}
			}
			foreach (X509Certificate item3 in arrayList3)
			{
				RemoveCertificate(item3);
			}
			foreach (X509Certificate item4 in arrayList2)
			{
				AddCertificate(item4);
			}
			if (_safeBags.Count > 0)
			{
				ASN1 aSN2 = new ASN1(48);
				foreach (SafeBag safeBag6 in _safeBags)
				{
					if (safeBag6.BagOID.Equals("1.2.840.113549.1.12.10.

BepInEx/core/Mono.WebBrowser.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Mono.Mozilla;
using Mono.Mozilla.DOM;
using Mono.WebBrowser;
using Mono.WebBrowser.DOM;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Mono.WebBrowser")]
[assembly: AssemblyDescription("Managed Wrapper for xulrunner engine, to support WebBrowser")]
[assembly: AssemblyConfiguration("Development version")]
[assembly: AssemblyProduct("Mono.WebBrowser")]
[assembly: AssemblyCopyright("(c) 2007, 2008 Andreia Gaita")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyVersion("4.0.0.0")]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
namespace Mono.WebBrowser
{
	public class Exception : System.Exception
	{
		internal enum ErrorCodes
		{
			Other,
			GluezillaInit,
			EngineNotSupported,
			ServiceManager,
			IOService,
			DirectoryService,
			PrefService,
			StreamNotOpen,
			Navigation,
			AccessibilityService,
			DocumentEncoderService
		}

		private ErrorCodes code;

		private static ArrayList messages;

		internal ErrorCodes ErrorCode => code;

		static Exception()
		{
			messages = new ArrayList();
			messages.Insert(0, string.Intern("A critical error occurred."));
			messages.Insert(1, string.Intern("An error occurred while initializing gluezilla. Please make sure you have libgluezilla installed."));
			messages.Insert(2, string.Intern("Browser engine not supported at this time: "));
			messages.Insert(3, string.Intern("Error obtaining a handle to the service manager."));
			messages.Insert(4, string.Intern("Error obtaining a handle to the io service."));
			messages.Insert(5, string.Intern("Error obtaining a handle to the directory service."));
			messages.Insert(6, string.Intern("Error obtaining a handle to the preferences service."));
			messages.Insert(7, string.Intern("Stream is not open for writing. Call OpenStream before appending."));
			messages.Insert(8, string.Intern("An error occurred while initializing the navigation object."));
			messages.Insert(9, string.Intern("Error obtaining a handle to the accessibility service."));
			messages.Insert(10, string.Intern("Error obtaining a handle to the document encoder service."));
		}

		internal Exception(ErrorCodes code)
			: base(GetMessage(code, string.Empty))
		{
			this.code = code;
		}

		internal Exception(ErrorCodes code, string message)
			: base(GetMessage(code, message))
		{
			this.code = code;
		}

		internal Exception(ErrorCodes code, System.Exception innerException)
			: base(GetMessage(code, string.Empty), innerException)
		{
			this.code = code;
		}

		internal Exception(ErrorCodes code, string message, Exception innerException)
			: base(GetMessage(code, message), innerException)
		{
			this.code = code;
		}

		private static string GetMessage(ErrorCodes code, string message)
		{
			return (messages[(int)code] as string) + " " + message;
		}
	}
	public interface IWebBrowser
	{
		bool Initialized { get; }

		IWindow Window { get; }

		IDocument Document { get; }

		bool Offline { get; set; }

		INavigation Navigation { get; }

		event NodeEventHandler KeyDown;

		event NodeEventHandler KeyPress;

		event NodeEventHandler KeyUp;

		event NodeEventHandler MouseClick;

		event NodeEventHandler MouseDoubleClick;

		event NodeEventHandler MouseDown;

		event NodeEventHandler MouseEnter;

		event NodeEventHandler MouseLeave;

		event NodeEventHandler MouseMove;

		event NodeEventHandler MouseUp;

		event EventHandler Focus;

		event CreateNewWindowEventHandler CreateNewWindow;

		event AlertEventHandler Alert;

		event LoadStartedEventHandler LoadStarted;

		event LoadCommitedEventHandler LoadCommited;

		event ProgressChangedEventHandler ProgressChanged;

		event LoadFinishedEventHandler LoadFinished;

		event StatusChangedEventHandler StatusChanged;

		event SecurityChangedEventHandler SecurityChanged;

		event ContextMenuEventHandler ContextMenuShown;

		event NavigationRequestedEventHandler NavigationRequested;

		bool Load(IntPtr handle, int width, int height);

		void Shutdown();

		void FocusIn(FocusOption focus);

		void FocusOut();

		void Activate();

		void Deactivate();

		void Resize(int width, int height);

		void Render(byte[] data);

		void Render(string html);

		void Render(string html, string uri, string contentType);

		void ExecuteScript(string script);
	}
	public enum ReloadOption : uint
	{
		None,
		Proxy,
		Full
	}
	public enum FocusOption
	{
		None,
		FocusFirstElement,
		FocusLastElement
	}
	[Flags]
	public enum DialogButtonFlags
	{
		BUTTON_POS_0 = 1,
		BUTTON_POS_1 = 0x100,
		BUTTON_POS_2 = 0x10000,
		BUTTON_TITLE_OK = 1,
		BUTTON_TITLE_CANCEL = 2,
		BUTTON_TITLE_YES = 3,
		BUTTON_TITLE_NO = 4,
		BUTTON_TITLE_SAVE = 5,
		BUTTON_TITLE_DONT_SAVE = 6,
		BUTTON_TITLE_REVERT = 7,
		BUTTON_TITLE_IS_STRING = 0x7F,
		BUTTON_POS_0_DEFAULT = 0,
		BUTTON_POS_1_DEFAULT = 0x1000000,
		BUTTON_POS_2_DEFAULT = 0x2000000,
		BUTTON_DELAY_ENABLE = 0x4000000,
		STD_OK_CANCEL_BUTTONS = 0x201
	}
	public enum DialogType
	{
		Alert = 1,
		AlertCheck,
		Confirm,
		ConfirmEx,
		ConfirmCheck,
		Prompt,
		PromptUsernamePassword,
		PromptPassword,
		Select
	}
	public enum Platform
	{
		Unknown,
		Winforms,
		Gtk
	}
	public enum SecurityLevel
	{
		Insecure = 1,
		Mixed,
		Secure
	}
	public delegate bool CreateNewWindowEventHandler(object sender, CreateNewWindowEventArgs e);
	public class CreateNewWindowEventArgs : EventArgs
	{
		private bool isModal;

		public bool IsModal => isModal;

		public CreateNewWindowEventArgs(bool isModal)
		{
			this.isModal = isModal;
		}
	}
	public delegate void AlertEventHandler(object sender, AlertEventArgs e);
	public class AlertEventArgs : EventArgs
	{
		private DialogType type;

		private string title;

		private string text;

		private string text2;

		private string username;

		private string password;

		private string checkMsg;

		private bool checkState;

		private DialogButtonFlags dialogButtons;

		private StringCollection buttons;

		private StringCollection options;

		private object returnValue;

		public DialogType Type
		{
			get
			{
				return type;
			}
			set
			{
				type = value;
			}
		}

		public string Title
		{
			get
			{
				return title;
			}
			set
			{
				title = value;
			}
		}

		public string Text
		{
			get
			{
				return text;
			}
			set
			{
				text = value;
			}
		}

		public string Text2
		{
			get
			{
				return text2;
			}
			set
			{
				text2 = value;
			}
		}

		public string CheckMessage
		{
			get
			{
				return checkMsg;
			}
			set
			{
				checkMsg = value;
			}
		}

		public bool CheckState
		{
			get
			{
				return checkState;
			}
			set
			{
				checkState = value;
			}
		}

		public DialogButtonFlags DialogButtons
		{
			get
			{
				return dialogButtons;
			}
			set
			{
				dialogButtons = value;
			}
		}

		public StringCollection Buttons
		{
			get
			{
				return buttons;
			}
			set
			{
				buttons = value;
			}
		}

		public StringCollection Options
		{
			get
			{
				return options;
			}
			set
			{
				options = value;
			}
		}

		public string Username
		{
			get
			{
				return username;
			}
			set
			{
				username = value;
			}
		}

		public string Password
		{
			get
			{
				return password;
			}
			set
			{
				password = value;
			}
		}

		public bool BoolReturn
		{
			get
			{
				if (returnValue is bool)
				{
					return (bool)returnValue;
				}
				return false;
			}
			set
			{
				returnValue = value;
			}
		}

		public int IntReturn
		{
			get
			{
				if (returnValue is int)
				{
					return (int)returnValue;
				}
				return -1;
			}
			set
			{
				returnValue = value;
			}
		}

		public string StringReturn
		{
			get
			{
				if (returnValue is string)
				{
					return (string)returnValue;
				}
				return string.Empty;
			}
			set
			{
				returnValue = value;
			}
		}
	}
	public delegate void StatusChangedEventHandler(object sender, StatusChangedEventArgs e);
	public class StatusChangedEventArgs : EventArgs
	{
		private string message;

		private int status;

		public string Message
		{
			get
			{
				return message;
			}
			set
			{
				message = value;
			}
		}

		public int Status
		{
			get
			{
				return status;
			}
			set
			{
				status = value;
			}
		}

		public StatusChangedEventArgs(string message, int status)
		{
			this.message = message;
			this.status = status;
		}
	}
	public delegate void ProgressChangedEventHandler(object sender, ProgressChangedEventArgs e);
	public class ProgressChangedEventArgs : EventArgs
	{
		private int progress;

		private int maxProgress;

		public int Progress => progress;

		public int MaxProgress => maxProgress;

		public ProgressChangedEventArgs(int progress, int maxProgress)
		{
			this.progress = progress;
			this.maxProgress = maxProgress;
		}
	}
	public delegate void LoadStartedEventHandler(object sender, LoadStartedEventArgs e);
	public class LoadStartedEventArgs : CancelEventArgs
	{
		private string uri;

		private string frameName;

		public string Uri => uri;

		public string FrameName => frameName;

		public LoadStartedEventArgs(string uri, string frameName)
		{
			this.uri = uri;
			this.frameName = frameName;
		}
	}
	public delegate void LoadCommitedEventHandler(object sender, LoadCommitedEventArgs e);
	public class LoadCommitedEventArgs : EventArgs
	{
		private string uri;

		public string Uri => uri;

		public LoadCommitedEventArgs(string uri)
		{
			this.uri = uri;
		}
	}
	public delegate void LoadFinishedEventHandler(object sender, LoadFinishedEventArgs e);
	public class LoadFinishedEventArgs : EventArgs
	{
		private string uri;

		public string Uri => uri;

		public LoadFinishedEventArgs(string uri)
		{
			this.uri = uri;
		}
	}
	public delegate void SecurityChangedEventHandler(object sender, SecurityChangedEventArgs e);
	public class SecurityChangedEventArgs : EventArgs
	{
		private SecurityLevel state;

		public SecurityLevel State
		{
			get
			{
				return state;
			}
			set
			{
				state = value;
			}
		}

		public SecurityChangedEventArgs(SecurityLevel state)
		{
			this.state = state;
		}
	}
	public delegate void ContextMenuEventHandler(object sender, ContextMenuEventArgs e);
	public class ContextMenuEventArgs : EventArgs
	{
		private int x;

		private int y;

		public int X => x;

		public int Y => y;

		public ContextMenuEventArgs(int x, int y)
		{
			this.x = x;
			this.y = y;
		}
	}
	public delegate void NavigationRequestedEventHandler(object sender, NavigationRequestedEventArgs e);
	public class NavigationRequestedEventArgs : CancelEventArgs
	{
		private string uri;

		public string Uri => uri;

		public NavigationRequestedEventArgs(string uri)
		{
			this.uri = uri;
		}
	}
	public sealed class Manager
	{
		public static IWebBrowser GetNewInstance()
		{
			return GetNewInstance(Platform.Winforms);
		}

		public static IWebBrowser GetNewInstance(Platform platform)
		{
			string text = Environment.GetEnvironmentVariable("MONO_BROWSER_ENGINE");
			if (text == "webkit")
			{
				try
				{
					return (IWebBrowser)Assembly.LoadWithPartialName("mono-webkit").CreateInstance("Mono.WebKit.WebBrowser");
				}
				catch
				{
					text = null;
				}
			}
			if (text == null || text == "mozilla")
			{
				return new Mono.Mozilla.WebBrowser(platform);
			}
			throw new Exception(Exception.ErrorCodes.EngineNotSupported, text);
		}
	}
}
namespace Mono.WebBrowser.DOM
{
	public class NodeEventArgs : EventArgs
	{
		private INode node;

		public INode Node => node;

		public IElement Element
		{
			get
			{
				if (node is IElement)
				{
					return (IElement)node;
				}
				return null;
			}
		}

		public IDocument Document
		{
			get
			{
				if (node is IDocument)
				{
					return (IDocument)node;
				}
				return null;
			}
		}

		public NodeEventArgs(INode node)
		{
			this.node = node;
		}
	}
	public class WindowEventArgs : EventArgs
	{
		private IWindow window;

		public IWindow Window => window;

		public WindowEventArgs(IWindow window)
		{
			this.window = window;
		}
	}
	public delegate void NodeEventHandler(object sender, NodeEventArgs e);
	public delegate void WindowEventHandler(object sender, WindowEventArgs e);
	public interface IAttribute : INode
	{
		string Name { get; }

		new int GetHashCode();
	}
	public interface IAttributeCollection : INodeList, IList, ICollection, IEnumerable
	{
		IAttribute this[string name] { get; }

		bool Exists(string name);

		new int GetHashCode();
	}
	public interface IDOMImplementation
	{
		bool HasFeature(string feature, string version);

		IDocumentType CreateDocumentType(string qualifiedName, string publicId, string systemId);

		IDocument CreateDocument(string namespaceURI, string qualifiedName, IDocumentType doctype);
	}
	public interface IDocument : INode
	{
		IElement Active { get; }

		string ActiveLinkColor { get; set; }

		IElementCollection Anchors { get; }

		IElementCollection Applets { get; }

		string Background { get; set; }

		string BackColor { get; set; }

		IElement Body { get; }

		string Charset { get; set; }

		string Cookie { get; set; }

		IElement DocumentElement { get; }

		IDocumentType DocType { get; }

		string Domain { get; }

		string ForeColor { get; set; }

		IElementCollection Forms { get; }

		IElementCollection Images { get; }

		IDOMImplementation Implementation { get; }

		string LinkColor { get; set; }

		IElementCollection Links { get; }

		IStylesheetList Stylesheets { get; }

		string Title { get; set; }

		string Url { get; }

		string VisitedLinkColor { get; set; }

		IWindow Window { get; }

		event EventHandler LoadStopped;

		IAttribute CreateAttribute(string name);

		IElement CreateElement(string tagName);

		IElement GetElementById(string id);

		IElement GetElement(int x, int y);

		IElementCollection GetElementsByTagName(string id);

		void Write(string text);

		string InvokeScript(string script);

		new int GetHashCode();
	}
	public interface IDocumentType : INode
	{
		string Name { get; }

		INamedNodeMap Entities { get; }

		INamedNodeMap Notations { get; }

		string PublicId { get; }

		string SystemId { get; }

		string InternalSubset { get; }
	}
	public interface IElement : INode
	{
		IElementCollection All { get; }

		IElementCollection Children { get; }

		int ClientWidth { get; }

		int ClientHeight { get; }

		int ScrollHeight { get; }

		int ScrollWidth { get; }

		int ScrollLeft { get; set; }

		int ScrollTop { get; set; }

		int OffsetHeight { get; }

		int OffsetWidth { get; }

		int OffsetLeft { get; }

		int OffsetTop { get; }

		IElement OffsetParent { get; }

		string InnerText { get; set; }

		string InnerHTML { get; set; }

		string OuterText { get; set; }

		string OuterHTML { get; set; }

		string Style { get; set; }

		int TabIndex { get; set; }

		string TagName { get; }

		bool Disabled { get; set; }

		System.IO.Stream ContentStream { get; }

		IElement AppendChild(IElement child);

		void Blur();

		void Focus();

		bool HasAttribute(string name);

		string GetAttribute(string name);

		IElementCollection GetElementsByTagName(string id);

		new int GetHashCode();

		void ScrollIntoView(bool alignWithTop);

		void SetAttribute(string name, string value);
	}
	public interface IElementCollection : INodeList, IList, ICollection, IEnumerable
	{
		new IElement this[int index] { get; set; }

		new int GetHashCode();
	}
	public interface IHistory
	{
		int Count { get; }

		void Back(int count);

		void Forward(int count);

		void GoToIndex(int index);

		void GoToUrl(string url);
	}
	public interface IMediaList
	{
	}
	public interface INamedNodeMap : IList, ICollection, IEnumerable
	{
		INode this[string name] { get; set; }

		new INode this[int index] { get; set; }

		INode this[string namespaceURI, string localName] { get; set; }

		INode RemoveNamedItem(string name);

		INode RemoveNamedItemNS(string namespaceURI, string localName);
	}
	public interface INavigation
	{
		bool CanGoBack { get; }

		bool CanGoForward { get; }

		int HistoryCount { get; }

		bool Back();

		bool Forward();

		void Home();

		void Reload();

		void Reload(ReloadOption option);

		void Stop();

		void Go(int index);

		void Go(int index, bool relative);

		void Go(string url);

		void Go(string url, LoadFlags flags);
	}
	[Flags]
	public enum LoadFlags : uint
	{
		None = 0u,
		AsMetaRefresh = 0x10u,
		AsLinkClick = 0x20u,
		BypassHistory = 0x40u,
		ReplaceHistory = 0x80u,
		BypassLocalCache = 0x100u,
		BypassProxy = 0x200u,
		CharsetChange = 0x400u
	}
	public interface INode
	{
		IAttributeCollection Attributes { get; }

		INodeList ChildNodes { get; }

		INode FirstChild { get; }

		INode LastChild { get; }

		string LocalName { get; }

		INode Next { get; }

		IDocument Owner { get; }

		INode Parent { get; }

		INode Previous { get; }

		NodeType Type { get; }

		string Value { get; set; }

		IntPtr AccessibleObject { get; }

		event NodeEventHandler Click;

		event NodeEventHandler DoubleClick;

		event NodeEventHandler KeyDown;

		event NodeEventHandler KeyPress;

		event NodeEventHandler KeyUp;

		event NodeEventHandler MouseDown;

		event NodeEventHandler MouseEnter;

		event NodeEventHandler MouseLeave;

		event NodeEventHandler MouseMove;

		event NodeEventHandler MouseOver;

		event NodeEventHandler MouseUp;

		event NodeEventHandler OnFocus;

		event NodeEventHandler OnBlur;

		INode InsertBefore(INode newChild, INode refChild);

		INode ReplaceChild(INode newChild, INode oldChild);

		INode RemoveChild(INode child);

		INode AppendChild(INode child);

		void FireEvent(string eventName);

		new int GetHashCode();

		new bool Equals(object obj);

		void AttachEventHandler(string eventName, EventHandler handler);

		void DetachEventHandler(string eventName, EventHandler handler);

		void AttachEventHandler(string eventName, Delegate handler);

		void DetachEventHandler(string eventName, Delegate handler);
	}
	public enum NodeType
	{
		Element = 1,
		Attribute,
		Text,
		CDataSection,
		EntityReference,
		Entity,
		ProcessingInstruction,
		Comment,
		Document,
		DocumentType,
		DocumentFragment,
		Notation
	}
	public interface INodeList : IList, ICollection, IEnumerable
	{
		new INode this[int index] { get; set; }

		new int GetHashCode();
	}
	public interface IStylesheet
	{
		string Type { get; }

		bool Disabled { get; set; }

		INode OwnerNode { get; }

		IStylesheet ParentStyleSheet { get; }

		string Href { get; }

		string Title { get; }

		IMediaList Media { get; }
	}
	public interface IStylesheetList : IEnumerable
	{
		int Count { get; }

		IStylesheet this[int index] { get; set; }
	}
	public interface IWindow
	{
		IDocument Document { get; }

		IWindowCollection Frames { get; }

		string Name { get; set; }

		IWindow Parent { get; }

		string StatusText { get; }

		IWindow Top { get; }

		IHistory History { get; }

		event EventHandler Load;

		event EventHandler Unload;

		event EventHandler OnFocus;

		event EventHandler OnBlur;

		event EventHandler Error;

		event EventHandler Scroll;

		void AttachEventHandler(string eventName, EventHandler handler);

		void DetachEventHandler(string eventName, EventHandler handler);

		void Focus();

		new bool Equals(object obj);

		new int GetHashCode();

		void Open(string url);

		void ScrollTo(int x, int y);
	}
	public interface IWindowCollection : IList, ICollection, IEnumerable
	{
		new IWindow this[int index] { get; set; }
	}
}
namespace Mono.Mozilla
{
	internal class AsciiString : IDisposable
	{
		[StructLayout(LayoutKind.Sequential)]
		private class nsStringContainer
		{
			private IntPtr v;

			private IntPtr d1;

			private uint d2;

			private IntPtr d3;
		}

		private bool disposed;

		private nsStringContainer unmanagedContainer;

		private HandleRef handle;

		private string str = string.Empty;

		private bool dirty;

		public HandleRef Handle
		{
			get
			{
				dirty = true;
				return handle;
			}
		}

		public string String
		{
			get
			{
				if (dirty)
				{
					Base.gluezilla_CStringGetData(handle, out var aBuf, out var _);
					str = Marshal.PtrToStringAnsi(aBuf);
					dirty = false;
				}
				return str;
			}
			set
			{
				if (str != value)
				{
					str = value;
					Base.gluezilla_CStringSetData(handle, str, (uint)str.Length);
				}
			}
		}

		public int Length => String.Length;

		public AsciiString(string value)
		{
			unmanagedContainer = new nsStringContainer();
			IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(nsStringContainer)));
			Marshal.StructureToPtr(unmanagedContainer, ptr, fDeleteOld: false);
			handle = new HandleRef(typeof(nsStringContainer), ptr);
			Base.gluezilla_CStringContainerInit(handle);
			String = value;
		}

		~AsciiString()
		{
			Dispose(disposing: false);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (disposing)
				{
					Base.gluezilla_CStringContainerFinish(handle);
					Marshal.FreeHGlobal(handle.Handle);
				}
				disposed = true;
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		public override string ToString()
		{
			return String;
		}
	}
	internal class Base
	{
		private class BindingInfo
		{
			public CallbackBinder callback;

			public IntPtr gluezilla;
		}

		private static Hashtable boundControls;

		private static bool initialized;

		private static object initLock;

		private static string monoMozDir;

		private static bool isInitialized()
		{
			if (!initialized)
			{
				return false;
			}
			return true;
		}

		private static BindingInfo getBinding(IWebBrowser control)
		{
			if (!boundControls.ContainsKey(control))
			{
				return null;
			}
			return boundControls[control] as BindingInfo;
		}

		static Base()
		{
			initLock = new object();
			boundControls = new Hashtable();
		}

		public static void Debug(int signal)
		{
			gluezilla_debug(signal);
		}

		public static bool Init(WebBrowser control, Platform platform)
		{
			lock (initLock)
			{
				if (!initialized)
				{
					Platform mozPlatform;
					try
					{
						short num = gluezilla_init(platform, out mozPlatform);
						monoMozDir = Path.Combine(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), ".mono"), "mozilla-" + num);
						if (!Directory.Exists(monoMozDir))
						{
							Directory.CreateDirectory(monoMozDir);
						}
					}
					catch (DllNotFoundException)
					{
						Console.WriteLine("libgluezilla not found. To have webbrowser support, you need libgluezilla installed");
						initialized = false;
						return false;
					}
					control.enginePlatform = mozPlatform;
					initialized = true;
				}
			}
			return initialized;
		}

		public static bool Bind(WebBrowser control, IntPtr handle, int width, int height)
		{
			if (!isInitialized())
			{
				return false;
			}
			BindingInfo bindingInfo = new BindingInfo();
			bindingInfo.callback = new CallbackBinder(control.callbacks);
			IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(bindingInfo.callback));
			Marshal.StructureToPtr(bindingInfo.callback, intPtr, fDeleteOld: true);
			bindingInfo.gluezilla = gluezilla_bind(intPtr, handle, width, height, Environment.CurrentDirectory, monoMozDir, control.platform);
			lock (initLock)
			{
				if (bindingInfo.gluezilla == IntPtr.Zero)
				{
					Marshal.FreeHGlobal(intPtr);
					bindingInfo = null;
					initialized = false;
					return false;
				}
			}
			boundControls.Add(control, bindingInfo);
			return true;
		}

		public static bool Create(IWebBrowser control)
		{
			if (!isInitialized())
			{
				return false;
			}
			gluezilla_createBrowserWindow(getBinding(control).gluezilla);
			return true;
		}

		public static void Shutdown(IWebBrowser control)
		{
			lock (initLock)
			{
				if (initialized)
				{
					gluezilla_shutdown(getBinding(control).gluezilla);
					boundControls.Remove(control);
					if (boundControls.Count == 0)
					{
						initialized = false;
					}
				}
			}
		}

		public static void Focus(IWebBrowser control, FocusOption focus)
		{
			if (isInitialized())
			{
				gluezilla_focus(getBinding(control).gluezilla, focus);
			}
		}

		public static void Blur(IWebBrowser control)
		{
			if (isInitialized())
			{
				gluezilla_blur(getBinding(control).gluezilla);
			}
		}

		public static void Activate(IWebBrowser control)
		{
			if (isInitialized())
			{
				gluezilla_activate(getBinding(control).gluezilla);
			}
		}

		public static void Deactivate(IWebBrowser control)
		{
			if (isInitialized())
			{
				gluezilla_deactivate(getBinding(control).gluezilla);
			}
		}

		public static void Resize(IWebBrowser control, int width, int height)
		{
			if (isInitialized())
			{
				gluezilla_resize(getBinding(control).gluezilla, width, height);
			}
		}

		public static void Home(IWebBrowser control)
		{
			if (isInitialized())
			{
				gluezilla_home(getBinding(control).gluezilla);
			}
		}

		public static nsIWebNavigation GetWebNavigation(IWebBrowser control)
		{
			if (!isInitialized())
			{
				return null;
			}
			return gluezilla_getWebNavigation(getBinding(control).gluezilla);
		}

		public static IntPtr StringInit()
		{
			if (!isInitialized())
			{
				return IntPtr.Zero;
			}
			return gluezilla_stringInit();
		}

		public static void StringFinish(HandleRef str)
		{
			if (isInitialized())
			{
				gluezilla_stringFinish(str);
			}
		}

		public static string StringGet(HandleRef str)
		{
			if (!isInitialized())
			{
				return string.Empty;
			}
			return Marshal.PtrToStringUni(gluezilla_stringGet(str));
		}

		public static void StringSet(HandleRef str, string text)
		{
			if (isInitialized())
			{
				gluezilla_stringSet(str, text);
			}
		}

		public static object GetProxyForObject(IWebBrowser control, Guid iid, object obj)
		{
			if (!isInitialized())
			{
				return null;
			}
			gluezilla_getProxyForObject(getBinding(control).gluezilla, iid, obj, out var ret);
			return Marshal.GetObjectForIUnknown(ret);
		}

		public static nsIServiceManager GetServiceManager(IWebBrowser control)
		{
			if (!isInitialized())
			{
				return null;
			}
			return gluezilla_getServiceManager2(getBinding(control).gluezilla);
		}

		public static string EvalScript(IWebBrowser control, string script)
		{
			if (!isInitialized())
			{
				return null;
			}
			return Marshal.PtrToStringAuto(gluezilla_evalScript(getBinding(control).gluezilla, script));
		}

		[DllImport("gluezilla")]
		private static extern void gluezilla_debug(int signal);

		[DllImport("gluezilla")]
		private static extern short gluezilla_init(Platform platform, out Platform mozPlatform);

		[DllImport("gluezilla")]
		private static extern IntPtr gluezilla_bind(IntPtr events, IntPtr hwnd, int width, int height, string startDir, string dataDir, Platform platform);

		[DllImport("gluezilla")]
		private static extern int gluezilla_createBrowserWindow(IntPtr instance);

		[DllImport("gluezilla")]
		private static extern IntPtr gluezilla_shutdown(IntPtr instance);

		[DllImport("gluezilla")]
		private static extern int gluezilla_focus(IntPtr instance, FocusOption focus);

		[DllImport("gluezilla")]
		private static extern int gluezilla_blur(IntPtr instance);

		[DllImport("gluezilla")]
		private static extern int gluezilla_activate(IntPtr instance);

		[DllImport("gluezilla")]
		private static extern int gluezilla_deactivate(IntPtr instance);

		[DllImport("gluezilla")]
		private static extern int gluezilla_resize(IntPtr instance, int width, int height);

		[DllImport("gluezilla")]
		private static extern int gluezilla_home(IntPtr instance);

		[DllImport("gluezilla")]
		[return: MarshalAs(UnmanagedType.Interface)]
		private static extern nsIWebNavigation gluezilla_getWebNavigation(IntPtr instance);

		[DllImport("gluezilla")]
		private static extern IntPtr gluezilla_stringInit();

		[DllImport("gluezilla")]
		private static extern int gluezilla_stringFinish(HandleRef str);

		[DllImport("gluezilla")]
		private static extern IntPtr gluezilla_stringGet(HandleRef str);

		[DllImport("gluezilla")]
		private static extern void gluezilla_stringSet(HandleRef str, [MarshalAs(UnmanagedType.LPWStr)] string text);

		[DllImport("gluezilla")]
		private static extern void gluezilla_getProxyForObject(IntPtr instance, [MarshalAs(UnmanagedType.LPStruct)] Guid iid, [MarshalAs(UnmanagedType.Interface)] object obj, out IntPtr ret);

		[DllImport("gluezilla")]
		public static extern uint gluezilla_StringContainerInit(HandleRef aStr);

		[DllImport("gluezilla")]
		public static extern void gluezilla_StringContainerFinish(HandleRef aStr);

		[DllImport("gluezilla")]
		public static extern uint gluezilla_StringGetData(HandleRef aStr, out IntPtr aBuf, out bool aTerm);

		[DllImport("gluezilla")]
		public static extern uint gluezilla_StringSetData(HandleRef aStr, [MarshalAs(UnmanagedType.LPWStr)] string aBuf, uint aCount);

		[DllImport("gluezilla")]
		public static extern uint gluezilla_CStringContainerInit(HandleRef aStr);

		[DllImport("gluezilla")]
		public static extern void gluezilla_CStringContainerFinish(HandleRef aStr);

		[DllImport("gluezilla")]
		public static extern uint gluezilla_CStringGetData(HandleRef aStr, out IntPtr aBuf, out bool aTerm);

		[DllImport("gluezilla")]
		public static extern uint gluezilla_CStringSetData(HandleRef aStr, string aBuf, uint aCount);

		[DllImport("gluezilla")]
		[return: MarshalAs(UnmanagedType.Interface)]
		public static extern nsIServiceManager gluezilla_getServiceManager2(IntPtr instance);

		[DllImport("gluezilla")]
		private static extern IntPtr gluezilla_evalScript(IntPtr instance, string script);
	}
	internal class Callback
	{
		private WebBrowser owner;

		private string currentUri;

		private bool calledLoadStarted;

		public Callback(WebBrowser owner)
		{
			this.owner = owner;
		}

		public void OnWidgetLoaded()
		{
		}

		public void OnStateChange(nsIWebProgress progress, nsIRequest request, int status, uint state)
		{
			if (!owner.created)
			{
				owner.created = true;
			}
			bool num = (state & 1) != 0;
			bool flag = (state & 4) != 0;
			bool flag2 = (state & 2) != 0;
			bool flag3 = (state & 0x10) != 0;
			bool flag4 = (state & 0x10000) != 0;
			bool flag5 = (state & 0x20000) != 0;
			bool flag6 = (state & 0x40000) != 0;
			bool flag7 = (state & 0x80000) != 0;
			if (num && flag4 && flag5 && !calledLoadStarted)
			{
				progress.getDOMWindow(out var ret);
				((nsIChannel)request).getURI(out var ret2);
				if (ret2 == null)
				{
					currentUri = "about:blank";
				}
				else
				{
					AsciiString asciiString = new AsciiString(string.Empty);
					ret2.getSpec(asciiString.Handle);
					currentUri = asciiString.ToString();
				}
				calledLoadStarted = true;
				LoadStartedEventHandler loadStartedEventHandler = (LoadStartedEventHandler)owner.Events[WebBrowser.LoadStarted];
				if (loadStartedEventHandler != null)
				{
					AsciiString asciiString2 = new AsciiString(string.Empty);
					ret.getName(asciiString2.Handle);
					LoadStartedEventArgs loadStartedEventArgs = new LoadStartedEventArgs(currentUri, asciiString2.ToString());
					loadStartedEventHandler(this, loadStartedEventArgs);
					if (loadStartedEventArgs.Cancel)
					{
						request.cancel(2152398850u);
					}
				}
			}
			else if (flag5 && flag4 && flag)
			{
				progress.getDOMWindow(out var ret3);
				((nsIChannel)request).getURI(out var ret4);
				if (ret4 == null)
				{
					currentUri = "about:blank";
				}
				else
				{
					AsciiString asciiString3 = new AsciiString(string.Empty);
					ret4.getSpec(asciiString3.Handle);
					currentUri = asciiString3.ToString();
				}
				ret3.getTop(out var ret5);
				if (ret5 == null || ret5.GetHashCode() == ret3.GetHashCode())
				{
					owner.Reset();
					ret3.getDocument(out var ret6);
					if (ret6 != null)
					{
						owner.document = new Document(owner, ret6);
					}
				}
				LoadCommitedEventHandler loadCommitedEventHandler = (LoadCommitedEventHandler)owner.Events[WebBrowser.LoadCommited];
				if (loadCommitedEventHandler != null)
				{
					LoadCommitedEventArgs e = new LoadCommitedEventArgs(currentUri);
					loadCommitedEventHandler(this, e);
				}
			}
			else if (flag5 && flag4 && flag2)
			{
				progress.getDOMWindow(out var _);
				((nsIChannel)request).getURI(out var ret8);
				if (ret8 == null)
				{
					currentUri = "about:blank";
					return;
				}
				AsciiString asciiString4 = new AsciiString(string.Empty);
				ret8.getSpec(asciiString4.Handle);
				currentUri = asciiString4.ToString();
			}
			else if (flag3 && !flag4 && !flag5 && flag6 && flag7)
			{
				calledLoadStarted = false;
				LoadFinishedEventHandler loadFinishedEventHandler = (LoadFinishedEventHandler)owner.Events[WebBrowser.LoadFinished];
				if (loadFinishedEventHandler != null)
				{
					progress.getDOMWindow(out var _);
					LoadFinishedEventArgs e2 = new LoadFinishedEventArgs(currentUri);
					loadFinishedEventHandler(this, e2);
				}
			}
			else
			{
				if (!(flag3 && !flag4 && flag5) || flag6 || flag7)
				{
					return;
				}
				progress.getDOMWindow(out var ret10);
				ret10.getDocument(out var ret11);
				if (ret11 != null)
				{
					int hashCode = ret11.GetHashCode();
					if (owner.documents.ContainsKey(hashCode))
					{
						((EventHandler)(owner.documents[hashCode] as Document).Events[Document.LoadStopped])?.Invoke(this, null);
					}
				}
				calledLoadStarted = false;
			}
		}

		public void OnProgress(nsIWebProgress progress, nsIRequest request, int currentTotalProgress, int maxTotalProgress)
		{
			Mono.WebBrowser.ProgressChangedEventHandler progressChangedEventHandler = (Mono.WebBrowser.ProgressChangedEventHandler)owner.Events[WebBrowser.ProgressChanged];
			if (progressChangedEventHandler != null)
			{
				Mono.WebBrowser.ProgressChangedEventArgs e = new Mono.WebBrowser.ProgressChangedEventArgs(currentTotalProgress, maxTotalProgress);
				progressChangedEventHandler(this, e);
			}
		}

		public void OnLocationChanged(nsIWebProgress progress, nsIRequest request, nsIURI uri)
		{
		}

		public void OnStatusChange(nsIWebProgress progress, nsIRequest request, string message, int status)
		{
			StatusChangedEventHandler statusChangedEventHandler = (StatusChangedEventHandler)owner.Events[WebBrowser.StatusChanged];
			if (statusChangedEventHandler != null)
			{
				StatusChangedEventArgs e = new StatusChangedEventArgs(message, status);
				statusChangedEventHandler(this, e);
			}
		}

		public void OnSecurityChange(nsIWebProgress progress, nsIRequest request, uint status)
		{
			SecurityChangedEventHandler securityChangedEventHandler = (SecurityChangedEventHandler)owner.Events[WebBrowser.SecurityChanged];
			if (securityChangedEventHandler != null)
			{
				SecurityLevel state = SecurityLevel.Insecure;
				switch (status)
				{
				case 4u:
					state = SecurityLevel.Insecure;
					break;
				case 1u:
					state = SecurityLevel.Mixed;
					break;
				case 2u:
					state = SecurityLevel.Secure;
					break;
				}
				SecurityChangedEventArgs e = new SecurityChangedEventArgs(state);
				securityChangedEventHandler(this, e);
			}
		}

		public bool OnClientDomKeyDown(KeyInfo keyInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode node = new Node(owner, target);
			string key = string.Intern(node.GetHashCode() + ":keydown");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(node, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.KeyDown];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(node);
				nodeEventHandler(this, e2);
				return true;
			}
			return false;
		}

		public bool OnClientDomKeyUp(KeyInfo keyInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode node = new Node(owner, target);
			string key = string.Intern(node.GetHashCode() + ":keyup");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(node, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.KeyUp];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(node);
				nodeEventHandler(this, e2);
				return true;
			}
			return false;
		}

		public bool OnClientDomKeyPress(KeyInfo keyInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode node = new Node(owner, target);
			string key = string.Intern(node.GetHashCode() + ":keypress");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(node, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.KeyPress];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(node);
				nodeEventHandler(this, e2);
				return true;
			}
			return false;
		}

		public bool OnClientMouseDown(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode node = new Node(owner, target);
			string key = string.Intern(node.GetHashCode() + ":mousedown");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(node, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseDown];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(node);
				nodeEventHandler(this, e2);
				return true;
			}
			return false;
		}

		public bool OnClientMouseUp(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode node = new Node(owner, target);
			string key = string.Intern(node.GetHashCode() + ":mouseup");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(node, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseUp];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(node);
				nodeEventHandler(this, e2);
				return true;
			}
			return false;
		}

		public bool OnClientMouseClick(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode node = new Node(owner, target);
			string key = string.Intern(node.GetHashCode() + ":click");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(node, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseClick];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(node);
				nodeEventHandler(this, e2);
				return true;
			}
			return false;
		}

		public bool OnClientMouseDoubleClick(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode node = new Node(owner, target);
			string key = string.Intern(node.GetHashCode() + ":dblclick");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(node, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseDoubleClick];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(node);
				nodeEventHandler(this, e2);
				return true;
			}
			return false;
		}

		public bool OnClientMouseOver(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode typedNode = new DOMObject(owner).GetTypedNode(target);
			string key = string.Intern(typedNode.GetHashCode() + ":mouseover");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(typedNode, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseEnter];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(typedNode);
				nodeEventHandler(typedNode, e2);
				return true;
			}
			return false;
		}

		public bool OnClientMouseOut(MouseInfo mouseInfo, ModifierKeys modifiers, nsIDOMNode target)
		{
			INode node = new Node(owner, target);
			string key = string.Intern(node.GetHashCode() + ":mouseout");
			EventHandler eventHandler = (EventHandler)owner.DomEvents[key];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(node, e);
			}
			NodeEventHandler nodeEventHandler = (NodeEventHandler)owner.Events[WebBrowser.MouseLeave];
			if (nodeEventHandler != null)
			{
				NodeEventArgs e2 = new NodeEventArgs(node);
				nodeEventHandler(this, e2);
				return true;
			}
			return false;
		}

		public bool OnClientActivate()
		{
			return false;
		}

		public bool OnClientFocus()
		{
			EventHandler eventHandler = (EventHandler)owner.Events[WebBrowser.Focus];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(this, e);
			}
			return false;
		}

		public bool OnClientBlur()
		{
			EventHandler eventHandler = (EventHandler)owner.Events[WebBrowser.Blur];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(this, e);
			}
			return false;
		}

		public bool OnCreateNewWindow()
		{
			bool result = false;
			CreateNewWindowEventHandler createNewWindowEventHandler = (CreateNewWindowEventHandler)owner.Events[WebBrowser.CreateNewWindow];
			if (createNewWindowEventHandler != null)
			{
				CreateNewWindowEventArgs e = new CreateNewWindowEventArgs(isModal: false);
				result = createNewWindowEventHandler(this, e);
			}
			return result;
		}

		public void OnAlert(IntPtr title, IntPtr text)
		{
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.Alert;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				alertEventHandler(this, alertEventArgs);
			}
		}

		public bool OnAlertCheck(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState)
		{
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.AlertCheck;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				if (chkMsg != IntPtr.Zero)
				{
					alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg);
				}
				alertEventArgs.CheckState = chkState;
				alertEventHandler(this, alertEventArgs);
				return alertEventArgs.BoolReturn;
			}
			return false;
		}

		public bool OnConfirm(IntPtr title, IntPtr text)
		{
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.Confirm;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				alertEventHandler(this, alertEventArgs);
				return alertEventArgs.BoolReturn;
			}
			return false;
		}

		public bool OnConfirmCheck(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState)
		{
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.ConfirmCheck;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				if (chkMsg != IntPtr.Zero)
				{
					alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg);
				}
				alertEventArgs.CheckState = chkState;
				alertEventHandler(this, alertEventArgs);
				chkState = alertEventArgs.CheckState;
				return alertEventArgs.BoolReturn;
			}
			return false;
		}

		public bool OnConfirmEx(IntPtr title, IntPtr text, DialogButtonFlags flags, IntPtr title0, IntPtr title1, IntPtr title2, IntPtr chkMsg, ref bool chkState, out int retVal)
		{
			retVal = -1;
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.ConfirmEx;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				if (chkMsg != IntPtr.Zero)
				{
					alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg);
				}
				alertEventArgs.CheckState = chkState;
				alertEventHandler(this, alertEventArgs);
				chkState = alertEventArgs.CheckState;
				return alertEventArgs.BoolReturn;
			}
			return false;
		}

		public bool OnPrompt(IntPtr title, IntPtr text, ref IntPtr retVal)
		{
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.Prompt;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				if (retVal != IntPtr.Zero)
				{
					alertEventArgs.Text2 = Marshal.PtrToStringUni(retVal);
				}
				alertEventHandler(this, alertEventArgs);
				retVal = Marshal.StringToHGlobalUni(alertEventArgs.StringReturn);
				return alertEventArgs.BoolReturn;
			}
			return false;
		}

		public bool OnPromptUsernameAndPassword(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState, out IntPtr username, out IntPtr password)
		{
			username = IntPtr.Zero;
			password = IntPtr.Zero;
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.PromptUsernamePassword;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				if (chkMsg != IntPtr.Zero)
				{
					alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg);
				}
				alertEventArgs.CheckState = chkState;
				alertEventHandler(this, alertEventArgs);
				return alertEventArgs.BoolReturn;
			}
			return false;
		}

		public bool OnPromptPassword(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState, out IntPtr password)
		{
			password = IntPtr.Zero;
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.PromptPassword;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				if (chkMsg != IntPtr.Zero)
				{
					alertEventArgs.CheckMessage = Marshal.PtrToStringUni(chkMsg);
				}
				alertEventArgs.CheckState = chkState;
				alertEventHandler(this, alertEventArgs);
				return alertEventArgs.BoolReturn;
			}
			return false;
		}

		public bool OnSelect(IntPtr title, IntPtr text, uint count, IntPtr list, out int retVal)
		{
			retVal = 0;
			AlertEventHandler alertEventHandler = (AlertEventHandler)owner.Events[WebBrowser.Alert];
			if (alertEventHandler != null)
			{
				AlertEventArgs alertEventArgs = new AlertEventArgs();
				alertEventArgs.Type = DialogType.Select;
				if (title != IntPtr.Zero)
				{
					alertEventArgs.Title = Marshal.PtrToStringUni(title);
				}
				if (text != IntPtr.Zero)
				{
					alertEventArgs.Text = Marshal.PtrToStringUni(text);
				}
				alertEventHandler(this, alertEventArgs);
				return alertEventArgs.BoolReturn;
			}
			return false;
		}

		public void OnLoad()
		{
			((Window)owner.Window).OnLoad();
		}

		public void OnUnload()
		{
			((Window)owner.Window).OnUnload();
		}

		public void OnShowContextMenu(uint contextFlags, [MarshalAs(UnmanagedType.Interface)] nsIDOMEvent eve, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode node)
		{
			ContextMenuEventHandler contextMenuEventHandler = (ContextMenuEventHandler)owner.Events[WebBrowser.ContextMenuEvent];
			if (contextMenuEventHandler != null)
			{
				nsIDOMMouseEvent obj = (nsIDOMMouseEvent)eve;
				obj.getClientX(out var ret);
				obj.getClientY(out var ret2);
				ContextMenuEventArgs e = new ContextMenuEventArgs(ret, ret2);
				contextMenuEventHandler(owner, e);
			}
		}

		public void OnGeneric(string type)
		{
			EventHandler eventHandler = (EventHandler)owner.Events[WebBrowser.Generic];
			if (eventHandler != null)
			{
				EventArgs e = new EventArgs();
				eventHandler(type, e);
			}
		}
	}
	internal delegate void CallbackVoid();
	internal delegate void CallbackString(string arg1);
	internal delegate void CallbackWString([MarshalAs(UnmanagedType.LPWStr)] string arg1);
	internal delegate void CallbackStringString(string arg1, string arg2);
	internal delegate void CallbackStringInt(string arg1, int arg2);
	internal delegate void CallbackWStringInt([MarshalAs(UnmanagedType.LPWStr)] string arg1, int arg2);
	internal delegate void CallbackStringIntInt(string arg1, int arg2, int arg3);
	internal delegate void CallbackStringIntUint(string arg1, int arg2, uint arg3);
	internal delegate void CallbackIntInt(int arg1, int arg2);
	internal delegate void CallbackIntUint(int arg2, uint arg3);
	internal delegate void CallbackUint(uint arg1);
	internal delegate void CallbackUintInt(uint arg1, int arg2);
	internal delegate void CallbackPtrPtr(IntPtr arg1, IntPtr arg2);
	internal delegate void CallbackBool(bool val);
	internal delegate bool KeyCallback(KeyInfo keyInfo, ModifierKeys modifiers, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode target);
	internal delegate bool MouseCallback(MouseInfo mouseInfo, ModifierKeys modifiers, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode target);
	internal delegate void GenericCallback(IntPtr type);
	internal delegate bool Callback2();
	internal delegate bool Callback2String(string arg1);
	internal delegate bool CallbackOnAlertCheck(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState);
	internal delegate bool CallbackOnConfirm(IntPtr title, IntPtr text);
	internal delegate bool CallbackOnConfirmCheck(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState);
	internal delegate bool CallbackOnConfirmEx(IntPtr title, IntPtr text, DialogButtonFlags flags, IntPtr title0, IntPtr title1, IntPtr title2, IntPtr chkMsg, ref bool chkState, out int retVal);
	internal delegate bool CallbackOnPrompt(IntPtr title, IntPtr text, ref IntPtr retVal);
	internal delegate bool CallbackOnPromptUsernameAndPassword(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState, out IntPtr username, out IntPtr password);
	internal delegate bool CallbackOnPromptPassword(IntPtr title, IntPtr text, IntPtr chkMsg, ref bool chkState, out IntPtr password);
	internal delegate bool CallbackOnSelect(IntPtr title, IntPtr text, uint count, IntPtr list, out int retVal);
	internal delegate void CallbackOnLocationChanged([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, [MarshalAs(UnmanagedType.Interface)] nsIURI uri);
	internal delegate void CallbackOnStatusChange([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, [MarshalAs(UnmanagedType.LPWStr)] string message, int status);
	internal delegate void CallbackOnSecurityChange([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, uint status);
	internal delegate void CallbackOnStateChange([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, int arg2, uint arg3);
	internal delegate void CallbackOnProgress([MarshalAs(UnmanagedType.Interface)] nsIWebProgress progress, [MarshalAs(UnmanagedType.Interface)] nsIRequest request, int arg2, int arg3);
	internal delegate void CallbackOnShowContextMenu(uint contextFlags, [MarshalAs(UnmanagedType.Interface)] nsIDOMEvent eve, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode node);
	internal struct CallbackBinder
	{
		public CallbackVoid OnWidgetLoaded;

		public CallbackOnStateChange OnStateChange;

		public CallbackOnProgress OnProgress;

		public CallbackOnLocationChanged OnLocationChanged;

		public CallbackOnStatusChange OnStatusChange;

		public CallbackOnSecurityChange OnSecurityChange;

		public KeyCallback OnKeyDown;

		public KeyCallback OnKeyUp;

		public KeyCallback OnKeyPress;

		public MouseCallback OnMouseDown;

		public MouseCallback OnMouseUp;

		public MouseCallback OnMouseClick;

		public MouseCallback OnMouseDoubleClick;

		public MouseCallback OnMouseOver;

		public MouseCallback OnMouseOut;

		public Callback2 OnActivate;

		public Callback2 OnFocus;

		public Callback2 OnBlur;

		public CallbackPtrPtr OnAlert;

		public CallbackOnAlertCheck OnAlertCheck;

		public CallbackOnConfirm OnConfirm;

		public CallbackOnConfirmCheck OnConfirmCheck;

		public CallbackOnConfirmEx OnConfirmEx;

		public CallbackOnPrompt OnPrompt;

		public CallbackOnPromptUsernameAndPassword OnPromptUsernameAndPassword;

		public CallbackOnPromptPassword OnPromptPassword;

		public CallbackOnSelect OnSelect;

		public CallbackVoid OnLoad;

		public CallbackVoid OnUnload;

		public CallbackOnShowContextMenu OnShowContextMenu;

		public CallbackWString OnGeneric;

		internal CallbackBinder(Callback callback)
		{
			OnWidgetLoaded = callback.OnWidgetLoaded;
			OnStateChange = callback.OnStateChange;
			OnProgress = callback.OnProgress;
			OnLocationChanged = callback.OnLocationChanged;
			OnStatusChange = callback.OnStatusChange;
			OnSecurityChange = callback.OnSecurityChange;
			OnKeyDown = callback.OnClientDomKeyDown;
			OnKeyUp = callback.OnClientDomKeyUp;
			OnKeyPress = callback.OnClientDomKeyPress;
			OnMouseDown = callback.OnClientMouseDown;
			OnMouseUp = callback.OnClientMouseUp;
			OnMouseClick = callback.OnClientMouseClick;
			OnMouseDoubleClick = callback.OnClientMouseDoubleClick;
			OnMouseOver = callback.OnClientMouseOver;
			OnMouseOut = callback.OnClientMouseOut;
			OnActivate = callback.OnClientActivate;
			OnFocus = callback.OnClientFocus;
			OnBlur = callback.OnClientBlur;
			OnAlert = callback.OnAlert;
			OnAlertCheck = callback.OnAlertCheck;
			OnConfirm = callback.OnConfirm;
			OnConfirmCheck = callback.OnConfirmCheck;
			OnConfirmEx = callback.OnConfirmEx;
			OnPrompt = callback.OnPrompt;
			OnPromptUsernameAndPassword = callback.OnPromptUsernameAndPassword;
			OnPromptPassword = callback.OnPromptPassword;
			OnSelect = callback.OnSelect;
			OnLoad = callback.OnLoad;
			OnUnload = callback.OnUnload;
			OnShowContextMenu = callback.OnShowContextMenu;
			OnGeneric = callback.OnGeneric;
		}
	}
	internal struct SizeInfo
	{
		public uint width;

		public uint height;
	}
	internal struct ModifierKeys
	{
		public int altKey;

		public int ctrlKey;

		public int metaKey;

		public int shiftKey;
	}
	internal struct MouseInfo
	{
		public ushort button;

		public int clientX;

		public int clientY;

		public int screenX;

		public int screenY;
	}
	internal struct KeyInfo
	{
		public uint charCode;

		public uint keyCode;
	}
	[Flags]
	internal enum StateFlags
	{
		Start = 1,
		Redirecting = 2,
		Transferring = 4,
		Negotiating = 8,
		Stop = 0x10,
		IsRequest = 0x10000,
		IsDocument = 0x20000,
		IsNetwork = 0x40000,
		IsWindow = 0x80000,
		Restoring = 0x1000000,
		IsInsecure = 4,
		IsBroken = 1,
		IsSecure = 2,
		SecureHigh = 0x40000,
		SecureMed = 0x10000,
		SecureLow = 0x20000
	}
	internal class DocumentEncoder : DOMObject
	{
		private nsIDocumentEncoder docEncoder;

		private string mimeType;

		private DocumentEncoderFlags flags;

		public string MimeType
		{
			get
			{
				if (mimeType == null)
				{
					mimeType = "text/html";
				}
				return mimeType;
			}
			set
			{
				mimeType = value;
			}
		}

		public DocumentEncoderFlags Flags
		{
			get
			{
				return flags;
			}
			set
			{
				flags = value;
			}
		}

		public DocumentEncoder(WebBrowser control)
			: base(control)
		{
			IntPtr ret = IntPtr.Zero;
			base.control.ServiceManager.getServiceByContractID("@mozilla.org/layout/documentEncoder;1?type=text/html", typeof(nsIDocumentEncoder).GUID, out ret);
			if (ret == IntPtr.Zero)
			{
				throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.DocumentEncoderService);
			}
			try
			{
				docEncoder = (nsIDocumentEncoder)Marshal.GetObjectForIUnknown(ret);
			}
			catch (System.Exception)
			{
				throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.DocumentEncoderService);
			}
			if (control.platform != control.enginePlatform)
			{
				docEncoder = nsDocumentEncoder.GetProxy(control, docEncoder);
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (disposing)
				{
					docEncoder = null;
				}
				disposed = true;
			}
		}

		private void Init(Document document, string mimeType, DocumentEncoderFlags flags)
		{
			UniString uniString = new UniString(mimeType);
			try
			{
				docEncoder.init((nsIDOMDocument)document.nodeNoProxy, uniString.Handle, (uint)flags);
			}
			catch (System.Exception innerException)
			{
				throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.DocumentEncoderService, innerException);
			}
		}

		public string EncodeToString(Document document)
		{
			Init(document, MimeType, Flags);
			docEncoder.encodeToString(storage);
			return Base.StringGet(storage);
		}

		public string EncodeToString(HTMLElement element)
		{
			Init((Document)element.Owner, MimeType, Flags);
			docEncoder.setNode(element.nodeNoProxy);
			docEncoder.encodeToString(storage);
			string text = Base.StringGet(storage);
			string tagName = element.TagName;
			string text2 = "<" + tagName;
			foreach (IAttribute attribute in element.Attributes)
			{
				text2 = text2 + " " + attribute.Name + "=\"" + attribute.Value + "\"";
			}
			return text2 + ">" + text + "</" + tagName + ">";
		}

		public System.IO.Stream EncodeToStream(Document document)
		{
			Init(document, MimeType, Flags);
			Stream stream = new Stream(new MemoryStream());
			docEncoder.encodeToStream(stream);
			return stream.BaseStream;
		}

		public System.IO.Stream EncodeToStream(HTMLElement element)
		{
			Init((Document)element.Owner, MimeType, Flags);
			docEncoder.setNode(element.nodeNoProxy);
			Stream stream = new Stream(new MemoryStream());
			docEncoder.encodeToStream(stream);
			return stream.BaseStream;
		}
	}
	internal class Stream : nsIInputStream, nsIOutputStream
	{
		private System.IO.Stream back;

		public System.IO.Stream BaseStream => back;

		public Stream(System.IO.Stream stream)
		{
			back = stream;
		}

		public int close()
		{
			back.Close();
			return 0;
		}

		public int flush()
		{
			back.Flush();
			return 0;
		}

		public int write([MarshalAs(UnmanagedType.LPStr)] string str, uint count, out uint ret)
		{
			ret = count;
			if (count == 0)
			{
				return 0;
			}
			byte[] bytes = Encoding.ASCII.GetBytes(str);
			back.Write(bytes, 0, (int)count);
			return 0;
		}

		public int writeFrom([MarshalAs(UnmanagedType.Interface)] nsIInputStream aFromStream, uint aCount, out uint ret)
		{
			ret = 0u;
			return 0;
		}

		public int writeSegments(nsIReadSegmentFunDelegate aReader, IntPtr aClosure, uint aCount, out uint ret)
		{
			ret = 0u;
			return 0;
		}

		public int isNonBlocking(out bool ret)
		{
			ret = false;
			return 0;
		}

		public int available(out uint ret)
		{
			ret = 0u;
			return 0;
		}

		public int read(HandleRef str, uint count, out uint ret)
		{
			byte[] array = new byte[count];
			ret = (uint)back.Read(array, 0, (int)count);
			string @string = Encoding.ASCII.GetString(array);
			Base.StringSet(str, @string);
			return 0;
		}

		public int readSegments(nsIWriteSegmentFunDelegate aWriter, IntPtr aClosure, uint aCount, out uint ret)
		{
			ret = 0u;
			return 0;
		}
	}
	internal class UniString : IDisposable
	{
		[StructLayout(LayoutKind.Sequential)]
		private class nsStringContainer
		{
			private IntPtr v;

			private IntPtr d1;

			private uint d2;

			private IntPtr d3;
		}

		private bool disposed;

		private nsStringContainer unmanagedContainer;

		private HandleRef handle;

		private string str = string.Empty;

		private bool dirty;

		public HandleRef Handle
		{
			get
			{
				dirty = true;
				return handle;
			}
		}

		public string String
		{
			get
			{
				if (dirty)
				{
					Base.gluezilla_StringGetData(handle, out var aBuf, out var _);
					str = Marshal.PtrToStringUni(aBuf);
					dirty = false;
				}
				return str;
			}
			set
			{
				if (str != value)
				{
					str = value;
					Base.gluezilla_StringSetData(handle, str, (uint)str.Length);
				}
			}
		}

		public int Length => String.Length;

		public UniString(string value)
		{
			unmanagedContainer = new nsStringContainer();
			IntPtr ptr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(nsStringContainer)));
			Marshal.StructureToPtr(unmanagedContainer, ptr, fDeleteOld: false);
			handle = new HandleRef(typeof(nsStringContainer), ptr);
			Base.gluezilla_StringContainerInit(handle);
			String = value;
		}

		~UniString()
		{
			Dispose(disposing: false);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!disposed)
			{
				if (disposing)
				{
					Base.gluezilla_StringContainerFinish(handle);
					Marshal.FreeHGlobal(handle.Handle);
				}
				disposed = true;
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		public override string ToString()
		{
			return String;
		}
	}
	internal class WebBrowser : IWebBrowser
	{
		private bool loaded;

		internal bool created;

		private bool creating;

		internal Document document;

		internal Navigation navigation;

		internal Platform platform;

		internal Platform enginePlatform;

		internal Callback callbacks;

		private EventHandlerList events;

		private EventHandlerList domEvents;

		private string statusText;

		private bool streamingMode;

		internal Hashtable documents;

		private int width;

		private int height;

		private bool isDirty;

		private ContentListener contentListener;

		private nsIServiceManager servMan;

		private nsIIOService ioService;

		private nsIAccessibilityService accessibilityService;

		private nsIErrorService errorService;

		private DocumentEncoder docEncoder;

		internal static object KeyDownEvent;

		internal static object KeyPressEvent;

		internal static object KeyUpEvent;

		internal static object MouseClickEvent;

		internal static object MouseDoubleClickEvent;

		internal static object MouseDownEvent;

		internal static object MouseEnterEvent;

		internal static object MouseLeaveEvent;

		internal static object MouseMoveEvent;

		internal static object MouseUpEvent;

		internal static object FocusEvent;

		internal static object BlurEvent;

		internal static object CreateNewWindowEvent;

		internal static object AlertEvent;

		internal static object LoadStartedEvent;

		internal static object LoadCommitedEvent;

		internal static object ProgressChangedEvent;

		internal static object LoadFinishedEvent;

		internal static object LoadEvent;

		internal static object UnloadEvent;

		internal static object StatusChangedEvent;

		internal static object SecurityChangedEvent;

		internal static object ProgressEvent;

		internal static object ContextMenuEvent;

		internal static object NavigationRequestedEvent;

		internal static object GenericEvent;

		private bool Created
		{
			get
			{
				if (!creating && !created)
				{
					creating = true;
					created = Base.Create(this);
					if (created && isDirty)
					{
						isDirty = false;
						Base.Resize(this, width, height);
					}
				}
				return created;
			}
		}

		public bool Initialized => loaded;

		public IWindow Window
		{
			get
			{
				if (Navigation != null)
				{
					((nsIWebBrowserFocus)navigation.navigation).getFocusedWindow(out var ret);
					if (ret == null)
					{
						((nsIWebBrowser)navigation.navigation).getContentDOMWindow(out ret);
					}
					if (ret != null)
					{
						return new Window(this, ret);
					}
				}
				return null;
			}
		}

		public IDocument Document
		{
			get
			{
				if (Navigation != null && document == null)
				{
					document = navigation.Document;
				}
				return document;
			}
		}

		public INavigation Navigation
		{
			get
			{
				if (!Created)
				{
					return null;
				}
				if (navigation == null)
				{
					nsIWebNavigation webNavigation = Base.GetWebNavigation(this);
					navigation = new Navigation(this, webNavigation);
				}
				return navigation;
			}
		}

		public string StatusText => statusText;

		public bool Offline
		{
			get
			{
				if (!Created)
				{
					return true;
				}
				IOService.getOffline(out var ret);
				return ret;
			}
			set
			{
				IOService.setOffline(value);
			}
		}

		internal EventHandlerList DomEvents
		{
			get
			{
				if (domEvents == null)
				{
					domEvents = new EventHandlerList();
				}
				return domEvents;
			}
		}

		internal EventHandlerList Events
		{
			get
			{
				if (events == null)
				{
					events = new EventHandlerList();
				}
				return events;
			}
		}

		private ContentListener ContentListener
		{
			get
			{
				if (contentListener == null)
				{
					contentListener = new ContentListener(this);
				}
				return contentListener;
			}
		}

		internal nsIServiceManager ServiceManager
		{
			get
			{
				if (servMan == null)
				{
					servMan = Base.GetServiceManager(this);
				}
				return servMan;
			}
		}

		internal nsIIOService IOService
		{
			get
			{
				if (ioService == null)
				{
					IntPtr ret = IntPtr.Zero;
					ServiceManager.getServiceByContractID("@mozilla.org/network/io-service;1", typeof(nsIIOService).GUID, out ret);
					if (ret == IntPtr.Zero)
					{
						throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.IOService);
					}
					try
					{
						ioService = (nsIIOService)Marshal.GetObjectForIUnknown(ret);
					}
					catch (System.Exception innerException)
					{
						throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.IOService, innerException);
					}
				}
				return ioService;
			}
		}

		internal nsIAccessibilityService AccessibilityService
		{
			get
			{
				if (accessibilityService == null)
				{
					IntPtr ret = IntPtr.Zero;
					ServiceManager.getServiceByContractID("@mozilla.org/accessibilityService;1", typeof(nsIAccessibilityService).GUID, out ret);
					if (ret == IntPtr.Zero)
					{
						throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.AccessibilityService);
					}
					try
					{
						accessibilityService = (nsIAccessibilityService)Marshal.GetObjectForIUnknown(ret);
					}
					catch (System.Exception innerException)
					{
						throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.AccessibilityService, innerException);
					}
				}
				return accessibilityService;
			}
		}

		internal nsIErrorService ErrorService
		{
			get
			{
				if (errorService == null)
				{
					IntPtr ret = IntPtr.Zero;
					ServiceManager.getServiceByContractID("@mozilla.org/xpcom/error-service;1", typeof(nsIErrorService).GUID, out ret);
					if (ret == IntPtr.Zero)
					{
						return null;
					}
					try
					{
						errorService = (nsIErrorService)Marshal.GetObjectForIUnknown(ret);
					}
					catch (System.Exception)
					{
						return null;
					}
				}
				return errorService;
			}
		}

		internal DocumentEncoder DocEncoder
		{
			get
			{
				if (docEncoder == null)
				{
					docEncoder = new DocumentEncoder(this);
				}
				return docEncoder;
			}
		}

		public event NodeEventHandler KeyDown
		{
			add
			{
				Events.AddHandler(KeyDownEvent, value);
			}
			remove
			{
				Events.RemoveHandler(KeyDownEvent, value);
			}
		}

		public event NodeEventHandler KeyPress
		{
			add
			{
				Events.AddHandler(KeyPressEvent, value);
			}
			remove
			{
				Events.RemoveHandler(KeyPressEvent, value);
			}
		}

		public event NodeEventHandler KeyUp
		{
			add
			{
				Events.AddHandler(KeyUpEvent, value);
			}
			remove
			{
				Events.RemoveHandler(KeyUpEvent, value);
			}
		}

		public event NodeEventHandler MouseClick
		{
			add
			{
				Events.AddHandler(MouseClickEvent, value);
			}
			remove
			{
				Events.RemoveHandler(MouseClickEvent, value);
			}
		}

		public event NodeEventHandler MouseDoubleClick
		{
			add
			{
				Events.AddHandler(MouseDoubleClickEvent, value);
			}
			remove
			{
				Events.RemoveHandler(MouseDoubleClickEvent, value);
			}
		}

		public event NodeEventHandler MouseDown
		{
			add
			{
				Events.AddHandler(MouseDownEvent, value);
			}
			remove
			{
				Events.RemoveHandler(MouseDownEvent, value);
			}
		}

		public event NodeEventHandler MouseEnter
		{
			add
			{
				Events.AddHandler(MouseEnterEvent, value);
			}
			remove
			{
				Events.RemoveHandler(MouseEnterEvent, value);
			}
		}

		public event NodeEventHandler MouseLeave
		{
			add
			{
				Events.AddHandler(MouseLeaveEvent, value);
			}
			remove
			{
				Events.RemoveHandler(MouseLeaveEvent, value);
			}
		}

		public event NodeEventHandler MouseMove
		{
			add
			{
				Events.AddHandler(MouseMoveEvent, value);
			}
			remove
			{
				Events.RemoveHandler(MouseMoveEvent, value);
			}
		}

		public event NodeEventHandler MouseUp
		{
			add
			{
				Events.AddHandler(MouseUpEvent, value);
			}
			remove
			{
				Events.RemoveHandler(MouseUpEvent, value);
			}
		}

		public event EventHandler Focus
		{
			add
			{
				Events.AddHandler(FocusEvent, value);
			}
			remove
			{
				Events.RemoveHandler(FocusEvent, value);
			}
		}

		public event EventHandler Blur
		{
			add
			{
				Events.AddHandler(BlurEvent, value);
			}
			remove
			{
				Events.RemoveHandler(BlurEvent, value);
			}
		}

		public event CreateNewWindowEventHandler CreateNewWindow
		{
			add
			{
				Events.AddHandler(CreateNewWindowEvent, value);
			}
			remove
			{
				Events.RemoveHandler(CreateNewWindowEvent, value);
			}
		}

		public event AlertEventHandler Alert
		{
			add
			{
				Events.AddHandler(AlertEvent, value);
			}
			remove
			{
				Events.RemoveHandler(AlertEvent, value);
			}
		}

		public event EventHandler Loaded
		{
			add
			{
				Events.AddHandler(LoadEvent, value);
			}
			remove
			{
				Events.RemoveHandler(LoadEvent, value);
			}
		}

		public event EventHandler Unloaded
		{
			add
			{
				Events.AddHandler(UnloadEvent, value);
			}
			remove
			{
				Events.RemoveHandler(UnloadEvent, value);
			}
		}

		public event StatusChangedEventHandler StatusChanged
		{
			add
			{
				Events.AddHandler(StatusChangedEvent, value);
			}
			remove
			{
				Events.RemoveHandler(StatusChangedEvent, value);
			}
		}

		public event SecurityChangedEventHandler SecurityChanged
		{
			add
			{
				Events.AddHandler(SecurityChangedEvent, value);
			}
			remove
			{
				Events.RemoveHandler(SecurityChangedEvent, value);
			}
		}

		public event LoadStartedEventHandler LoadStarted
		{
			add
			{
				Events.AddHandler(LoadStartedEvent, value);
			}
			remove
			{
				Events.RemoveHandler(LoadStartedEvent, value);
			}
		}

		public event LoadCommitedEventHandler LoadCommited
		{
			add
			{
				Events.AddHandler(LoadCommitedEvent, value);
			}
			remove
			{
				Events.RemoveHandler(LoadCommitedEvent, value);
			}
		}

		public event Mono.WebBrowser.ProgressChangedEventHandler ProgressChanged
		{
			add
			{
				Events.AddHandler(ProgressChangedEvent, value);
			}
			remove
			{
				Events.RemoveHandler(ProgressChangedEvent, value);
			}
		}

		public event LoadFinishedEventHandler LoadFinished
		{
			add
			{
				Events.AddHandler(LoadFinishedEvent, value);
			}
			remove
			{
				Events.RemoveHandler(LoadFinishedEvent, value);
			}
		}

		public event ContextMenuEventHandler ContextMenuShown
		{
			add
			{
				Events.AddHandler(ContextMenuEvent, value);
			}
			remove
			{
				Events.RemoveHandler(ContextMenuEvent, value);
			}
		}

		public event NavigationRequestedEventHandler NavigationRequested
		{
			add
			{
				ContentListener.AddHandler(value);
			}
			remove
			{
				ContentListener.RemoveHandler(value);
			}
		}

		internal event EventHandler Generic
		{
			add
			{
				Events.AddHandler(GenericEvent, value);
			}
			remove
			{
				Events.RemoveHandler(GenericEvent, value);
			}
		}

		public WebBrowser(Platform platform)
		{
			this.platform = platform;
			callbacks = new Callback(this);
			loaded = Base.Init(this, platform);
			documents = new Hashtable();
		}

		public bool Load(IntPtr handle, int width, int height)
		{
			loaded = Base.Bind(this, handle, width, height);
			return loaded;
		}

		public void Shutdown()
		{
			Base.Shutdown(this);
		}

		internal void Reset()
		{
			document = null;
			DomEvents.Dispose();
			domEvents = null;
			documents.Clear();
		}

		public void FocusIn(FocusOption focus)
		{
			if (created)
			{
				Base.Focus(this, focus);
			}
		}

		public void FocusOut()
		{
			if (created)
			{
				Base.Blur(this);
			}
		}

		public void Activate()
		{
			if (Created)
			{
				Base.Activate(this);
			}
		}

		public void Deactivate()
		{
			if (created)
			{
				Base.Deactivate(this);
			}
		}

		public void Resize(int width, int height)
		{
			this.width = width;
			this.height = height;
			isDirty = true;
			if (created)
			{
				Base.Resize(this, width, height);
			}
		}

		public void Render(byte[] data)
		{
			if (Created)
			{
				if (data == null)
				{
					throw new ArgumentNullException("data");
				}
				string @string = Encoding.UTF8.GetString(data);
				Render(@string);
			}
		}

		public void Render(string html)
		{
			if (Created)
			{
				Render(html, "file:///", "text/html");
			}
		}

		public void Render(string html, string uri, string contentType)
		{
			if (Created)
			{
				if (Navigation == null)
				{
					throw new Mono.WebBrowser.Exception(Mono.WebBrowser.Exception.ErrorCodes.Navigation);
				}
				nsIWebBrowserStream nsIWebBrowserStream2 = (nsIWebBrowserStream)navigation.navigation;
				AsciiString asciiString = new AsciiString(uri);
				IOService.newURI(asciiString.Handle, null, null, out var ret);
				HandleRef handle = new AsciiString(contentType).Handle;
				nsIWebBrowserStream2.openStream(ret, handle);
				IntPtr intPtr = Marshal.StringToHGlobalAnsi(html);
				nsIWebBrowserStream2.appendToStream(intPtr, (uint)html.Length);
				Marshal.FreeHGlobal(intPtr);
				nsIWebBrowserStream2.closeStream();
			}
		}

		public void ExecuteScript(string script)
		{
			if (Created)
			{
				Base.EvalScript(this, script);
			}
		}

		internal void AttachEvent(INode node, string eve, EventHandler handler)
		{
			string key = string.Intern(node.GetHashCode() + ":" + eve);
			DomEvents.AddHandler(key, handler);
		}

		internal void DetachEvent(INode node, string eve, EventHandler handler)
		{
			string key = string.Intern(node.GetHashCode() + ":" + eve);
			DomEvents.RemoveHandler(key, handler);
		}

		static WebBrowser()
		{
			KeyDown = new object();
			KeyPress = new object();
			KeyUp = new object();
			MouseClick = new object();
			MouseDoubleClick = new object();
			MouseDown = new object();
			MouseEnter = new object();
			MouseLeave = new object();
			MouseMove = new object();
			MouseUp = new object();
			Focus = new object();
			Blur = new object();
			CreateNewWindow = new object();
			Alert = new object();
			LoadStarted = new object();
			LoadCommited = new object();
			ProgressChanged = new object();
			LoadFinished = new object();
			LoadEvent = new object();
			UnloadEvent = new object();
			StatusChanged = new object();
			SecurityChanged = new object();
			ProgressEvent = new object();
			ContextMenuEvent = new object();
			NavigationRequested = new object();
			Generic = new object();
		}
	}
	internal enum StopOption : uint
	{
		Network = 1u,
		Content,
		All
	}
	internal delegate void nsIReadSegmentFunDelegate([MarshalAs(UnmanagedType.Interface)] nsIOutputStream aInStream, IntPtr aClosure, string aFromSegment, uint aCount, out uint aWriteCount);
	internal delegate void nsITimerCallbackDelegate([MarshalAs(UnmanagedType.Interface)] nsITimer timer, IntPtr closure);
	internal delegate void nsIWriteSegmentFunDelegate([MarshalAs(UnmanagedType.Interface)] nsIInputStream aInStream, IntPtr aClosure, string aFromSegment, uint aToOffset, uint aCount, out uint aWriteCount);
	[ComImport]
	[Guid("71a3b4e7-e83d-45cf-a20e-9ce292bcf19f")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface nsIAccessNode
	{
		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getDOMNode([MarshalAs(UnmanagedType.Interface)] out nsIDOMNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getNumChildren(out int ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getChildNodeAt(int childNum, [MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getParentNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getFirstChildNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getLastChildNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getPreviousSiblingNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getNextSiblingNode([MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getAccessibleDocument([MarshalAs(UnmanagedType.Interface)] out nsIAccessibleDocument ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getInnerHTML(HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int scrollTo(uint aScrollType);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int scrollToPoint(uint aCoordinateType, int aX, int aY);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getOwnerWindow(IntPtr ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getUniqueID(IntPtr ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getComputedStyleValue(HandleRef pseudoElt, HandleRef propertyName, HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getComputedStyleCSSValue(HandleRef pseudoElt, HandleRef propertyName, [MarshalAs(UnmanagedType.Interface)] out nsIDOMCSSPrimitiveValue ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getLanguage(HandleRef ret);
	}
	internal class nsAccessNode
	{
		public static nsIAccessNode GetProxy(IWebBrowser control, nsIAccessNode obj)
		{
			return Base.GetProxyForObject(control, typeof(nsIAccessNode).GUID, obj) as nsIAccessNode;
		}
	}
	[ComImport]
	[Guid("27386cf1-f27e-4d2d-9bf4-c4621d50d299")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface nsIAccessibilityService : nsIAccessibleRetrieval
	{
		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getAccessibleFor([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getAttachedAccessibleFor([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getRelevantContentNodeFor([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] out nsIDOMNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getAccessibleInWindow([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIDOMWindow aDOMWin, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getAccessibleInWeakShell([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getAccessibleInShell([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, IntPtr aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getCachedAccessNode([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessNode ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getCachedAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getStringRole(uint aRole, HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getStringStates(uint aStates, uint aExtraStates, [MarshalAs(UnmanagedType.Interface)] out nsIDOMDOMStringList ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getStringEventType(uint aEventType, HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		new int getStringRelationType(uint aRelationType, HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createOuterDocAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createRootAccessible(IntPtr aShell, IntPtr aDocument, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTML4ButtonAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHyperTextAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLBRAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLButtonAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLAccessibleByMarkup(IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aWeakShell, [MarshalAs(UnmanagedType.Interface)] nsIDOMNode aDOMNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLLIAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] IntPtr aBulletFrame, HandleRef aBulletText, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLCheckboxAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLComboboxAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLGenericAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLGroupboxAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLHRAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLImageAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLLabelAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLListboxAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLObjectFrameAccessible(IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLRadioButtonAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLSelectOptionAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, [MarshalAs(UnmanagedType.Interface)] nsIAccessible aAccParent, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aPresShell, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLTableAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLTableCellAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLTableHeadAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aDOMNode, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLTextAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLTextFieldAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int createHTMLCaptionAccessible([MarshalAs(UnmanagedType.Interface)] IntPtr aFrame, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getAccessible([MarshalAs(UnmanagedType.Interface)] nsIDOMNode aNode, IntPtr aPresShell, [MarshalAs(UnmanagedType.Interface)] nsIWeakReference aWeakShell, out IntPtr frameHint, out bool aIsHidden, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int addNativeRootAccessible(IntPtr aAtkAccessible, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int removeNativeRootAccessible([MarshalAs(UnmanagedType.Interface)] nsIAccessible aRootAccessible);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int invalidateSubtreeFor(IntPtr aPresShell, IntPtr aChangedContent, uint aEvent);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int processDocLoadEvent([MarshalAs(UnmanagedType.Interface)] nsITimer aTimer, IntPtr aClosure, uint aEventType);
	}
	internal class nsAccessibilityService
	{
		public static nsIAccessibilityService GetProxy(IWebBrowser control, nsIAccessibilityService obj)
		{
			return Base.GetProxyForObject(control, typeof(nsIAccessibilityService).GUID, obj) as nsIAccessibilityService;
		}
	}
	[ComImport]
	[Guid("004b6882-2df1-49df-bb5f-0fb81a5b1edf")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	internal interface nsIAccessible
	{
		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getParent([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getNextSibling([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getPreviousSibling([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getFirstChild([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getLastChild([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getChildren([MarshalAs(UnmanagedType.Interface)] out nsIArray ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getChildCount(out int ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getIndexInParent(out int ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getName(HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int setName(HandleRef value);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getValue(HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getDescription(HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getKeyboardShortcut(HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getDefaultKeyBinding(HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getKeyBindings(char aActionIndex, [MarshalAs(UnmanagedType.Interface)] out nsIDOMDOMStringList ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getRole(out uint ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getFinalRole(out uint ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getFinalState(out uint aState, out uint aExtraState);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getHelp(HandleRef ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getFocusedChild([MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getAttributes([MarshalAs(UnmanagedType.Interface)] out nsIPersistentProperties ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int groupPosition(out int aGroupLevel, out int aSimilarItemsInGroup, out int aPositionInGroup);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getChildAtPoint(int x, int y, [MarshalAs(UnmanagedType.Interface)] out nsIAccessible ret);

		[MethodImpl(MethodImplOptions.PreserveSig | MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
		int getChildAt(in

BepInEx/core/mscorlib.dll

Decompiled 2 weeks ago
#define CONTRACTS_FULL
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration.Assemblies;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Diagnostics.SymbolStore;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.IO.Enumeration;
using System.Numerics;
using System.Numerics.Hashing;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.ExceptionServices;
using System.Runtime.Hosting;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Lifetime;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Metadata;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Remoting.Services;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.AccessControl;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Principal;
using System.Security.Util;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Internal.Cryptography;
using Internal.Runtime.Augments;
using Internal.Threading.Tasks.Tracing;
using Microsoft.CodeAnalysis;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using Mono;
using Mono.Globalization.Unicode;
using Mono.Interop;
using Mono.Math;
using Mono.Math.Prime;
using Mono.Math.Prime.Generator;
using Mono.Security;
using Mono.Security.Cryptography;
using Mono.Xml;
using Unity;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("mscorlib.dll")]
[assembly: AssemblyDescription("mscorlib.dll")]
[assembly: AssemblyDefaultAlias("mscorlib.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyKeyFile("../ecma.pub")]
[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: ComVisible(false)]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: DefaultDependency(LoadHint.Always)]
[assembly: StringFreezing]
[assembly: InternalsVisibleTo("System, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Core, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Security, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Runtime.WindowsRuntime.UI.Xaml, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Net.Http, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: Guid("BED7F4EA-1A96-11D2-8F08-00A0C9A6186D")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
}
internal static class Interop
{
	internal static class Kernel32
	{
		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct WIN32_FIND_DATA
		{
			internal uint dwFileAttributes;

			internal FILE_TIME ftCreationTime;

			internal FILE_TIME ftLastAccessTime;

			internal FILE_TIME ftLastWriteTime;

			internal uint nFileSizeHigh;

			internal uint nFileSizeLow;

			internal uint dwReserved0;

			internal uint dwReserved1;

			private unsafe fixed char _cFileName[260];

			private unsafe fixed char _cAlternateFileName[14];

			internal unsafe ReadOnlySpan<char> cFileName
			{
				get
				{
					fixed (char* pointer = _cFileName)
					{
						return new ReadOnlySpan<char>(pointer, 260);
					}
				}
			}
		}

		internal struct REG_TZI_FORMAT
		{
			internal int Bias;

			internal int StandardBias;

			internal int DaylightBias;

			internal SYSTEMTIME StandardDate;

			internal SYSTEMTIME DaylightDate;

			internal REG_TZI_FORMAT(in TIME_ZONE_INFORMATION tzi)
			{
				Bias = tzi.Bias;
				StandardDate = tzi.StandardDate;
				StandardBias = tzi.StandardBias;
				DaylightDate = tzi.DaylightDate;
				DaylightBias = tzi.DaylightBias;
			}
		}

		internal struct SYSTEMTIME
		{
			internal ushort Year;

			internal ushort Month;

			internal ushort DayOfWeek;

			internal ushort Day;

			internal ushort Hour;

			internal ushort Minute;

			internal ushort Second;

			internal ushort Milliseconds;

			internal bool Equals(in SYSTEMTIME other)
			{
				if (Year == other.Year && Month == other.Month && DayOfWeek == other.DayOfWeek && Day == other.Day && Hour == other.Hour && Minute == other.Minute && Second == other.Second)
				{
					return Milliseconds == other.Milliseconds;
				}
				return false;
			}
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct TIME_DYNAMIC_ZONE_INFORMATION
		{
			internal int Bias;

			internal unsafe fixed char StandardName[32];

			internal SYSTEMTIME StandardDate;

			internal int StandardBias;

			internal unsafe fixed char DaylightName[32];

			internal SYSTEMTIME DaylightDate;

			internal int DaylightBias;

			internal unsafe fixed char TimeZoneKeyName[128];

			internal byte DynamicDaylightTimeDisabled;

			internal unsafe string GetTimeZoneKeyName()
			{
				fixed (char* value = TimeZoneKeyName)
				{
					return new string(value);
				}
			}
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct TIME_ZONE_INFORMATION
		{
			internal int Bias;

			internal unsafe fixed char StandardName[32];

			internal SYSTEMTIME StandardDate;

			internal int StandardBias;

			internal unsafe fixed char DaylightName[32];

			internal SYSTEMTIME DaylightDate;

			internal int DaylightBias;

			internal unsafe TIME_ZONE_INFORMATION(in TIME_DYNAMIC_ZONE_INFORMATION dtzi)
			{
				fixed (TIME_ZONE_INFORMATION* ptr = &this)
				{
					fixed (TIME_DYNAMIC_ZONE_INFORMATION* ptr2 = &dtzi)
					{
						*ptr = *(TIME_ZONE_INFORMATION*)ptr2;
					}
				}
			}

			internal unsafe string GetStandardName()
			{
				fixed (char* value = StandardName)
				{
					return new string(value);
				}
			}

			internal unsafe string GetDaylightName()
			{
				fixed (char* value = DaylightName)
				{
					return new string(value);
				}
			}
		}

		internal enum FILE_INFO_BY_HANDLE_CLASS : uint
		{
			FileBasicInfo,
			FileStandardInfo,
			FileNameInfo,
			FileRenameInfo,
			FileDispositionInfo,
			FileAllocationInfo,
			FileEndOfFileInfo,
			FileStreamInfo,
			FileCompressionInfo,
			FileAttributeTagInfo,
			FileIdBothDirectoryInfo,
			FileIdBothDirectoryRestartInfo,
			FileIoPriorityHintInfo,
			FileRemoteProtocolInfo,
			FileFullDirectoryInfo,
			FileFullDirectoryRestartInfo
		}

		internal struct FILE_TIME
		{
			internal uint dwLowDateTime;

			internal uint dwHighDateTime;

			internal FILE_TIME(long fileTime)
			{
				dwLowDateTime = (uint)fileTime;
				dwHighDateTime = (uint)(fileTime >> 32);
			}

			internal long ToTicks()
			{
				return (long)(((ulong)dwHighDateTime << 32) + dwLowDateTime);
			}

			internal DateTime ToDateTimeUtc()
			{
				return DateTime.FromFileTimeUtc(ToTicks());
			}

			internal DateTimeOffset ToDateTimeOffset()
			{
				return DateTimeOffset.FromFileTime(ToTicks());
			}
		}

		internal enum FINDEX_INFO_LEVELS : uint
		{
			FindExInfoStandard,
			FindExInfoBasic,
			FindExInfoMaxInfoLevel
		}

		internal enum FINDEX_SEARCH_OPS : uint
		{
			FindExSearchNameMatch,
			FindExSearchLimitToDirectories,
			FindExSearchLimitToDevices,
			FindExSearchMaxSearchOp
		}

		internal class FileAttributes
		{
			internal const int FILE_ATTRIBUTE_NORMAL = 128;

			internal const int FILE_ATTRIBUTE_READONLY = 1;

			internal const int FILE_ATTRIBUTE_DIRECTORY = 16;

			internal const int FILE_ATTRIBUTE_REPARSE_POINT = 1024;
		}

		internal class IOReparseOptions
		{
			internal const uint IO_REPARSE_TAG_FILE_PLACEHOLDER = 2147483669u;

			internal const uint IO_REPARSE_TAG_MOUNT_POINT = 2684354563u;
		}

		internal class FileOperations
		{
			internal const int OPEN_EXISTING = 3;

			internal const int COPY_FILE_FAIL_IF_EXISTS = 1;

			internal const int FILE_ACTION_ADDED = 1;

			internal const int FILE_ACTION_REMOVED = 2;

			internal const int FILE_ACTION_MODIFIED = 3;

			internal const int FILE_ACTION_RENAMED_OLD_NAME = 4;

			internal const int FILE_ACTION_RENAMED_NEW_NAME = 5;

			internal const int FILE_FLAG_BACKUP_SEMANTICS = 33554432;

			internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 524288;

			internal const int FILE_FLAG_OVERLAPPED = 1073741824;

			internal const int FILE_LIST_DIRECTORY = 1;
		}

		internal enum GET_FILEEX_INFO_LEVELS : uint
		{
			GetFileExInfoStandard,
			GetFileExMaxInfoLevel
		}

		internal class GenericOperations
		{
			internal const int GENERIC_READ = int.MinValue;

			internal const int GENERIC_WRITE = 1073741824;
		}

		internal struct SECURITY_ATTRIBUTES
		{
			internal uint nLength;

			internal IntPtr lpSecurityDescriptor;

			internal BOOL bInheritHandle;
		}

		internal struct FILE_BASIC_INFO
		{
			internal long CreationTime;

			internal long LastAccessTime;

			internal long LastWriteTime;

			internal long ChangeTime;

			internal uint FileAttributes;
		}

		internal struct WIN32_FILE_ATTRIBUTE_DATA
		{
			internal int dwFileAttributes;

			internal FILE_TIME ftCreationTime;

			internal FILE_TIME ftLastAccessTime;

			internal FILE_TIME ftLastWriteTime;

			internal uint nFileSizeHigh;

			internal uint nFileSizeLow;

			internal void PopulateFrom(ref WIN32_FIND_DATA findData)
			{
				dwFileAttributes = (int)findData.dwFileAttributes;
				ftCreationTime = findData.ftCreationTime;
				ftLastAccessTime = findData.ftLastAccessTime;
				ftLastWriteTime = findData.ftLastWriteTime;
				nFileSizeHigh = findData.nFileSizeHigh;
				nFileSizeLow = findData.nFileSizeLow;
			}
		}

		internal const int LOAD_LIBRARY_AS_DATAFILE = 2;

		internal const int MAX_PATH = 260;

		internal const uint MUI_PREFERRED_UI_LANGUAGES = 16u;

		internal const uint TIME_ZONE_ID_INVALID = uint.MaxValue;

		internal const uint SEM_FAILCRITICALERRORS = 1u;

		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;

		internal const int REPLACEFILE_IGNORE_MERGE_ERRORS = 2;

		internal static int CopyFile(string src, string dst, bool failIfExists)
		{
			int flags = (failIfExists ? 1 : 0);
			int cancel = 0;
			if (!CopyFileEx(src, dst, IntPtr.Zero, IntPtr.Zero, ref cancel, flags))
			{
				return Marshal.GetLastWin32Error();
			}
			return 0;
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "DeleteVolumeMountPointW", SetLastError = true)]
		internal static extern bool DeleteVolumeMountPointPrivate(string mountPoint);

		internal static bool DeleteVolumeMountPoint(string mountPoint)
		{
			mountPoint = PathInternal.EnsureExtendedPrefixIfNeeded(mountPoint);
			return DeleteVolumeMountPointPrivate(mountPoint);
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern bool FreeLibrary(IntPtr hModule);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "LoadLibraryExW", SetLastError = true)]
		internal static extern SafeLibraryHandle LoadLibraryEx(string libFilename, IntPtr reserved, int flags);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern bool GetFileMUIPath(uint flags, string filePath, [Out] StringBuilder language, ref int languageLength, [Out] StringBuilder fileMuiPath, ref int fileMuiPathLength, ref long enumerator);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern uint GetDynamicTimeZoneInformation(out TIME_DYNAMIC_ZONE_INFORMATION pTimeZoneInformation);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern uint GetTimeZoneInformation(out TIME_ZONE_INFORMATION lpTimeZoneInformation);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CloseHandle(IntPtr handle);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CopyFileExW", SetLastError = true)]
		private static extern bool CopyFileExPrivate(string src, string dst, IntPtr progressRoutine, IntPtr progressData, ref int cancel, int flags);

		internal static bool CopyFileEx(string src, string dst, IntPtr progressRoutine, IntPtr progressData, ref int cancel, int flags)
		{
			src = PathInternal.EnsureExtendedPrefixIfNeeded(src);
			dst = PathInternal.EnsureExtendedPrefixIfNeeded(dst);
			return CopyFileExPrivate(src, dst, progressRoutine, progressData, ref cancel, flags);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateDirectoryW", SetLastError = true)]
		private static extern bool CreateDirectoryPrivate(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes);

		internal static bool CreateDirectory(string path, ref SECURITY_ATTRIBUTES lpSecurityAttributes)
		{
			path = PathInternal.EnsureExtendedPrefix(path);
			return CreateDirectoryPrivate(path, ref lpSecurityAttributes);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", ExactSpelling = true, SetLastError = true)]
		private unsafe static extern IntPtr CreateFilePrivate(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);

		internal unsafe static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, ref SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)
		{
			lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName);
			fixed (SECURITY_ATTRIBUTES* securityAttrs2 = &securityAttrs)
			{
				IntPtr intPtr = CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, securityAttrs2, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
				try
				{
					return new SafeFileHandle(intPtr, ownsHandle: true);
				}
				catch
				{
					CloseHandle(intPtr);
					throw;
				}
			}
		}

		internal static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes)
		{
			IntPtr intPtr = CreateFile_IntPtr(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, dwFlagsAndAttributes);
			try
			{
				return new SafeFileHandle(intPtr, ownsHandle: true);
			}
			catch
			{
				CloseHandle(intPtr);
				throw;
			}
		}

		internal unsafe static IntPtr CreateFile_IntPtr(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes)
		{
			lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName);
			return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "DeleteFileW", SetLastError = true)]
		private static extern bool DeleteFilePrivate(string path);

		internal static bool DeleteFile(string path)
		{
			path = PathInternal.EnsureExtendedPrefixIfNeeded(path);
			return DeleteFilePrivate(path);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "FindFirstFileExW", SetLastError = true)]
		private static extern SafeFindHandle FindFirstFileExPrivate(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, ref WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, int dwAdditionalFlags);

		internal static SafeFindHandle FindFirstFile(string fileName, ref WIN32_FIND_DATA data)
		{
			fileName = PathInternal.EnsureExtendedPrefixIfNeeded(fileName);
			return FindFirstFileExPrivate(fileName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "FindNextFileW", SetLastError = true)]
		internal static extern bool FindNextFile(SafeFindHandle hndFindFile, ref WIN32_FIND_DATA lpFindFileData);

		[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;
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetFileAttributesExW", SetLastError = true)]
		private static extern bool GetFileAttributesExPrivate(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation);

		internal static bool GetFileAttributesEx(string name, GET_FILEEX_INFO_LEVELS fileInfoLevel, ref WIN32_FILE_ATTRIBUTE_DATA lpFileInformation)
		{
			name = PathInternal.EnsureExtendedPrefixIfNeeded(name);
			return GetFileAttributesExPrivate(name, fileInfoLevel, ref lpFileInformation);
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		internal static extern int GetLogicalDrives();

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW", SetLastError = true)]
		private static extern bool MoveFileExPrivate(string src, string dst, uint flags);

		internal static bool MoveFile(string src, string dst)
		{
			src = PathInternal.EnsureExtendedPrefixIfNeeded(src);
			dst = PathInternal.EnsureExtendedPrefixIfNeeded(dst);
			return MoveFileExPrivate(src, dst, 2u);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "RemoveDirectoryW", SetLastError = true)]
		private static extern bool RemoveDirectoryPrivate(string path);

		internal static bool RemoveDirectory(string path)
		{
			path = PathInternal.EnsureExtendedPrefixIfNeeded(path);
			return RemoveDirectoryPrivate(path);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "ReplaceFileW", SetLastError = true)]
		private static extern bool ReplaceFilePrivate(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved);

		internal static bool ReplaceFile(string replacedFileName, string replacementFileName, string backupFileName, int dwReplaceFlags, IntPtr lpExclude, IntPtr lpReserved)
		{
			replacedFileName = PathInternal.EnsureExtendedPrefixIfNeeded(replacedFileName);
			replacementFileName = PathInternal.EnsureExtendedPrefixIfNeeded(replacementFileName);
			backupFileName = PathInternal.EnsureExtendedPrefixIfNeeded(backupFileName);
			return ReplaceFilePrivate(replacedFileName, replacementFileName, backupFileName, dwReplaceFlags, lpExclude, lpReserved);
		}

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "SetFileAttributesW", SetLastError = true)]
		private static extern bool SetFileAttributesPrivate(string name, int attr);

		internal static bool SetFileAttributes(string name, int attr)
		{
			name = PathInternal.EnsureExtendedPrefixIfNeeded(name);
			return SetFileAttributesPrivate(name, attr);
		}

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern bool SetFileInformationByHandle(SafeFileHandle hFile, FILE_INFO_BY_HANDLE_CLASS FileInformationClass, ref FILE_BASIC_INFO lpFileInformation, uint dwBufferSize);

		internal unsafe static bool SetFileTime(SafeFileHandle hFile, long creationTime = -1L, long lastAccessTime = -1L, long lastWriteTime = -1L, long changeTime = -1L, uint fileAttributes = 0u)
		{
			FILE_BASIC_INFO fILE_BASIC_INFO = default(FILE_BASIC_INFO);
			fILE_BASIC_INFO.CreationTime = creationTime;
			fILE_BASIC_INFO.LastAccessTime = lastAccessTime;
			fILE_BASIC_INFO.LastWriteTime = lastWriteTime;
			fILE_BASIC_INFO.ChangeTime = changeTime;
			fILE_BASIC_INFO.FileAttributes = fileAttributes;
			FILE_BASIC_INFO lpFileInformation = fILE_BASIC_INFO;
			return SetFileInformationByHandle(hFile, FILE_INFO_BY_HANDLE_CLASS.FileBasicInfo, ref lpFileInformation, (uint)sizeof(FILE_BASIC_INFO));
		}

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern bool SetThreadErrorMode(uint dwNewMode, out uint lpOldMode);
	}

	internal class BCrypt
	{
		internal enum NTSTATUS : uint
		{
			STATUS_SUCCESS = 0u,
			STATUS_NOT_FOUND = 3221226021u,
			STATUS_INVALID_PARAMETER = 3221225485u,
			STATUS_NO_MEMORY = 3221225495u
		}

		internal const int BCRYPT_USE_SYSTEM_PREFERRED_RNG = 2;

		[DllImport("BCrypt.dll", CharSet = CharSet.Unicode)]
		internal unsafe static extern NTSTATUS BCryptGenRandom(IntPtr hAlgorithm, byte* pbBuffer, int cbBuffer, int dwFlags);
	}

	internal class User32
	{
		[DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "LoadStringW", SetLastError = true)]
		internal static extern int LoadString(SafeLibraryHandle handle, int id, [Out] StringBuilder buffer, int bufferLength);
	}

	internal enum BOOL
	{
		FALSE,
		TRUE
	}

	internal enum BOOLEAN : byte
	{
		FALSE,
		TRUE
	}

	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_BAD_NETPATH = 53;

		internal const int ERROR_BAD_NET_NAME = 67;

		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_DIRECTORY = 267;

		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_NETWORK_UNREACHABLE = 1231;

		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 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 const string ErrorHandling = "api-ms-win-core-errorhandling-l1-1-0.dll";

		internal const string Handle = "api-ms-win-core-handle-l1-1-0.dll";

		internal const string IO = "api-ms-win-core-io-l1-1-0.dll";

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

		internal const string ProcessEnvironment = "api-ms-win-core-processenvironment-l1-1-0.dll";

		internal const string ProcessThreads = "api-ms-win-core-processthreads-l1-1-0.dll";

		internal const string RealTime = "api-ms-win-core-realtime-l1-1-0.dll";

		internal const string SysInfo = "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 Localization = "api-ms-win-core-localization-l1-2-1.dll";
	}

	internal struct LongFileTime
	{
		internal long TicksSince1601;

		internal DateTimeOffset ToDateTimeOffset()
		{
			return new DateTimeOffset(DateTime.FromFileTimeUtc(TicksSince1601));
		}
	}

	internal struct UNICODE_STRING
	{
		internal ushort Length;

		internal ushort MaximumLength;

		internal IntPtr Buffer;
	}

	internal class NtDll
	{
		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		public struct FILE_FULL_DIR_INFORMATION
		{
			public uint NextEntryOffset;

			public uint FileIndex;

			public LongFileTime CreationTime;

			public LongFileTime LastAccessTime;

			public LongFileTime LastWriteTime;

			public LongFileTime ChangeTime;

			public long EndOfFile;

			public long AllocationSize;

			public FileAttributes FileAttributes;

			public uint FileNameLength;

			public uint EaSize;

			private char _fileName;

			public unsafe ReadOnlySpan<char> FileName
			{
				get
				{
					fixed (char* pointer = &_fileName)
					{
						return new ReadOnlySpan<char>(pointer, (int)FileNameLength / 2);
					}
				}
			}

			public unsafe static FILE_FULL_DIR_INFORMATION* GetNextInfo(FILE_FULL_DIR_INFORMATION* info)
			{
				if (info == null)
				{
					return null;
				}
				uint nextEntryOffset = info->NextEntryOffset;
				if (nextEntryOffset == 0)
				{
					return null;
				}
				return (FILE_FULL_DIR_INFORMATION*)((byte*)info + nextEntryOffset);
			}
		}

		public enum FILE_INFORMATION_CLASS : uint
		{
			FileDirectoryInformation = 1u,
			FileFullDirectoryInformation,
			FileBothDirectoryInformation,
			FileBasicInformation,
			FileStandardInformation,
			FileInternalInformation,
			FileEaInformation,
			FileAccessInformation,
			FileNameInformation,
			FileRenameInformation,
			FileLinkInformation,
			FileNamesInformation,
			FileDispositionInformation,
			FilePositionInformation,
			FileFullEaInformation,
			FileModeInformation,
			FileAlignmentInformation,
			FileAllInformation,
			FileAllocationInformation,
			FileEndOfFileInformation,
			FileAlternateNameInformation,
			FileStreamInformation,
			FilePipeInformation,
			FilePipeLocalInformation,
			FilePipeRemoteInformation,
			FileMailslotQueryInformation,
			FileMailslotSetInformation,
			FileCompressionInformation,
			FileObjectIdInformation,
			FileCompletionInformation,
			FileMoveClusterInformation,
			FileQuotaInformation,
			FileReparsePointInformation,
			FileNetworkOpenInformation,
			FileAttributeTagInformation,
			FileTrackingInformation,
			FileIdBothDirectoryInformation,
			FileIdFullDirectoryInformation,
			FileValidDataLengthInformation,
			FileShortNameInformation,
			FileIoCompletionNotificationInformation,
			FileIoStatusBlockRangeInformation,
			FileIoPriorityHintInformation,
			FileSfioReserveInformation,
			FileSfioVolumeInformation,
			FileHardLinkInformation,
			FileProcessIdsUsingFileInformation,
			FileNormalizedNameInformation,
			FileNetworkPhysicalNameInformation,
			FileIdGlobalTxDirectoryInformation,
			FileIsRemoteDeviceInformation,
			FileUnusedInformation,
			FileNumaNodeInformation,
			FileStandardLinkInformation,
			FileRemoteProtocolInformation,
			FileRenameInformationBypassAccessCheck,
			FileLinkInformationBypassAccessCheck,
			FileVolumeNameInformation,
			FileIdInformation,
			FileIdExtdDirectoryInformation,
			FileReplaceCompletionInformation,
			FileHardLinkFullIdInformation,
			FileIdExtdBothDirectoryInformation,
			FileDispositionInformationEx,
			FileRenameInformationEx,
			FileRenameInformationExBypassAccessCheck,
			FileDesiredStorageClassInformation,
			FileStatInformation
		}

		public struct IO_STATUS_BLOCK
		{
			[StructLayout(LayoutKind.Explicit)]
			public struct IO_STATUS
			{
				[FieldOffset(0)]
				public uint Status;

				[FieldOffset(0)]
				public IntPtr Pointer;
			}

			public IO_STATUS Status;

			public IntPtr Information;
		}

		public struct OBJECT_ATTRIBUTES
		{
			public uint Length;

			public IntPtr RootDirectory;

			public unsafe UNICODE_STRING* ObjectName;

			public ObjectAttributes Attributes;

			public unsafe void* SecurityDescriptor;

			public unsafe void* SecurityQualityOfService;

			public unsafe OBJECT_ATTRIBUTES(UNICODE_STRING* objectName, ObjectAttributes attributes, IntPtr rootDirectory)
			{
				Length = (uint)sizeof(OBJECT_ATTRIBUTES);
				RootDirectory = rootDirectory;
				ObjectName = objectName;
				Attributes = attributes;
				SecurityDescriptor = null;
				SecurityQualityOfService = null;
			}
		}

		[Flags]
		public enum ObjectAttributes : uint
		{
			OBJ_INHERIT = 2u,
			OBJ_PERMANENT = 0x10u,
			OBJ_EXCLUSIVE = 0x20u,
			OBJ_CASE_INSENSITIVE = 0x40u,
			OBJ_OPENIF = 0x80u,
			OBJ_OPENLINK = 0x100u
		}

		public enum CreateDisposition : uint
		{
			FILE_SUPERSEDE,
			FILE_OPEN,
			FILE_CREATE,
			FILE_OPEN_IF,
			FILE_OVERWRITE,
			FILE_OVERWRITE_IF
		}

		public enum CreateOptions : uint
		{
			FILE_DIRECTORY_FILE = 1u,
			FILE_WRITE_THROUGH = 2u,
			FILE_SEQUENTIAL_ONLY = 4u,
			FILE_NO_INTERMEDIATE_BUFFERING = 8u,
			FILE_SYNCHRONOUS_IO_ALERT = 0x10u,
			FILE_SYNCHRONOUS_IO_NONALERT = 0x20u,
			FILE_NON_DIRECTORY_FILE = 0x40u,
			FILE_CREATE_TREE_CONNECTION = 0x80u,
			FILE_COMPLETE_IF_OPLOCKED = 0x100u,
			FILE_NO_EA_KNOWLEDGE = 0x200u,
			FILE_RANDOM_ACCESS = 0x800u,
			FILE_DELETE_ON_CLOSE = 0x1000u,
			FILE_OPEN_BY_FILE_ID = 0x2000u,
			FILE_OPEN_FOR_BACKUP_INTENT = 0x4000u,
			FILE_NO_COMPRESSION = 0x8000u,
			FILE_OPEN_REQUIRING_OPLOCK = 0x10000u,
			FILE_DISALLOW_EXCLUSIVE = 0x20000u,
			FILE_SESSION_AWARE = 0x40000u,
			FILE_RESERVE_OPFILTER = 0x100000u,
			FILE_OPEN_REPARSE_POINT = 0x200000u,
			FILE_OPEN_NO_RECALL = 0x400000u
		}

		[Flags]
		public enum DesiredAccess : uint
		{
			FILE_READ_DATA = 1u,
			FILE_LIST_DIRECTORY = 1u,
			FILE_WRITE_DATA = 2u,
			FILE_ADD_FILE = 2u,
			FILE_APPEND_DATA = 4u,
			FILE_ADD_SUBDIRECTORY = 4u,
			FILE_CREATE_PIPE_INSTANCE = 4u,
			FILE_READ_EA = 8u,
			FILE_WRITE_EA = 0x10u,
			FILE_EXECUTE = 0x20u,
			FILE_TRAVERSE = 0x20u,
			FILE_DELETE_CHILD = 0x40u,
			FILE_READ_ATTRIBUTES = 0x80u,
			FILE_WRITE_ATTRIBUTES = 0x100u,
			FILE_ALL_ACCESS = 0xF01FFu,
			DELETE = 0x10000u,
			READ_CONTROL = 0x20000u,
			WRITE_DAC = 0x40000u,
			WRITE_OWNER = 0x80000u,
			SYNCHRONIZE = 0x100000u,
			STANDARD_RIGHTS_READ = 0x20000u,
			STANDARD_RIGHTS_WRITE = 0x20000u,
			STANDARD_RIGHTS_EXECUTE = 0x20000u,
			FILE_GENERIC_READ = 0x80000000u,
			FILE_GENERIC_WRITE = 0x40000000u,
			FILE_GENERIC_EXECUTE = 0x20000000u
		}

		[DllImport("ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
		private unsafe static extern int NtCreateFile(out IntPtr FileHandle, DesiredAccess DesiredAccess, ref OBJECT_ATTRIBUTES ObjectAttributes, out IO_STATUS_BLOCK IoStatusBlock, long* AllocationSize, FileAttributes FileAttributes, FileShare ShareAccess, CreateDisposition CreateDisposition, CreateOptions CreateOptions, void* EaBuffer, uint EaLength);

		internal unsafe static (int status, IntPtr handle) CreateFile(ReadOnlySpan<char> path, IntPtr rootDirectory, CreateDisposition createDisposition, DesiredAccess desiredAccess = DesiredAccess.SYNCHRONIZE | DesiredAccess.FILE_GENERIC_READ, FileShare shareAccess = FileShare.ReadWrite | FileShare.Delete, FileAttributes fileAttributes = (FileAttributes)0, CreateOptions createOptions = CreateOptions.FILE_SYNCHRONOUS_IO_NONALERT, ObjectAttributes objectAttributes = NtDll.ObjectAttributes.OBJ_CASE_INSENSITIVE)
		{
			checked
			{
				fixed (char* ptr = &MemoryMarshal.GetReference(path))
				{
					UNICODE_STRING uNICODE_STRING = default(UNICODE_STRING);
					uNICODE_STRING.Length = (ushort)(path.Length * 2);
					uNICODE_STRING.MaximumLength = (ushort)(path.Length * 2);
					uNICODE_STRING.Buffer = (IntPtr)ptr;
					UNICODE_STRING uNICODE_STRING2 = uNICODE_STRING;
					OBJECT_ATTRIBUTES ObjectAttributes = new OBJECT_ATTRIBUTES(&uNICODE_STRING2, objectAttributes, rootDirectory);
					IntPtr FileHandle;
					IO_STATUS_BLOCK IoStatusBlock;
					return (NtCreateFile(out FileHandle, desiredAccess, ref ObjectAttributes, out IoStatusBlock, null, fileAttributes, shareAccess, createDisposition, createOptions, null, 0u), FileHandle);
				}
			}
		}

		[DllImport("ntdll.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
		public unsafe static extern int NtQueryDirectoryFile(IntPtr FileHandle, IntPtr Event, IntPtr ApcRoutine, IntPtr ApcContext, out IO_STATUS_BLOCK IoStatusBlock, IntPtr FileInformation, uint Length, FILE_INFORMATION_CLASS FileInformationClass, BOOLEAN ReturnSingleEntry, UNICODE_STRING* FileName, BOOLEAN RestartScan);

		[DllImport("ntdll.dll", ExactSpelling = true)]
		public static extern uint RtlNtStatusToDosError(int Status);
	}

	internal class StatusOptions
	{
		internal const uint STATUS_SUCCESS = 0u;

		internal const uint STATUS_SOME_NOT_MAPPED = 263u;

		internal const uint STATUS_NO_MORE_FILES = 2147483654u;

		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 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);

		[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		public static extern IntPtr RegisterServiceCtrlHandler(string serviceName, Delegate callback);

		[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		public static extern IntPtr RegisterServiceCtrlHandlerEx(string serviceName, Delegate callback, IntPtr userData);
	}

	internal static class mincore
	{
		[DllImport("api-ms-win-core-heap-l1-1-0.dll")]
		internal static extern IntPtr GetProcessHeap();

		[DllImport("api-ms-win-core-heap-l1-1-0.dll")]
		internal static extern IntPtr HeapAlloc(IntPtr hHeap, uint dwFlags, UIntPtr dwBytes);

		[DllImport("api-ms-win-core-heap-l1-1-0.dll")]
		internal static extern int HeapFree(IntPtr hHeap, uint dwFlags, IntPtr lpMem);

		[DllImport("api-ms-win-core-threadpool-l1-2-0.dll", SetLastError = true)]
		internal static extern SafeThreadPoolIOHandle CreateThreadpoolIo(SafeHandle fl, IntPtr pfnio, IntPtr context, IntPtr pcbe);

		[DllImport("api-ms-win-core-threadpool-l1-2-0.dll")]
		internal static extern void CloseThreadpoolIo(IntPtr pio);

		[DllImport("api-ms-win-core-threadpool-l1-2-0.dll")]
		internal static extern void StartThreadpoolIo(SafeThreadPoolIOHandle pio);

		[DllImport("api-ms-win-core-threadpool-l1-2-0.dll")]
		internal static extern void CancelThreadpoolIo(SafeThreadPoolIOHandle pio);
	}

	internal delegate void NativeIoCompletionCallback(IntPtr instance, IntPtr context, IntPtr overlapped, uint ioResult, UIntPtr numberOfBytesTransferred, IntPtr io);

	internal unsafe static void GetRandomBytes(byte* buffer, int length)
	{
		switch (BCrypt.BCryptGenRandom(IntPtr.Zero, buffer, length, 2))
		{
		case BCrypt.NTSTATUS.STATUS_NO_MEMORY:
			throw new OutOfMemoryException();
		default:
			throw new InvalidOperationException();
		case BCrypt.NTSTATUS.STATUS_SUCCESS:
			break;
		}
	}

	internal static IntPtr MemAlloc(UIntPtr sizeInBytes)
	{
		IntPtr intPtr = mincore.HeapAlloc(mincore.GetProcessHeap(), 0u, sizeInBytes);
		if (intPtr == IntPtr.Zero)
		{
			throw new OutOfMemoryException();
		}
		return intPtr;
	}

	internal static void MemFree(IntPtr allocatedMemory)
	{
		mincore.HeapFree(mincore.GetProcessHeap(), 0u, allocatedMemory);
	}
}
internal static class AssemblyRef
{
	internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string EcmaPublicKey = "b77a5c561934e089";

	public const string FrameworkPublicKeyFull = "00000000000000000400000000000000";

	public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000";

	public const string MicrosoftPublicKey = "b03f5f7f11d50a3a";

	public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal sealed class Locale
{
	private Locale()
	{
	}

	public static string GetText(string msg)
	{
		return msg;
	}

	public static string GetText(string fmt, params object[] args)
	{
		return string.Format(fmt, args);
	}
}
internal static class SR
{
	public const string RTL = "RTL_False";

	public const string ContinueButtonText = "Continue";

	public const string DebugMessageTruncated = "{0}...\n<truncated>";

	public const string DebugAssertTitleShort = "Assertion Failed";

	public const string DebugAssertTitle = "Assertion Failed: Cancel=Debug, OK=Continue";

	public const string NotSupported = "This operation is not supported.";

	public const string DebugLaunchFailed = "Cannot launch the debugger.  Make sure that a Microsoft (R) .NET Framework debugger is properly installed.";

	public const string DebugLaunchFailedTitle = "Microsoft .NET Framework Debug Launch Failure";

	public const string ObjectDisposed = "Object {0} has been disposed and can no longer be used.";

	public const string ExceptionOccurred = "An exception occurred writing trace output to log file '{0}'. {1}";

	public const string MustAddListener = "Only TraceListeners can be added to a TraceListenerCollection.";

	public const string ToStringNull = "(null)";

	public const string EnumConverterInvalidValue = "The value '{0}' is not a valid value for the enum '{1}'.";

	public const string ConvertFromException = "{0} cannot convert from {1}.";

	public const string ConvertToException = "'{0}' is unable to convert '{1}' to '{2}'.";

	public const string ConvertInvalidPrimitive = "{0} is not a valid value for {1}.";

	public const string ErrorMissingPropertyAccessors = "Accessor methods for the {0} property are missing.";

	public const string ErrorInvalidPropertyType = "Invalid type for the {0} property.";

	public const string ErrorMissingEventAccessors = "Accessor methods for the {0} event are missing.";

	public const string ErrorInvalidEventHandler = "Invalid event handler for the {0} event.";

	public const string ErrorInvalidEventType = "Invalid type for the {0} event.";

	public const string InvalidMemberName = "Invalid member name.";

	public const string ErrorBadExtenderType = "The {0} extender provider is not compatible with the {1} type.";

	public const string NullableConverterBadCtorArg = "The specified type is not a nullable type.";

	public const string TypeDescriptorExpectedElementType = "Expected types in the collection to be of type {0}.";

	public const string TypeDescriptorSameAssociation = "Cannot create an association when the primary and secondary objects are the same.";

	public const string TypeDescriptorAlreadyAssociated = "The primary and secondary objects are already associated with each other.";

	public const string TypeDescriptorProviderError = "The type description provider {0} has returned null from {1} which is illegal.";

	public const string TypeDescriptorUnsupportedRemoteObject = "The object {0} is being remoted by a proxy that does not support interface discovery.  This type of remoted object is not supported.";

	public const string TypeDescriptorArgsCountMismatch = "The number of elements in the Type and Object arrays must match.";

	public const string ErrorCreateSystemEvents = "Failed to create system events window thread.";

	public const string ErrorCreateTimer = "Cannot create timer.";

	public const string ErrorKillTimer = "Cannot end timer.";

	public const string ErrorSystemEventsNotSupported = "System event notifications are not supported under the current context. Server processes, for example, may not support global system event notifications.";

	public const string ErrorGetTempPath = "Cannot get temporary file name";

	public const string CHECKOUTCanceled = "The checkout was canceled by the user.";

	public const string ErrorInvalidServiceInstance = "The service instance must derive from or implement {0}.";

	public const string ErrorServiceExists = "The service {0} already exists in the service container.";

	public const string Argument_InvalidNumberStyles = "An undefined NumberStyles value is being used.";

	public const string Argument_InvalidHexStyle = "With the AllowHexSpecifier bit set in the enum bit field, the only other valid bits that can be combined into the enum value must be a subset of those in HexNumber.";

	public const string Argument_ByteArrayLengthMustBeAMultipleOf4 = "The Byte[] length must be a multiple of 4.";

	public const string Argument_InvalidCharactersInString = "The string contained an invalid character.";

	public const string Argument_ParsedStringWasInvalid = "The parsed string was invalid.";

	public const string Argument_MustBeBigInt = "The parameter must be a BigInteger.";

	public const string Format_InvalidFormatSpecifier = "Format specifier was invalid.";

	public const string Format_TooLarge = "The value is too large to be represented by this format specifier.";

	public const string ArgumentOutOfRange_MustBeLessThanUInt32MaxValue = "The value must be less than UInt32.MaxValue (2^32).";

	public const string ArgumentOutOfRange_MustBeNonNeg = "The number must be greater than or equal to zero.";

	public const string NotSupported_NumberStyle = "The NumberStyle option is not supported.";

	public const string Overflow_BigIntInfinity = "BigInteger cannot represent infinity.";

	public const string Overflow_NotANumber = "The value is not a number.";

	public const string Overflow_ParseBigInteger = "The value could not be parsed.";

	public const string Overflow_Int32 = "Value was either too large or too small for an Int32.";

	public const string Overflow_Int64 = "Value was either too large or too small for an Int64.";

	public const string Overflow_UInt32 = "Value was either too large or too small for a UInt32.";

	public const string Overflow_UInt64 = "Value was either too large or too small for a UInt64.";

	public const string Overflow_Decimal = "Value was either too large or too small for a Decimal.";

	public const string Argument_FrameworkNameTooShort = "FrameworkName cannot have less than two components or more than three components.";

	public const string Argument_FrameworkNameInvalid = "FrameworkName is invalid.";

	public const string Argument_FrameworkNameInvalidVersion = "FrameworkName version component is invalid.";

	public const string Argument_FrameworkNameMissingVersion = "FrameworkName version component is missing.";

	public const string ArgumentNull_Key = "Key cannot be null.";

	public const string Argument_InvalidValue = "Argument {0} should be larger than {1}.";

	public const string Arg_MultiRank = "Multi dimension array is not supported on this operation.";

	public const string Barrier_ctor_ArgumentOutOfRange = "The participantCount argument must be non-negative and less than or equal to 32767.";

	public const string Barrier_AddParticipants_NonPositive_ArgumentOutOfRange = "The participantCount argument must be a positive value.";

	public const string Barrier_AddParticipants_Overflow_ArgumentOutOfRange = "Adding participantCount participants would result in the number of participants exceeding the maximum number allowed.";

	public const string Barrier_InvalidOperation_CalledFromPHA = "This method may not be called from within the postPhaseAction.";

	public const string Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange = "The participantCount argument must be a positive value.";

	public const string Barrier_RemoveParticipants_ArgumentOutOfRange = "The participantCount argument must be less than or equal the number of participants.";

	public const string Barrier_RemoveParticipants_InvalidOperation = "The participantCount argument is greater than the number of participants that haven't yet arrived at the barrier in this phase.";

	public const string Barrier_SignalAndWait_ArgumentOutOfRange = "The specified timeout must represent a value between -1 and Int32.MaxValue, inclusive.";

	public const string Barrier_SignalAndWait_InvalidOperation_ZeroTotal = "The barrier has no registered participants.";

	public const string Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded = "The number of threads using the barrier exceeded the total number of registered participants.";

	public const string Barrier_Dispose = "The barrier has been disposed.";

	public const string BarrierPostPhaseException = "The postPhaseAction failed with an exception.";

	public const string UriTypeConverter_ConvertFrom_CannotConvert = "{0} cannot convert from {1}.";

	public const string UriTypeConverter_ConvertTo_CannotConvert = "{0} cannot convert {1} to {2}.";

	public const string ISupportInitializeDescr = "Specifies support for transacted initialization.";

	public const string CantModifyListSortDescriptionCollection = "Once a ListSortDescriptionCollection has been created it can't be modified.";

	public const string Argument_NullComment = "The 'Comment' property of the CodeCommentStatement '{0}' cannot be null.";

	public const string InvalidPrimitiveType = "Invalid Primitive Type: {0}. Consider using CodeObjectCreateExpression.";

	public const string Cannot_Specify_Both_Compiler_Path_And_Version = "Cannot specify both the '{0}' and '{1}' CodeDom provider options to choose a compiler. Please remove one of them.";

	public const string CodeGenOutputWriter = "The output writer for code generation and the writer supplied don't match and cannot be used. This is generally caused by a bad implementation of a CodeGenerator derived class.";

	public const string CodeGenReentrance = "This code generation API cannot be called while the generator is being used to generate something else.";

	public const string InvalidLanguageIdentifier = "The identifier:\"{0}\" on the property:\"{1}\" of type:\"{2}\" is not a valid language-independent identifier name. Check to see if CodeGenerator.IsValidLanguageIndependentIdentifier allows the identifier name.";

	public const string InvalidTypeName = "The type name:\"{0}\" on the property:\"{1}\" of type:\"{2}\" is not a valid language-independent type name.";

	public const string Empty_attribute = "The '{0}' attribute cannot be an empty string.";

	public const string Invalid_nonnegative_integer_attribute = "The '{0}' attribute must be a non-negative integer.";

	public const string CodeDomProvider_NotDefined = "There is no CodeDom provider defined for the language.";

	public const string Language_Names_Cannot_Be_Empty = "You need to specify a non-empty String for a language name in the CodeDom configuration section.";

	public const string Extension_Names_Cannot_Be_Empty_Or_Non_Period_Based = "An extension name in the CodeDom configuration section must be a non-empty string which starts with a period.";

	public const string Unable_To_Locate_Type = "The CodeDom provider type \"{0}\" could not be located.";

	public const string NotSupported_CodeDomAPI = "This CodeDomProvider does not support this method.";

	public const string ArityDoesntMatch = "The total arity specified in '{0}' does not match the number of TypeArguments supplied.  There were '{1}' TypeArguments supplied.";

	public const string PartialTrustErrorTextReplacement = "<The original value of this property potentially contains file system information and has been suppressed.>";

	public const string PartialTrustIllegalProvider = "When used in partial trust, langID must be C#, VB, J#, or JScript, and the language provider must be in the global assembly cache.";

	public const string IllegalAssemblyReference = "Assembly references cannot begin with '-', or contain a '/' or '\\'.";

	public const string NullOrEmpty_Value_in_Property = "The '{0}' property cannot contain null or empty strings.";

	public const string AutoGen_Comment_Line1 = "auto-generated>";

	public const string AutoGen_Comment_Line2 = "This code was generated by a tool.";

	public const string AutoGen_Comment_Line3 = "Runtime Version:";

	public const string AutoGen_Comment_Line4 = "Changes to this file may cause incorrect behavior and will be lost if";

	public const string AutoGen_Comment_Line5 = "the code is regenerated.";

	public const string CantContainNullEntries = "Array '{0}' cannot contain null entries.";

	public const string InvalidPathCharsInChecksum = "The CodeChecksumPragma file name '{0}' contains invalid path characters.";

	public const string InvalidRegion = "The region directive '{0}' contains invalid characters.  RegionText cannot contain any new line characters.";

	public const string Provider_does_not_support_options = "This CodeDomProvider type does not have a constructor that takes providerOptions - \"{0}\"";

	public const string MetaExtenderName = "{0} on {1}";

	public const string InvalidEnumArgument = "The value of argument '{0}' ({1}) is invalid for Enum type '{2}'.";

	public const string InvalidArgument = "'{1}' is not a valid value for '{0}'.";

	public const string InvalidNullArgument = "Null is not a valid value for {0}.";

	public const string LicExceptionTypeOnly = "A valid license cannot be granted for the type {0}. Contact the manufacturer of the component for more information.";

	public const string LicExceptionTypeAndInstance = "An instance of type '{1}' was being created, and a valid license could not be granted for the type '{0}'. Please,  contact the manufacturer of the component for more information.";

	public const string LicMgrContextCannotBeChanged = "The CurrentContext property of the LicenseManager is currently locked and cannot be changed.";

	public const string LicMgrAlreadyLocked = "The CurrentContext property of the LicenseManager is already locked by another user.";

	public const string LicMgrDifferentUser = "The CurrentContext property of the LicenseManager can only be unlocked with the same contextUser.";

	public const string InvalidElementType = "Element type {0} is not supported.";

	public const string InvalidIdentifier = "Identifier '{0}' is not valid.";

	public const string ExecFailedToCreate = "Failed to create file {0}.";

	public const string ExecTimeout = "Timed out waiting for a program to execute. The command being executed was {0}.";

	public const string ExecBadreturn = "An invalid return code was encountered waiting for a program to execute. The command being executed was {0}.";

	public const string ExecCantGetRetCode = "Unable to get the return code for a program being executed. The command that was being executed was '{0}'.";

	public const string ExecCantExec = "Cannot execute a program. The command being executed was {0}.";

	public const string ExecCantRevert = "Cannot execute a program. Impersonation failed.";

	public const string CompilerNotFound = "Compiler executable file {0} cannot be found.";

	public const string DuplicateFileName = "The file name '{0}' was already in the collection.";

	public const string CollectionReadOnly = "Collection is read-only.";

	public const string BitVectorFull = "Bit vector is full.";

	public const string ArrayConverterText = "{0} Array";

	public const string CollectionConverterText = "(Collection)";

	public const string MultilineStringConverterText = "(Text)";

	public const string CultureInfoConverterDefaultCultureString = "(Default)";

	public const string CultureInfoConverterInvalidCulture = "The {0} culture cannot be converted to a CultureInfo object on this computer.";

	public const string InvalidPrimitive = "The text {0} is not a valid {1}.";

	public const string TimerInvalidInterval = "'{0}' is not a valid value for 'Interval'. 'Interval' must be greater than {1}.";

	public const string TraceSwitchLevelTooHigh = "Attempted to set {0} to a value that is too high.  Setting level to TraceLevel.Verbose";

	public const string TraceSwitchLevelTooLow = "Attempted to set {0} to a value that is too low.  Setting level to TraceLevel.Off";

	public const string TraceSwitchInvalidLevel = "The Level must be set to a value in the enumeration TraceLevel.";

	public const string TraceListenerIndentSize = "The IndentSize property must be non-negative.";

	public const string TraceListenerFail = "Fail:";

	public const string TraceAsTraceSource = "Trace";

	public const string InvalidLowBoundArgument = "'{1}' is not a valid value for '{0}'. '{0}' must be greater than {2}.";

	public const string DuplicateComponentName = "Duplicate component name '{0}'.  Component names must be unique and case-insensitive.";

	public const string NotImplemented = "{0}: Not implemented";

	public const string OutOfMemory = "Could not allocate needed memory.";

	public const string EOF = "End of data stream encountered.";

	public const string IOError = "Unknown input/output failure.";

	public const string BadChar = "Unexpected Character: '{0}'.";

	public const string toStringNone = "(none)";

	public const string toStringUnknown = "(unknown)";

	public const string InvalidEnum = "{0} is not a valid {1} value.";

	public const string IndexOutOfRange = "Index {0} is out of range.";

	public const string ErrorPropertyAccessorException = "Property accessor '{0}' on object '{1}' threw the following exception:'{2}'";

	public const string InvalidOperation = "Invalid operation.";

	public const string EmptyStack = "Stack has no items in it.";

	public const string PerformanceCounterDesc = "Represents a Windows performance counter component.";

	public const string PCCategoryName = "Category name of the performance counter object.";

	public const string PCCounterName = "Counter name of the performance counter object.";

	public const string PCInstanceName = "Instance name of the performance counter object.";

	public const string PCMachineName = "Specifies the machine from where to read the performance data.";

	public const string PCInstanceLifetime = "Specifies the lifetime of the instance.";

	public const string PropertyCategoryAction = "Action";

	public const string PropertyCategoryAppearance = "Appearance";

	public const string PropertyCategoryAsynchronous = "Asynchronous";

	public const string PropertyCategoryBehavior = "Behavior";

	public const string PropertyCategoryData = "Data";

	public const string PropertyCategoryDDE = "DDE";

	public const string PropertyCategoryDesign = "Design";

	public const string PropertyCategoryDragDrop = "Drag Drop";

	public const string PropertyCategoryFocus = "Focus";

	public const string PropertyCategoryFont = "Font";

	public const string PropertyCategoryFormat = "Format";

	public const string PropertyCategoryKey = "Key";

	public const string PropertyCategoryList = "List";

	public const string PropertyCategoryLayout = "Layout";

	public const string PropertyCategoryDefault = "Misc";

	public const string PropertyCategoryMouse = "Mouse";

	public const string PropertyCategoryPosition = "Position";

	public const string PropertyCategoryText = "Text";

	public const string PropertyCategoryScale = "Scale";

	public const string PropertyCategoryWindowStyle = "Window Style";

	public const string PropertyCategoryConfig = "Configurations";

	public const string ArgumentNull_ArrayWithNullElements = "The array cannot contain null elements.";

	public const string OnlyAllowedOnce = "This operation is only allowed once per object.";

	public const string BeginIndexNotNegative = "Start index cannot be less than 0 or greater than input length.";

	public const string LengthNotNegative = "Length cannot be less than 0 or exceed input length.";

	public const string UnimplementedState = "Unimplemented state.";

	public const string UnexpectedOpcode = "Unexpected opcode in regular expression generation: {0}.";

	public const string NoResultOnFailed = "Result cannot be called on a failed Match.";

	public const string UnterminatedBracket = "Unterminated [] set.";

	public const string TooManyParens = "Too many )'s.";

	public const string NestedQuantify = "Nested quantifier {0}.";

	public const string QuantifyAfterNothing = "Quantifier {x,y} following nothing.";

	public const string InternalError = "Internal error in ScanRegex.";

	public const string IllegalRange = "Illegal {x,y} with x > y.";

	public const string NotEnoughParens = "Not enough )'s.";

	public const string BadClassInCharRange = "Cannot include class \\{0} in character range.";

	public const string ReversedCharRange = "[x-y] range in reverse order.";

	public const string UndefinedReference = "(?({0}) ) reference to undefined group.";

	public const string MalformedReference = "(?({0}) ) malformed.";

	public const string UnrecognizedGrouping = "Unrecognized grouping construct.";

	public const string UnterminatedComment = "Unterminated (?#...) comment.";

	public const string IllegalEndEscape = "Illegal \\ at end of pattern.";

	public const string MalformedNameRef = "Malformed \\k<...> named back reference.";

	public const string UndefinedBackref = "Reference to undefined group number {0}.";

	public const string UndefinedNameRef = "Reference to undefined group name {0}.";

	public const string TooFewHex = "Insufficient hexadecimal digits.";

	public const string MissingControl = "Missing control character.";

	public const string UnrecognizedControl = "Unrecognized control character.";

	public const string UnrecognizedEscape = "Unrecognized escape sequence \\{0}.";

	public const string IllegalCondition = "Illegal conditional (?(...)) expression.";

	public const string TooManyAlternates = "Too many | in (?()|).";

	public const string MakeException = "parsing \"{0}\" - {1}";

	public const string IncompleteSlashP = "Incomplete \\p{X} character escape.";

	public const string MalformedSlashP = "Malformed \\p{X} character escape.";

	public const string InvalidGroupName = "Invalid group name: Group names must begin with a word character.";

	public const string CapnumNotZero = "Capture number cannot be zero.";

	public const string AlternationCantCapture = "Alternation conditions do not capture and cannot be named.";

	public const string AlternationCantHaveComment = "Alternation conditions cannot be comments.";

	public const string CaptureGroupOutOfRange = "Capture group numbers must be less than or equal to Int32.MaxValue.";

	public const string SubtractionMustBeLast = "A subtraction must be the last element in a character class.";

	public const string UnknownProperty = "Unknown property '{0}'.";

	public const string ReplacementError = "Replacement pattern error.";

	public const string CountTooSmall = "Count cannot be less than -1.";

	public const string EnumNotStarted = "Enumeration has either not started or has already finished.";

	public const string Arg_InvalidArrayType = "Target array type is not compatible with the type of items in the collection.";

	public const string RegexMatchTimeoutException_Occurred = "The RegEx engine has timed out while trying to match a pattern to an input string. This can occur for many reasons, including very large inputs or excessive backtracking caused by nested quantifiers, back-references and other factors.";

	public const string IllegalDefaultRegexMatchTimeoutInAppDomain = "AppDomain data '{0}' contains an invalid value or object for specifying a default matching timeout for System.Text.RegularExpressions.Regex.";

	public const string FileObject_AlreadyOpen = "The file is already open.  Call Close before trying to open the FileObject again.";

	public const string FileObject_Closed = "The FileObject is currently closed.  Try opening it.";

	public const string FileObject_NotWhileWriting = "File information cannot be queried while open for writing.";

	public const string FileObject_FileDoesNotExist = "File information cannot be queried if the file does not exist.";

	public const string FileObject_MustBeClosed = "This operation can only be done when the FileObject is closed.";

	public const string FileObject_MustBeFileName = "You must specify a file name, not a relative or absolute path.";

	public const string FileObject_InvalidInternalState = "FileObject's open mode wasn't set to a valid value.  This FileObject is corrupt.";

	public const string FileObject_PathNotSet = "The path has not been set, or is an empty string.  Please ensure you specify some path.";

	public const string FileObject_Reading = "The file is currently open for reading.  Close the file and reopen it before attempting this.";

	public const string FileObject_Writing = "The file is currently open for writing.  Close the file and reopen it before attempting this.";

	public const string FileObject_InvalidEnumeration = "Enumerator is positioned before the first line or after the last line of the file.";

	public const string FileObject_NoReset = "Reset is not supported on a FileLineEnumerator.";

	public const string DirectoryObject_MustBeDirName = "You must specify a directory name, not a relative or absolute path.";

	public const string DirectoryObjectPathDescr = "The fully qualified, or relative path to the directory you wish to read from. E.g., \"c:\\temp\".";

	public const string FileObjectDetectEncodingDescr = "Determines whether the file will be parsed to see if it has a byte order mark indicating its encoding.  If it does, this will be used rather than the current specified encoding.";

	public const string FileObjectEncodingDescr = "The encoding to use when reading the file. UTF-8 is the default.";

	public const string FileObjectPathDescr = "The fully qualified, or relative path to the file you wish to read from. E.g., \"myfile.txt\".";

	public const string Arg_EnumIllegalVal = "Illegal enum value: {0}.";

	public const string Arg_OutOfRange_NeedNonNegNum = "Non-negative number required.";

	public const string Argument_InvalidPermissionState = "Invalid permission state.";

	public const string Argument_InvalidOidValue = "The OID value was invalid.";

	public const string Argument_WrongType = "Operation on type '{0}' attempted with target of incorrect type.";

	public const string Arg_EmptyOrNullString = "String cannot be empty or null.";

	public const string Arg_EmptyOrNullArray = "Array cannot be empty or null.";

	public const string Argument_InvalidClassAttribute = "The value of \"class\" attribute is invalid.";

	public const string Argument_InvalidNameType = "The value of \"nameType\" is invalid.";

	public const string InvalidOperation_DuplicateItemNotAllowed = "Duplicate items are not allowed in the collection.";

	public const string Cryptography_Asn_MismatchedOidInCollection = "The AsnEncodedData object does not have the same OID for the collection.";

	public const string Cryptography_Cms_Envelope_Empty_Content = "Cannot create CMS enveloped for empty content.";

	public const string Cryptography_Cms_Invalid_Recipient_Info_Type = "The recipient info type {0} is not valid.";

	public const string Cryptography_Cms_Invalid_Subject_Identifier_Type = "The subject identifier type {0} is not valid.";

	public const string Cryptography_Cms_Invalid_Subject_Identifier_Type_Value_Mismatch = "The subject identifier type {0} does not match the value data type {1}.";

	public const string Cryptography_Cms_Key_Agree_Date_Not_Available = "The Date property is not available for none KID key agree recipient.";

	public const string Cryptography_Cms_Key_Agree_Other_Key_Attribute_Not_Available = "The OtherKeyAttribute property is not available for none KID key agree recipient.";

	public const string Cryptography_Cms_MessageNotSigned = "The CMS message is not signed.";

	public const string Cryptography_Cms_MessageNotSignedByNoSignature = "The CMS message is not signed by NoSignature.";

	public const string Cryptography_Cms_MessageNotEncrypted = "The CMS message is not encrypted.";

	public const string Cryptography_Cms_Not_Supported = "The Cryptographic Message Standard (CMS) is not supported on this platform.";

	public const string Cryptography_Cms_RecipientCertificateNotFound = "The recipient certificate is not specified.";

	public const string Cryptography_Cms_Sign_Empty_Content = "Cannot create CMS signature for empty content.";

	public const string Cryptography_Cms_Sign_No_Signature_First_Signer = "CmsSigner has to be the first signer with NoSignature.";

	public const string Cryptography_DpApi_InvalidMemoryLength = "The length of the data should be a multiple of 16 bytes.";

	public const string Cryptography_InvalidHandle = "{0} is an invalid handle.";

	public const string Cryptography_InvalidContextHandle = "The chain context handle is invalid.";

	public const string Cryptography_InvalidStoreHandle = "The store handle is invalid.";

	public const string Cryptography_Oid_InvalidValue = "The OID value is invalid.";

	public const string Cryptography_Pkcs9_ExplicitAddNotAllowed = "The PKCS 9 attribute cannot be explicitly added to the collection.";

	public const string Cryptography_Pkcs9_InvalidOid = "The OID does not represent a valid PKCS 9 attribute.";

	public const string Cryptography_Pkcs9_MultipleSigningTimeNotAllowed = "Cannot add multiple PKCS 9 signing time attributes.";

	public const string Cryptography_Pkcs9_AttributeMismatch = "The parameter should be a PKCS 9 attribute.";

	public const string Cryptography_X509_AddFailed = "Adding certificate with index '{0}' failed.";

	public const string Cryptography_X509_BadEncoding = "Input data cannot be coded as a valid certificate.";

	public const string Cryptography_X509_ExportFailed = "The certificate export operation failed.";

	public const string Cryptography_X509_ExtensionMismatch = "The parameter should be an X509Extension.";

	public const string Cryptography_X509_InvalidFindType = "Invalid find type.";

	public const string Cryptography_X509_InvalidFindValue = "Invalid find value.";

	public const string Cryptography_X509_InvalidEncodingFormat = "Invalid encoding format.";

	public const string Cryptography_X509_InvalidContentType = "Invalid content type.";

	public const string Cryptography_X509_KeyMismatch = "The public key of the certificate does not match the value specified.";

	public const string Cryptography_X509_RemoveFailed = "Removing certificate with index '{0}' failed.";

	public const string Cryptography_X509_StoreNotOpen = "The X509 certificate store has not been opened.";

	public const string Environment_NotInteractive = "The current session is not interactive.";

	public const string NotSupported_InvalidKeyImpl = "Only asymmetric keys that implement ICspAsymmetricAlgorithm are supported.";

	public const string NotSupported_KeyAlgorithm = "The certificate key algorithm is not supported.";

	public const string NotSupported_PlatformRequiresNT = "This operation is only supported on Windows 2000, Windows XP, and higher.";

	public const string NotSupported_UnreadableStream = "Stream does not support reading.";

	public const string Security_InvalidValue = "The {0} value was invalid.";

	public const string Unknown_Error = "Unknown error.";

	public const string security_ServiceNameCollection_EmptyServiceName = "A service name must not be null or empty.";

	public const string security_ExtendedProtectionPolicy_UseDifferentConstructorForNever = "To construct a policy with PolicyEnforcement.Never, the single-parameter constructor must be used.";

	public const string security_ExtendedProtectionPolicy_NoEmptyServiceNameCollection = "The ServiceNameCollection must contain at least one service name.";

	public const string security_ExtendedProtection_NoOSSupport = "This operation requires OS support for extended protection.";

	public const string net_nonClsCompliantException = "A non-CLS Compliant Exception (i.e. an object that does not derive from System.Exception) was thrown.";

	public const string net_illegalConfigWith = "The '{0}' attribute cannot appear when '{1}' is present.";

	public const string net_illegalConfigWithout = "The '{0}' attribute can only appear when '{1}' is present.";

	public const string net_resubmitcanceled = "An error occurred on an automatic resubmission of the request.";

	public const string net_redirect_perm = "WebPermission demand failed for redirect URI.";

	public const string net_resubmitprotofailed = "Cannot handle redirect from HTTP/HTTPS protocols to other dissimilar ones.";

	public const string net_invalidversion = "This protocol version is not supported.";

	public const string net_toolong = "The size of {0} is too long. It cannot be longer than {1} characters.";

	public const string net_connclosed = "The underlying connection was closed: {0}.";

	public const string net_mutualauthfailed = "The requirement for mutual authentication was not met by the remote server.";

	public const string net_invasync = "Cannot block a call on this socket while an earlier asynchronous call is in progress.";

	public const string net_inasync = "An asynchronous call is already in progress. It must be completed or canceled before you can call this method.";

	public const string net_mustbeuri = "The {0} parameter must represent a valid Uri (see inner exception).";

	public const string net_format_shexp = "The shell expression '{0}' could not be parsed because it is formatted incorrectly.";

	public const string net_cannot_load_proxy_helper = "Failed to load the proxy script runtime environment from the Microsoft.JScript assembly.";

	public const string net_io_no_0timeouts = "NetworkStream does not support a 0 millisecond timeout, use a value greater than zero for the timeout instead.";

	public const string net_tooManyRedirections = "Too many automatic redirections were attempted.";

	public const string net_authmodulenotregistered = "The supplied authentication module is not registered.";

	public const string net_authschemenotregistered = "There is no registered module for this authentication scheme.";

	public const string net_proxyschemenotsupported = "The ServicePointManager does not support proxies with the {0} scheme.";

	public const string net_maxsrvpoints = "The maximum number of service points was exceeded.";

	public const string net_notconnected = "The operation is not allowed on non-connected sockets.";

	public const string net_notstream = "The operation is not allowed on non-stream oriented sockets.";

	public const string net_nocontentlengthonget = "Content-Length or Chunked Encoding cannot be set for an operation that does not write data.";

	public const string net_contentlengthmissing = "When performing a write operation with AllowWriteStreamBuffering set to false, you must either set ContentLength to a non-negative number or set SendChunked to true.";

	public const string net_nonhttpproxynotallowed = "The URI scheme for the supplied IWebProxy has the illegal value '{0}'. Only 'http' is supported.";

	public const string net_need_writebuffering = "This request requires buffering data to succeed.";

	public const string net_nodefaultcreds = "Default credentials cannot be supplied for the {0} authentication scheme.";

	public const string net_stopped = "Not listening. You must call the Start() method before calling this method.";

	public const string net_udpconnected = "Cannot send packets to an arbitrary host while connected.";

	public const string net_no_concurrent_io_allowed = "The stream does not support concurrent IO read or write operations.";

	public const string net_needmorethreads = "There were not enough free threads in the ThreadPool to complete the operation.";

	public const string net_MethodNotSupportedException = "This method is not supported by this class.";

	public const string net_ProtocolNotSupportedException = "The '{0}' protocol is not supported by this class.";

	public const string net_SelectModeNotSupportedException = "The '{0}' select mode is not supported by this class.";

	public const string net_InvalidSocketHandle = "The socket handle is not valid.";

	public const string net_InvalidAddressFamily = "The AddressFamily {0} is not valid for the {1} end point, use {2} instead.";

	public const string net_InvalidEndPointAddressFamily = "The supplied EndPoint of AddressFamily {0} is not valid for this Socket, use {1} instead.";

	public const string net_InvalidSocketAddressSize = "The supplied {0} is an invalid size for the {1} end point.";

	public const string net_invalidAddressList = "None of the discovered or specified addresses match the socket address family.";

	public const string net_invalidPingBufferSize = "The buffer length must not exceed 65500 bytes.";

	public const string net_cant_perform_during_shutdown = "This operation cannot be performed while the AppDomain is shutting down.";

	public const string net_cant_create_environment = "Unable to create another web proxy script environment at this time.";

	public const string net_protocol_invalid_family = "'{0}' Client can only accept InterNetwork or InterNetworkV6 addresses.";

	public const string net_protocol_invalid_multicast_family = "Multicast family is not the same as the family of the '{0}' Client.";

	public const string net_empty_osinstalltype = "The Registry value '{0}' was either empty or not a string type.";

	public const string net_unknown_osinstalltype = "Unknown Windows installation type '{0}'.";

	public const string net_cant_determine_osinstalltype = "Can't determine OS installation type: Can't read key '{0}'. Exception message: {1}";

	public const string net_osinstalltype = "Current OS installation type is '{0}'.";

	public const string net_entire_body_not_written = "You must write ContentLength bytes to the request stream before calling [Begin]GetResponse.";

	public const string net_must_provide_request_body = "You must provide a request body if you set ContentLength>0 or SendChunked==true.  Do this by calling [Begin]GetRequestStream before [Begin]GetResponse.";

	public const string net_sockets_zerolist = "The parameter {0} must contain one or more elements.";

	public const string net_sockets_blocking = "The operation is not allowed on a non-blocking Socket.";

	public const string net_sockets_useblocking = "Use the Blocking property to change the status of the Socket.";

	public const string net_sockets_select = "The operation is not allowed on objects of type {0}. Use only objects of type {1}.";

	public const string net_sockets_toolarge_select = "The {0} list contains too many items; a maximum of {1} is allowed.";

	public const string net_sockets_empty_select = "All lists are either null or empty.";

	public const string net_sockets_mustbind = "You must call the Bind method before performing this operation.";

	public const string net_sockets_mustlisten = "You must call the Listen method before performing this operation.";

	public const string net_sockets_mustnotlisten = "You may not perform this operation after calling the Listen method.";

	public const string net_sockets_mustnotbebound = "The socket must not be bound or connected.";

	public const string net_sockets_namedmustnotbebound = "{0}: The socket must not be bound or connected.";

	public const string net_sockets_invalid_socketinformation = "The specified value for the socket information is invalid.";

	public const string net_sockets_invalid_ipaddress_length = "The number of specified IP addresses has to be greater than 0.";

	public const string net_sockets_invalid_optionValue = "The specified value is not a valid '{0}'.";

	public const string net_sockets_invalid_optionValue_all = "The specified value is not valid.";

	public const string net_sockets_invalid_dnsendpoint = "The parameter {0} must not be of type DnsEndPoint.";

	public const string net_sockets_disconnectedConnect = "Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint.  BeginConnect must be called on a thread that won't exit until the operation has been completed.";

	public const string net_sockets_disconnectedAccept = "Once the socket has been disconnected, you can only accept again asynchronously.  BeginAccept must be called on a thread that won't exit until the operation has been completed.";

	public const string net_tcplistener_mustbestopped = "The TcpListener must not be listening before performing this operation.";

	public const string net_sockets_no_duplicate_async = "BeginConnect cannot be called while another asynchronous operation is in progress on the same Socket.";

	public const string net_socketopinprogress = "An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance.";

	public const string net_buffercounttoosmall = "The Buffer space specified by the Count property is insufficient for the AcceptAsync method.";

	public const string net_multibuffernotsupported = "Multiple buffers cannot be used with this method.";

	public const string net_ambiguousbuffers = "Buffer and BufferList properties cannot both be non-null.";

	public const string net_sockets_ipv6only = "This operation is only valid for IPv6 Sockets.";

	public const string net_perfcounter_initialized_success = "System.Net performance counters initialization completed successful.";

	public const string net_perfcounter_initialized_error = "System.Net performance counters initialization completed with errors. See System.Net trace file for more information.";

	public const string net_perfcounter_nocategory = "Performance counter category '{0}' doesn't exist. No System.Net performance counter values available.";

	public const string net_perfcounter_initialization_started = "System.Net performance counter initialization started.";

	public const string net_perfcounter_cant_queue_workitem = "Can't queue counter initialization logic on a thread pool thread. System.Net performance counters will not be available.";

	public const string net_config_proxy = "Error creating the Web Proxy specified in the 'system.net/defaultProxy' configuration section.";

	public const string net_config_proxy_module_not_public = "The specified proxy module type is not public.";

	public const string net_config_authenticationmodules = "Error creating the modules specified in the 'system.net/authenticationModules' configuration section.";

	public const string net_config_webrequestmodules = "Error creating the modules specified in the 'system.net/webRequestModules' configuration section.";

	public const string net_config_requestcaching = "Error creating the Web Request caching policy specified in the 'system.net/requestCaching' configuration section.";

	public const string net_config_section_permission = "Insufficient permissions for setting the configuration section '{0}'.";

	public const string net_config_element_permission = "Insufficient permissions for setting the configuration element '{0}'.";

	public const string net_config_property_permission = "Insufficient permissions for setting the configuration property '{0}'.";

	public const string net_WebResponseParseError_InvalidHeaderName = "Header name is invalid";

	public const string net_WebResponseParseError_InvalidContentLength = "'Content-Length' header value is invalid";

	public const string net_WebResponseParseError_IncompleteHeaderLine = "Invalid header name";

	public const string net_WebResponseParseError_CrLfError = "CR must be followed by LF";

	public const string net_WebResponseParseError_InvalidChunkFormat = "Response chunk format is invalid";

	public const string net_WebResponseParseError_UnexpectedServerResponse = "Unexpected server response received";

	public const string net_webstatus_Success = "Status success";

	public const string net_webstatus_ReceiveFailure = "An unexpected error occurred on a receive";

	public const string net_webstatus_SendFailure = "An unexpected error occurred on a send";

	public const string net_webstatus_PipelineFailure = "A pipeline failure occurred";

	public const string net_webstatus_RequestCanceled = "The request was canceled";

	public const string net_webstatus_ConnectionClosed = "The connection was closed unexpectedly";

	public const string net_webstatus_TrustFailure = "Could not establish trust relationship for the SSL/TLS secure channel";

	public const string net_webstatus_SecureChannelFailure = "Could not create SSL/TLS secure channel";

	public const string net_webstatus_ServerProtocolViolation = "The server committed a protocol violation";

	public const string net_webstatus_KeepAliveFailure = "A connection that was expected to be kept alive was closed by the server";

	public const string net_webstatus_ProxyNameResolutionFailure = "The proxy name could not be resolved";

	public const string net_webstatus_MessageLengthLimitExceeded = "The message length limit was exceeded";

	public const string net_webstatus_CacheEntryNotFound = "The request cache-only policy does not allow a network request and the response is not found in cache";

	public const string net_webstatus_RequestProhibitedByCachePolicy = "The request could not be satisfied using a cache-only policy";

	public const string net_webstatus_RequestProhibitedByProxy = "The IWebProxy object associated with the request did not allow the request to proceed";

	public const string net_httpstatuscode_NoContent = "No Content";

	public const string net_httpstatuscode_NonAuthoritativeInformation = "Non Authoritative Information";

	public const string net_httpstatuscode_ResetContent = "Reset Content";

	public const string net_httpstatuscode_PartialContent = "Partial Content";

	public const string net_httpstatuscode_MultipleChoices = "Multiple Choices Redirect";

	public const string net_httpstatuscode_Ambiguous = "Ambiguous Redirect";

	public const string net_httpstatuscode_MovedPermanently = "Moved Permanently Redirect";

	public const string net_httpstatuscode_Moved = "Moved Redirect";

	public const string net_httpstatuscode_Found = "Found Redirect";

	public const string net_httpstatuscode_Redirect = "Redirect";

	public const string net_httpstatuscode_SeeOther = "See Other";

	public const string net_httpstatuscode_RedirectMethod = "Redirect Method";

	public const string net_httpstatuscode_NotModified = "Not Modified";

	public const string net_httpstatuscode_UseProxy = "Use Proxy Redirect";

	public const string net_httpstatuscode_TemporaryRedirect = "Temporary Redirect";

	public const string net_httpstatuscode_RedirectKeepVerb = "Redirect Keep Verb";

	public const string net_httpstatuscode_BadRequest = "Bad Request";

	public const string net_httpstatuscode_Unauthorized = "Unauthorized";

	public const string net_httpstatuscode_PaymentRequired = "Payment Required";

	public const string net_httpstatuscode_Forbidden = "Forbidden";

	public const string net_httpstatuscode_NotFound = "Not Found";

	public const string net_httpstatuscode_MethodNotAllowed = "Method Not Allowed";

	public const string ne

BepInEx/core/netstandard.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Configuration.Assemblies;
using System.Data;
using System.Data.Common;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Diagnostics.SymbolStore;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.IO.Enumeration;
using System.IO.IsolatedStorage;
using System.IO.MemoryMappedFiles;
using System.IO.Pipes;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Net.Cache;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.Net.Mime;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using System.Timers;
using System.Transactions;
using System.Web;
using System.Windows.Input;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Resolvers;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.XPath;
using System.Xml.Xsl;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("netstandard")]
[assembly: AssemblyDescription("netstandard")]
[assembly: AssemblyDefaultAlias("netstandard")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: TypeForwardedTo(typeof(CriticalHandleMinusOneIsInvalid))]
[assembly: TypeForwardedTo(typeof(CriticalHandleZeroOrMinusOneIsInvalid))]
[assembly: TypeForwardedTo(typeof(SafeFileHandle))]
[assembly: TypeForwardedTo(typeof(SafeHandleMinusOneIsInvalid))]
[assembly: TypeForwardedTo(typeof(SafeHandleZeroOrMinusOneIsInvalid))]
[assembly: TypeForwardedTo(typeof(SafeMemoryMappedFileHandle))]
[assembly: TypeForwardedTo(typeof(SafeMemoryMappedViewHandle))]
[assembly: TypeForwardedTo(typeof(SafePipeHandle))]
[assembly: TypeForwardedTo(typeof(SafeProcessHandle))]
[assembly: TypeForwardedTo(typeof(SafeWaitHandle))]
[assembly: TypeForwardedTo(typeof(SafeX509ChainHandle))]
[assembly: TypeForwardedTo(typeof(AccessViolationException))]
[assembly: TypeForwardedTo(typeof(Action))]
[assembly: TypeForwardedTo(typeof(Action<>))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, >))]
[assembly: TypeForwardedTo(typeof(Action<, , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Activator))]
[assembly: TypeForwardedTo(typeof(AggregateException))]
[assembly: TypeForwardedTo(typeof(AppContext))]
[assembly: TypeForwardedTo(typeof(AppDomain))]
[assembly: TypeForwardedTo(typeof(AppDomainUnloadedException))]
[assembly: TypeForwardedTo(typeof(ApplicationException))]
[assembly: TypeForwardedTo(typeof(ApplicationId))]
[assembly: TypeForwardedTo(typeof(ArgumentException))]
[assembly: TypeForwardedTo(typeof(ArgumentNullException))]
[assembly: TypeForwardedTo(typeof(ArgumentOutOfRangeException))]
[assembly: TypeForwardedTo(typeof(ArithmeticException))]
[assembly: TypeForwardedTo(typeof(Array))]
[assembly: TypeForwardedTo(typeof(ArraySegment<>))]
[assembly: TypeForwardedTo(typeof(ArrayTypeMismatchException))]
[assembly: TypeForwardedTo(typeof(AssemblyLoadEventArgs))]
[assembly: TypeForwardedTo(typeof(AssemblyLoadEventHandler))]
[assembly: TypeForwardedTo(typeof(AsyncCallback))]
[assembly: TypeForwardedTo(typeof(Attribute))]
[assembly: TypeForwardedTo(typeof(AttributeTargets))]
[assembly: TypeForwardedTo(typeof(AttributeUsageAttribute))]
[assembly: TypeForwardedTo(typeof(BadImageFormatException))]
[assembly: TypeForwardedTo(typeof(Base64FormattingOptions))]
[assembly: TypeForwardedTo(typeof(BitConverter))]
[assembly: TypeForwardedTo(typeof(bool))]
[assembly: TypeForwardedTo(typeof(Buffer))]
[assembly: TypeForwardedTo(typeof(ArrayBufferWriter<>))]
[assembly: TypeForwardedTo(typeof(ArrayPool<>))]
[assembly: TypeForwardedTo(typeof(BinaryPrimitives))]
[assembly: TypeForwardedTo(typeof(BuffersExtensions))]
[assembly: TypeForwardedTo(typeof(IBufferWriter<>))]
[assembly: TypeForwardedTo(typeof(IMemoryOwner<>))]
[assembly: TypeForwardedTo(typeof(IPinnable))]
[assembly: TypeForwardedTo(typeof(MemoryHandle))]
[assembly: TypeForwardedTo(typeof(MemoryManager<>))]
[assembly: TypeForwardedTo(typeof(MemoryPool<>))]
[assembly: TypeForwardedTo(typeof(OperationStatus))]
[assembly: TypeForwardedTo(typeof(ReadOnlySequence<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySequenceSegment<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySpanAction<, >))]
[assembly: TypeForwardedTo(typeof(SequenceReader<>))]
[assembly: TypeForwardedTo(typeof(SequenceReaderExtensions))]
[assembly: TypeForwardedTo(typeof(SpanAction<, >))]
[assembly: TypeForwardedTo(typeof(StandardFormat))]
[assembly: TypeForwardedTo(typeof(Base64))]
[assembly: TypeForwardedTo(typeof(Utf8Formatter))]
[assembly: TypeForwardedTo(typeof(Utf8Parser))]
[assembly: TypeForwardedTo(typeof(byte))]
[assembly: TypeForwardedTo(typeof(CannotUnloadAppDomainException))]
[assembly: TypeForwardedTo(typeof(char))]
[assembly: TypeForwardedTo(typeof(CharEnumerator))]
[assembly: TypeForwardedTo(typeof(CLSCompliantAttribute))]
[assembly: TypeForwardedTo(typeof(GeneratedCodeAttribute))]
[assembly: TypeForwardedTo(typeof(IndentedTextWriter))]
[assembly: TypeForwardedTo(typeof(ArrayList))]
[assembly: TypeForwardedTo(typeof(BitArray))]
[assembly: TypeForwardedTo(typeof(CaseInsensitiveComparer))]
[assembly: TypeForwardedTo(typeof(CaseInsensitiveHashCodeProvider))]
[assembly: TypeForwardedTo(typeof(CollectionBase))]
[assembly: TypeForwardedTo(typeof(Comparer))]
[assembly: TypeForwardedTo(typeof(BlockingCollection<>))]
[assembly: TypeForwardedTo(typeof(ConcurrentBag<>))]
[assembly: TypeForwardedTo(typeof(ConcurrentDictionary<, >))]
[assembly: TypeForwardedTo(typeof(ConcurrentQueue<>))]
[assembly: TypeForwardedTo(typeof(ConcurrentStack<>))]
[assembly: TypeForwardedTo(typeof(EnumerablePartitionerOptions))]
[assembly: TypeForwardedTo(typeof(IProducerConsumerCollection<>))]
[assembly: TypeForwardedTo(typeof(OrderablePartitioner<>))]
[assembly: TypeForwardedTo(typeof(Partitioner))]
[assembly: TypeForwardedTo(typeof(Partitioner<>))]
[assembly: TypeForwardedTo(typeof(DictionaryBase))]
[assembly: TypeForwardedTo(typeof(DictionaryEntry))]
[assembly: TypeForwardedTo(typeof(CollectionExtensions))]
[assembly: TypeForwardedTo(typeof(Comparer<>))]
[assembly: TypeForwardedTo(typeof(Dictionary<, >))]
[assembly: TypeForwardedTo(typeof(EqualityComparer<>))]
[assembly: TypeForwardedTo(typeof(HashSet<>))]
[assembly: TypeForwardedTo(typeof(IAsyncEnumerable<>))]
[assembly: TypeForwardedTo(typeof(IAsyncEnumerator<>))]
[assembly: TypeForwardedTo(typeof(ICollection<>))]
[assembly: TypeForwardedTo(typeof(IComparer<>))]
[assembly: TypeForwardedTo(typeof(IDictionary<, >))]
[assembly: TypeForwardedTo(typeof(IEnumerable<>))]
[assembly: TypeForwardedTo(typeof(IEnumerator<>))]
[assembly: TypeForwardedTo(typeof(IEqualityComparer<>))]
[assembly: TypeForwardedTo(typeof(IList<>))]
[assembly: TypeForwardedTo(typeof(IReadOnlyCollection<>))]
[assembly: TypeForwardedTo(typeof(IReadOnlyDictionary<, >))]
[assembly: TypeForwardedTo(typeof(IReadOnlyList<>))]
[assembly: TypeForwardedTo(typeof(ISet<>))]
[assembly: TypeForwardedTo(typeof(KeyNotFoundException))]
[assembly: TypeForwardedTo(typeof(KeyValuePair))]
[assembly: TypeForwardedTo(typeof(KeyValuePair<, >))]
[assembly: TypeForwardedTo(typeof(LinkedList<>))]
[assembly: TypeForwardedTo(typeof(LinkedListNode<>))]
[assembly: TypeForwardedTo(typeof(List<>))]
[assembly: TypeForwardedTo(typeof(Queue<>))]
[assembly: TypeForwardedTo(typeof(SortedDictionary<, >))]
[assembly: TypeForwardedTo(typeof(SortedList<, >))]
[assembly: TypeForwardedTo(typeof(SortedSet<>))]
[assembly: TypeForwardedTo(typeof(Stack<>))]
[assembly: TypeForwardedTo(typeof(Hashtable))]
[assembly: TypeForwardedTo(typeof(ICollection))]
[assembly: TypeForwardedTo(typeof(IComparer))]
[assembly: TypeForwardedTo(typeof(IDictionary))]
[assembly: TypeForwardedTo(typeof(IDictionaryEnumerator))]
[assembly: TypeForwardedTo(typeof(IEnumerable))]
[assembly: TypeForwardedTo(typeof(IEnumerator))]
[assembly: TypeForwardedTo(typeof(IEqualityComparer))]
[assembly: TypeForwardedTo(typeof(IHashCodeProvider))]
[assembly: TypeForwardedTo(typeof(IList))]
[assembly: TypeForwardedTo(typeof(IStructuralComparable))]
[assembly: TypeForwardedTo(typeof(IStructuralEquatable))]
[assembly: TypeForwardedTo(typeof(Collection<>))]
[assembly: TypeForwardedTo(typeof(KeyedCollection<, >))]
[assembly: TypeForwardedTo(typeof(ObservableCollection<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlyCollection<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlyDictionary<, >))]
[assembly: TypeForwardedTo(typeof(ReadOnlyObservableCollection<>))]
[assembly: TypeForwardedTo(typeof(Queue))]
[assembly: TypeForwardedTo(typeof(ReadOnlyCollectionBase))]
[assembly: TypeForwardedTo(typeof(SortedList))]
[assembly: TypeForwardedTo(typeof(BitVector32))]
[assembly: TypeForwardedTo(typeof(CollectionsUtil))]
[assembly: TypeForwardedTo(typeof(HybridDictionary))]
[assembly: TypeForwardedTo(typeof(INotifyCollectionChanged))]
[assembly: TypeForwardedTo(typeof(IOrderedDictionary))]
[assembly: TypeForwardedTo(typeof(ListDictionary))]
[assembly: TypeForwardedTo(typeof(NameObjectCollectionBase))]
[assembly: TypeForwardedTo(typeof(NameValueCollection))]
[assembly: TypeForwardedTo(typeof(NotifyCollectionChangedAction))]
[assembly: TypeForwardedTo(typeof(NotifyCollectionChangedEventArgs))]
[assembly: TypeForwardedTo(typeof(NotifyCollectionChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(OrderedDictionary))]
[assembly: TypeForwardedTo(typeof(StringCollection))]
[assembly: TypeForwardedTo(typeof(StringDictionary))]
[assembly: TypeForwardedTo(typeof(StringEnumerator))]
[assembly: TypeForwardedTo(typeof(Stack))]
[assembly: TypeForwardedTo(typeof(StructuralComparisons))]
[assembly: TypeForwardedTo(typeof(Comparison<>))]
[assembly: TypeForwardedTo(typeof(AddingNewEventArgs))]
[assembly: TypeForwardedTo(typeof(AddingNewEventHandler))]
[assembly: TypeForwardedTo(typeof(AmbientValueAttribute))]
[assembly: TypeForwardedTo(typeof(ArrayConverter))]
[assembly: TypeForwardedTo(typeof(AsyncCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(AsyncCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(AsyncOperation))]
[assembly: TypeForwardedTo(typeof(AsyncOperationManager))]
[assembly: TypeForwardedTo(typeof(AttributeCollection))]
[assembly: TypeForwardedTo(typeof(AttributeProviderAttribute))]
[assembly: TypeForwardedTo(typeof(BackgroundWorker))]
[assembly: TypeForwardedTo(typeof(BaseNumberConverter))]
[assembly: TypeForwardedTo(typeof(BindableAttribute))]
[assembly: TypeForwardedTo(typeof(BindableSupport))]
[assembly: TypeForwardedTo(typeof(BindingDirection))]
[assembly: TypeForwardedTo(typeof(BindingList<>))]
[assembly: TypeForwardedTo(typeof(BooleanConverter))]
[assembly: TypeForwardedTo(typeof(BrowsableAttribute))]
[assembly: TypeForwardedTo(typeof(ByteConverter))]
[assembly: TypeForwardedTo(typeof(CancelEventArgs))]
[assembly: TypeForwardedTo(typeof(CancelEventHandler))]
[assembly: TypeForwardedTo(typeof(CategoryAttribute))]
[assembly: TypeForwardedTo(typeof(CharConverter))]
[assembly: TypeForwardedTo(typeof(CollectionChangeAction))]
[assembly: TypeForwardedTo(typeof(CollectionChangeEventArgs))]
[assembly: TypeForwardedTo(typeof(CollectionChangeEventHandler))]
[assembly: TypeForwardedTo(typeof(CollectionConverter))]
[assembly: TypeForwardedTo(typeof(ComplexBindingPropertiesAttribute))]
[assembly: TypeForwardedTo(typeof(Component))]
[assembly: TypeForwardedTo(typeof(ComponentCollection))]
[assembly: TypeForwardedTo(typeof(ComponentConverter))]
[assembly: TypeForwardedTo(typeof(ComponentEditor))]
[assembly: TypeForwardedTo(typeof(ComponentResourceManager))]
[assembly: TypeForwardedTo(typeof(Container))]
[assembly: TypeForwardedTo(typeof(ContainerFilterService))]
[assembly: TypeForwardedTo(typeof(CultureInfoConverter))]
[assembly: TypeForwardedTo(typeof(CustomTypeDescriptor))]
[assembly: TypeForwardedTo(typeof(DataErrorsChangedEventArgs))]
[assembly: TypeForwardedTo(typeof(DataObjectAttribute))]
[assembly: TypeForwardedTo(typeof(DataObjectFieldAttribute))]
[assembly: TypeForwardedTo(typeof(DataObjectMethodAttribute))]
[assembly: TypeForwardedTo(typeof(DataObjectMethodType))]
[assembly: TypeForwardedTo(typeof(DateTimeConverter))]
[assembly: TypeForwardedTo(typeof(DateTimeOffsetConverter))]
[assembly: TypeForwardedTo(typeof(DecimalConverter))]
[assembly: TypeForwardedTo(typeof(DefaultBindingPropertyAttribute))]
[assembly: TypeForwardedTo(typeof(DefaultEventAttribute))]
[assembly: TypeForwardedTo(typeof(DefaultPropertyAttribute))]
[assembly: TypeForwardedTo(typeof(DefaultValueAttribute))]
[assembly: TypeForwardedTo(typeof(DescriptionAttribute))]
[assembly: TypeForwardedTo(typeof(ActiveDesignerEventArgs))]
[assembly: TypeForwardedTo(typeof(ActiveDesignerEventHandler))]
[assembly: TypeForwardedTo(typeof(CheckoutException))]
[assembly: TypeForwardedTo(typeof(CommandID))]
[assembly: TypeForwardedTo(typeof(ComponentChangedEventArgs))]
[assembly: TypeForwardedTo(typeof(ComponentChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(ComponentChangingEventArgs))]
[assembly: TypeForwardedTo(typeof(ComponentChangingEventHandler))]
[assembly: TypeForwardedTo(typeof(ComponentEventArgs))]
[assembly: TypeForwardedTo(typeof(ComponentEventHandler))]
[assembly: TypeForwardedTo(typeof(ComponentRenameEventArgs))]
[assembly: TypeForwardedTo(typeof(ComponentRenameEventHandler))]
[assembly: TypeForwardedTo(typeof(DesignerCollection))]
[assembly: TypeForwardedTo(typeof(DesignerEventArgs))]
[assembly: TypeForwardedTo(typeof(DesignerEventHandler))]
[assembly: TypeForwardedTo(typeof(DesignerOptionService))]
[assembly: TypeForwardedTo(typeof(DesignerTransaction))]
[assembly: TypeForwardedTo(typeof(DesignerTransactionCloseEventArgs))]
[assembly: TypeForwardedTo(typeof(DesignerTransactionCloseEventHandler))]
[assembly: TypeForwardedTo(typeof(DesignerVerb))]
[assembly: TypeForwardedTo(typeof(DesignerVerbCollection))]
[assembly: TypeForwardedTo(typeof(DesigntimeLicenseContext))]
[assembly: TypeForwardedTo(typeof(DesigntimeLicenseContextSerializer))]
[assembly: TypeForwardedTo(typeof(HelpContextType))]
[assembly: TypeForwardedTo(typeof(HelpKeywordAttribute))]
[assembly: TypeForwardedTo(typeof(HelpKeywordType))]
[assembly: TypeForwardedTo(typeof(IComponentChangeService))]
[assembly: TypeForwardedTo(typeof(IComponentDiscoveryService))]
[assembly: TypeForwardedTo(typeof(IComponentInitializer))]
[assembly: TypeForwardedTo(typeof(IDesigner))]
[assembly: TypeForwardedTo(typeof(IDesignerEventService))]
[assembly: TypeForwardedTo(typeof(IDesignerFilter))]
[assembly: TypeForwardedTo(typeof(IDesignerHost))]
[assembly: TypeForwardedTo(typeof(IDesignerHostTransactionState))]
[assembly: TypeForwardedTo(typeof(IDesignerOptionService))]
[assembly: TypeForwardedTo(typeof(IDictionaryService))]
[assembly: TypeForwardedTo(typeof(IEventBindingService))]
[assembly: TypeForwardedTo(typeof(IExtenderListService))]
[assembly: TypeForwardedTo(typeof(IExtenderProviderService))]
[assembly: TypeForwardedTo(typeof(IHelpService))]
[assembly: TypeForwardedTo(typeof(IInheritanceService))]
[assembly: TypeForwardedTo(typeof(IMenuCommandService))]
[assembly: TypeForwardedTo(typeof(IReferenceService))]
[assembly: TypeForwardedTo(typeof(IResourceService))]
[assembly: TypeForwardedTo(typeof(IRootDesigner))]
[assembly: TypeForwardedTo(typeof(ISelectionService))]
[assembly: TypeForwardedTo(typeof(IServiceContainer))]
[assembly: TypeForwardedTo(typeof(ITreeDesigner))]
[assembly: TypeForwardedTo(typeof(ITypeDescriptorFilterService))]
[assembly: TypeForwardedTo(typeof(ITypeDiscoveryService))]
[assembly: TypeForwardedTo(typeof(ITypeResolutionService))]
[assembly: TypeForwardedTo(typeof(MenuCommand))]
[assembly: TypeForwardedTo(typeof(SelectionTypes))]
[assembly: TypeForwardedTo(typeof(ComponentSerializationService))]
[assembly: TypeForwardedTo(typeof(ContextStack))]
[assembly: TypeForwardedTo(typeof(DefaultSerializationProviderAttribute))]
[assembly: TypeForwardedTo(typeof(DesignerLoader))]
[assembly: TypeForwardedTo(typeof(DesignerSerializerAttribute))]
[assembly: TypeForwardedTo(typeof(IDesignerLoaderHost))]
[assembly: TypeForwardedTo(typeof(IDesignerLoaderHost2))]
[assembly: TypeForwardedTo(typeof(IDesignerLoaderService))]
[assembly: TypeForwardedTo(typeof(IDesignerSerializationManager))]
[assembly: TypeForwardedTo(typeof(IDesignerSerializationProvider))]
[assembly: TypeForwardedTo(typeof(IDesignerSerializationService))]
[assembly: TypeForwardedTo(typeof(INameCreationService))]
[assembly: TypeForwardedTo(typeof(InstanceDescriptor))]
[assembly: TypeForwardedTo(typeof(MemberRelationship))]
[assembly: TypeForwardedTo(typeof(MemberRelationshipService))]
[assembly: TypeForwardedTo(typeof(ResolveNameEventArgs))]
[assembly: TypeForwardedTo(typeof(ResolveNameEventHandler))]
[assembly: TypeForwardedTo(typeof(RootDesignerSerializerAttribute))]
[assembly: TypeForwardedTo(typeof(SerializationStore))]
[assembly: TypeForwardedTo(typeof(ServiceContainer))]
[assembly: TypeForwardedTo(typeof(ServiceCreatorCallback))]
[assembly: TypeForwardedTo(typeof(StandardCommands))]
[assembly: TypeForwardedTo(typeof(StandardToolWindows))]
[assembly: TypeForwardedTo(typeof(TypeDescriptionProviderService))]
[assembly: TypeForwardedTo(typeof(ViewTechnology))]
[assembly: TypeForwardedTo(typeof(DesignerAttribute))]
[assembly: TypeForwardedTo(typeof(DesignerCategoryAttribute))]
[assembly: TypeForwardedTo(typeof(DesignerSerializationVisibility))]
[assembly: TypeForwardedTo(typeof(DesignerSerializationVisibilityAttribute))]
[assembly: TypeForwardedTo(typeof(DesignOnlyAttribute))]
[assembly: TypeForwardedTo(typeof(DesignTimeVisibleAttribute))]
[assembly: TypeForwardedTo(typeof(DisplayNameAttribute))]
[assembly: TypeForwardedTo(typeof(DoubleConverter))]
[assembly: TypeForwardedTo(typeof(DoWorkEventArgs))]
[assembly: TypeForwardedTo(typeof(DoWorkEventHandler))]
[assembly: TypeForwardedTo(typeof(EditorAttribute))]
[assembly: TypeForwardedTo(typeof(EditorBrowsableAttribute))]
[assembly: TypeForwardedTo(typeof(EditorBrowsableState))]
[assembly: TypeForwardedTo(typeof(EnumConverter))]
[assembly: TypeForwardedTo(typeof(EventDescriptor))]
[assembly: TypeForwardedTo(typeof(EventDescriptorCollection))]
[assembly: TypeForwardedTo(typeof(EventHandlerList))]
[assembly: TypeForwardedTo(typeof(ExpandableObjectConverter))]
[assembly: TypeForwardedTo(typeof(ExtenderProvidedPropertyAttribute))]
[assembly: TypeForwardedTo(typeof(GuidConverter))]
[assembly: TypeForwardedTo(typeof(HandledEventArgs))]
[assembly: TypeForwardedTo(typeof(HandledEventHandler))]
[assembly: TypeForwardedTo(typeof(IBindingList))]
[assembly: TypeForwardedTo(typeof(IBindingListView))]
[assembly: TypeForwardedTo(typeof(ICancelAddNew))]
[assembly: TypeForwardedTo(typeof(IChangeTracking))]
[assembly: TypeForwardedTo(typeof(IComNativeDescriptorHandler))]
[assembly: TypeForwardedTo(typeof(IComponent))]
[assembly: TypeForwardedTo(typeof(IContainer))]
[assembly: TypeForwardedTo(typeof(ICustomTypeDescriptor))]
[assembly: TypeForwardedTo(typeof(IDataErrorInfo))]
[assembly: TypeForwardedTo(typeof(IEditableObject))]
[assembly: TypeForwardedTo(typeof(IExtenderProvider))]
[assembly: TypeForwardedTo(typeof(IIntellisenseBuilder))]
[assembly: TypeForwardedTo(typeof(IListSource))]
[assembly: TypeForwardedTo(typeof(ImmutableObjectAttribute))]
[assembly: TypeForwardedTo(typeof(INestedContainer))]
[assembly: TypeForwardedTo(typeof(INestedSite))]
[assembly: TypeForwardedTo(typeof(InheritanceAttribute))]
[assembly: TypeForwardedTo(typeof(InheritanceLevel))]
[assembly: TypeForwardedTo(typeof(InitializationEventAttribute))]
[assembly: TypeForwardedTo(typeof(INotifyDataErrorInfo))]
[assembly: TypeForwardedTo(typeof(INotifyPropertyChanged))]
[assembly: TypeForwardedTo(typeof(INotifyPropertyChanging))]
[assembly: TypeForwardedTo(typeof(InstallerTypeAttribute))]
[assembly: TypeForwardedTo(typeof(InstanceCreationEditor))]
[assembly: TypeForwardedTo(typeof(Int16Converter))]
[assembly: TypeForwardedTo(typeof(Int32Converter))]
[assembly: TypeForwardedTo(typeof(Int64Converter))]
[assembly: TypeForwardedTo(typeof(InvalidAsynchronousStateException))]
[assembly: TypeForwardedTo(typeof(InvalidEnumArgumentException))]
[assembly: TypeForwardedTo(typeof(IRaiseItemChangedEvents))]
[assembly: TypeForwardedTo(typeof(IRevertibleChangeTracking))]
[assembly: TypeForwardedTo(typeof(ISite))]
[assembly: TypeForwardedTo(typeof(ISupportInitialize))]
[assembly: TypeForwardedTo(typeof(ISupportInitializeNotification))]
[assembly: TypeForwardedTo(typeof(ISynchronizeInvoke))]
[assembly: TypeForwardedTo(typeof(ITypeDescriptorContext))]
[assembly: TypeForwardedTo(typeof(ITypedList))]
[assembly: TypeForwardedTo(typeof(License))]
[assembly: TypeForwardedTo(typeof(LicenseContext))]
[assembly: TypeForwardedTo(typeof(LicenseException))]
[assembly: TypeForwardedTo(typeof(LicenseManager))]
[assembly: TypeForwardedTo(typeof(LicenseProvider))]
[assembly: TypeForwardedTo(typeof(LicenseProviderAttribute))]
[assembly: TypeForwardedTo(typeof(LicenseUsageMode))]
[assembly: TypeForwardedTo(typeof(LicFileLicenseProvider))]
[assembly: TypeForwardedTo(typeof(ListBindableAttribute))]
[assembly: TypeForwardedTo(typeof(ListChangedEventArgs))]
[assembly: TypeForwardedTo(typeof(ListChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(ListChangedType))]
[assembly: TypeForwardedTo(typeof(ListSortDescription))]
[assembly: TypeForwardedTo(typeof(ListSortDescriptionCollection))]
[assembly: TypeForwardedTo(typeof(ListSortDirection))]
[assembly: TypeForwardedTo(typeof(LocalizableAttribute))]
[assembly: TypeForwardedTo(typeof(LookupBindingPropertiesAttribute))]
[assembly: TypeForwardedTo(typeof(MarshalByValueComponent))]
[assembly: TypeForwardedTo(typeof(MaskedTextProvider))]
[assembly: TypeForwardedTo(typeof(MaskedTextResultHint))]
[assembly: TypeForwardedTo(typeof(MemberDescriptor))]
[assembly: TypeForwardedTo(typeof(MergablePropertyAttribute))]
[assembly: TypeForwardedTo(typeof(MultilineStringConverter))]
[assembly: TypeForwardedTo(typeof(NestedContainer))]
[assembly: TypeForwardedTo(typeof(NotifyParentPropertyAttribute))]
[assembly: TypeForwardedTo(typeof(NullableConverter))]
[assembly: TypeForwardedTo(typeof(ParenthesizePropertyNameAttribute))]
[assembly: TypeForwardedTo(typeof(PasswordPropertyTextAttribute))]
[assembly: TypeForwardedTo(typeof(ProgressChangedEventArgs))]
[assembly: TypeForwardedTo(typeof(ProgressChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(PropertyChangedEventArgs))]
[assembly: TypeForwardedTo(typeof(PropertyChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(PropertyChangingEventArgs))]
[assembly: TypeForwardedTo(typeof(PropertyChangingEventHandler))]
[assembly: TypeForwardedTo(typeof(PropertyDescriptor))]
[assembly: TypeForwardedTo(typeof(PropertyDescriptorCollection))]
[assembly: TypeForwardedTo(typeof(PropertyTabAttribute))]
[assembly: TypeForwardedTo(typeof(PropertyTabScope))]
[assembly: TypeForwardedTo(typeof(ProvidePropertyAttribute))]
[assembly: TypeForwardedTo(typeof(ReadOnlyAttribute))]
[assembly: TypeForwardedTo(typeof(RecommendedAsConfigurableAttribute))]
[assembly: TypeForwardedTo(typeof(ReferenceConverter))]
[assembly: TypeForwardedTo(typeof(RefreshEventArgs))]
[assembly: TypeForwardedTo(typeof(RefreshEventHandler))]
[assembly: TypeForwardedTo(typeof(RefreshProperties))]
[assembly: TypeForwardedTo(typeof(RefreshPropertiesAttribute))]
[assembly: TypeForwardedTo(typeof(RunInstallerAttribute))]
[assembly: TypeForwardedTo(typeof(RunWorkerCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(RunWorkerCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(SByteConverter))]
[assembly: TypeForwardedTo(typeof(SettingsBindableAttribute))]
[assembly: TypeForwardedTo(typeof(SingleConverter))]
[assembly: TypeForwardedTo(typeof(StringConverter))]
[assembly: TypeForwardedTo(typeof(SyntaxCheck))]
[assembly: TypeForwardedTo(typeof(TimeSpanConverter))]
[assembly: TypeForwardedTo(typeof(ToolboxItemAttribute))]
[assembly: TypeForwardedTo(typeof(ToolboxItemFilterAttribute))]
[assembly: TypeForwardedTo(typeof(ToolboxItemFilterType))]
[assembly: TypeForwardedTo(typeof(TypeConverter))]
[assembly: TypeForwardedTo(typeof(TypeConverterAttribute))]
[assembly: TypeForwardedTo(typeof(TypeDescriptionProvider))]
[assembly: TypeForwardedTo(typeof(TypeDescriptionProviderAttribute))]
[assembly: TypeForwardedTo(typeof(TypeDescriptor))]
[assembly: TypeForwardedTo(typeof(TypeListConverter))]
[assembly: TypeForwardedTo(typeof(UInt16Converter))]
[assembly: TypeForwardedTo(typeof(UInt32Converter))]
[assembly: TypeForwardedTo(typeof(UInt64Converter))]
[assembly: TypeForwardedTo(typeof(WarningException))]
[assembly: TypeForwardedTo(typeof(Win32Exception))]
[assembly: TypeForwardedTo(typeof(AssemblyHashAlgorithm))]
[assembly: TypeForwardedTo(typeof(AssemblyVersionCompatibility))]
[assembly: TypeForwardedTo(typeof(Console))]
[assembly: TypeForwardedTo(typeof(ConsoleCancelEventArgs))]
[assembly: TypeForwardedTo(typeof(ConsoleCancelEventHandler))]
[assembly: TypeForwardedTo(typeof(ConsoleColor))]
[assembly: TypeForwardedTo(typeof(ConsoleKey))]
[assembly: TypeForwardedTo(typeof(ConsoleKeyInfo))]
[assembly: TypeForwardedTo(typeof(ConsoleModifiers))]
[assembly: TypeForwardedTo(typeof(ConsoleSpecialKey))]
[assembly: TypeForwardedTo(typeof(ContextBoundObject))]
[assembly: TypeForwardedTo(typeof(ContextMarshalException))]
[assembly: TypeForwardedTo(typeof(ContextStaticAttribute))]
[assembly: TypeForwardedTo(typeof(Convert))]
[assembly: TypeForwardedTo(typeof(Converter<, >))]
[assembly: TypeForwardedTo(typeof(AcceptRejectRule))]
[assembly: TypeForwardedTo(typeof(CommandBehavior))]
[assembly: TypeForwardedTo(typeof(CommandType))]
[assembly: TypeForwardedTo(typeof(CatalogLocation))]
[assembly: TypeForwardedTo(typeof(DataAdapter))]
[assembly: TypeForwardedTo(typeof(DataColumnMapping))]
[assembly: TypeForwardedTo(typeof(DataColumnMappingCollection))]
[assembly: TypeForwardedTo(typeof(DataTableMapping))]
[assembly: TypeForwardedTo(typeof(DataTableMappingCollection))]
[assembly: TypeForwardedTo(typeof(DbColumn))]
[assembly: TypeForwardedTo(typeof(DbCommand))]
[assembly: TypeForwardedTo(typeof(DbCommandBuilder))]
[assembly: TypeForwardedTo(typeof(DbConnection))]
[assembly: TypeForwardedTo(typeof(DbConnectionStringBuilder))]
[assembly: TypeForwardedTo(typeof(DbDataAdapter))]
[assembly: TypeForwardedTo(typeof(DbDataReader))]
[assembly: TypeForwardedTo(typeof(DbDataReaderExtensions))]
[assembly: TypeForwardedTo(typeof(DbDataRecord))]
[assembly: TypeForwardedTo(typeof(DbDataSourceEnumerator))]
[assembly: TypeForwardedTo(typeof(DbEnumerator))]
[assembly: TypeForwardedTo(typeof(DbException))]
[assembly: TypeForwardedTo(typeof(DbMetaDataCollectionNames))]
[assembly: TypeForwardedTo(typeof(DbMetaDataColumnNames))]
[assembly: TypeForwardedTo(typeof(DbParameter))]
[assembly: TypeForwardedTo(typeof(DbParameterCollection))]
[assembly: TypeForwardedTo(typeof(DbProviderFactories))]
[assembly: TypeForwardedTo(typeof(DbProviderFactory))]
[assembly: TypeForwardedTo(typeof(DbProviderSpecificTypePropertyAttribute))]
[assembly: TypeForwardedTo(typeof(DbTransaction))]
[assembly: TypeForwardedTo(typeof(GroupByBehavior))]
[assembly: TypeForwardedTo(typeof(IDbColumnSchemaGenerator))]
[assembly: TypeForwardedTo(typeof(IdentifierCase))]
[assembly: TypeForwardedTo(typeof(RowUpdatedEventArgs))]
[assembly: TypeForwardedTo(typeof(RowUpdatingEventArgs))]
[assembly: TypeForwardedTo(typeof(SchemaTableColumn))]
[assembly: TypeForwardedTo(typeof(SchemaTableOptionalColumn))]
[assembly: TypeForwardedTo(typeof(SupportedJoinOperators))]
[assembly: TypeForwardedTo(typeof(ConflictOption))]
[assembly: TypeForwardedTo(typeof(ConnectionState))]
[assembly: TypeForwardedTo(typeof(Constraint))]
[assembly: TypeForwardedTo(typeof(ConstraintCollection))]
[assembly: TypeForwardedTo(typeof(ConstraintException))]
[assembly: TypeForwardedTo(typeof(DataColumn))]
[assembly: TypeForwardedTo(typeof(DataColumnChangeEventArgs))]
[assembly: TypeForwardedTo(typeof(DataColumnChangeEventHandler))]
[assembly: TypeForwardedTo(typeof(DataColumnCollection))]
[assembly: TypeForwardedTo(typeof(DataException))]
[assembly: TypeForwardedTo(typeof(DataReaderExtensions))]
[assembly: TypeForwardedTo(typeof(DataRelation))]
[assembly: TypeForwardedTo(typeof(DataRelationCollection))]
[assembly: TypeForwardedTo(typeof(DataRow))]
[assembly: TypeForwardedTo(typeof(DataRowAction))]
[assembly: TypeForwardedTo(typeof(DataRowBuilder))]
[assembly: TypeForwardedTo(typeof(DataRowChangeEventArgs))]
[assembly: TypeForwardedTo(typeof(DataRowChangeEventHandler))]
[assembly: TypeForwardedTo(typeof(DataRowCollection))]
[assembly: TypeForwardedTo(typeof(DataRowComparer))]
[assembly: TypeForwardedTo(typeof(DataRowComparer<>))]
[assembly: TypeForwardedTo(typeof(DataRowExtensions))]
[assembly: TypeForwardedTo(typeof(DataRowState))]
[assembly: TypeForwardedTo(typeof(DataRowVersion))]
[assembly: TypeForwardedTo(typeof(DataRowView))]
[assembly: TypeForwardedTo(typeof(DataSet))]
[assembly: TypeForwardedTo(typeof(DataSetDateTime))]
[assembly: TypeForwardedTo(typeof(DataSysDescriptionAttribute))]
[assembly: TypeForwardedTo(typeof(DataTable))]
[assembly: TypeForwardedTo(typeof(DataTableClearEventArgs))]
[assembly: TypeForwardedTo(typeof(DataTableClearEventHandler))]
[assembly: TypeForwardedTo(typeof(DataTableCollection))]
[assembly: TypeForwardedTo(typeof(DataTableExtensions))]
[assembly: TypeForwardedTo(typeof(DataTableNewRowEventArgs))]
[assembly: TypeForwardedTo(typeof(DataTableNewRowEventHandler))]
[assembly: TypeForwardedTo(typeof(DataTableReader))]
[assembly: TypeForwardedTo(typeof(DataView))]
[assembly: TypeForwardedTo(typeof(DataViewManager))]
[assembly: TypeForwardedTo(typeof(DataViewRowState))]
[assembly: TypeForwardedTo(typeof(DataViewSetting))]
[assembly: TypeForwardedTo(typeof(DataViewSettingCollection))]
[assembly: TypeForwardedTo(typeof(DBConcurrencyException))]
[assembly: TypeForwardedTo(typeof(DbType))]
[assembly: TypeForwardedTo(typeof(DeletedRowInaccessibleException))]
[assembly: TypeForwardedTo(typeof(DuplicateNameException))]
[assembly: TypeForwardedTo(typeof(EnumerableRowCollection))]
[assembly: TypeForwardedTo(typeof(EnumerableRowCollection<>))]
[assembly: TypeForwardedTo(typeof(EnumerableRowCollectionExtensions))]
[assembly: TypeForwardedTo(typeof(EvaluateException))]
[assembly: TypeForwardedTo(typeof(FillErrorEventArgs))]
[assembly: TypeForwardedTo(typeof(FillErrorEventHandler))]
[assembly: TypeForwardedTo(typeof(ForeignKeyConstraint))]
[assembly: TypeForwardedTo(typeof(IColumnMapping))]
[assembly: TypeForwardedTo(typeof(IColumnMappingCollection))]
[assembly: TypeForwardedTo(typeof(IDataAdapter))]
[assembly: TypeForwardedTo(typeof(IDataParameter))]
[assembly: TypeForwardedTo(typeof(IDataParameterCollection))]
[assembly: TypeForwardedTo(typeof(IDataReader))]
[assembly: TypeForwardedTo(typeof(IDataRecord))]
[assembly: TypeForwardedTo(typeof(IDbCommand))]
[assembly: TypeForwardedTo(typeof(IDbConnection))]
[assembly: TypeForwardedTo(typeof(IDbDataAdapter))]
[assembly: TypeForwardedTo(typeof(IDbDataParameter))]
[assembly: TypeForwardedTo(typeof(IDbTransaction))]
[assembly: TypeForwardedTo(typeof(InRowChangingEventException))]
[assembly: TypeForwardedTo(typeof(InternalDataCollectionBase))]
[assembly: TypeForwardedTo(typeof(InvalidConstraintException))]
[assembly: TypeForwardedTo(typeof(InvalidExpressionException))]
[assembly: TypeForwardedTo(typeof(System.Data.IsolationLevel))]
[assembly: TypeForwardedTo(typeof(ITableMapping))]
[assembly: TypeForwardedTo(typeof(ITableMappingCollection))]
[assembly: TypeForwardedTo(typeof(KeyRestrictionBehavior))]
[assembly: TypeForwardedTo(typeof(LoadOption))]
[assembly: TypeForwardedTo(typeof(MappingType))]
[assembly: TypeForwardedTo(typeof(MergeFailedEventArgs))]
[assembly: TypeForwardedTo(typeof(MergeFailedEventHandler))]
[assembly: TypeForwardedTo(typeof(MissingMappingAction))]
[assembly: TypeForwardedTo(typeof(MissingPrimaryKeyException))]
[assembly: TypeForwardedTo(typeof(MissingSchemaAction))]
[assembly: TypeForwardedTo(typeof(NoNullAllowedException))]
[assembly: TypeForwardedTo(typeof(OrderedEnumerableRowCollection<>))]
[assembly: TypeForwardedTo(typeof(ParameterDirection))]
[assembly: TypeForwardedTo(typeof(PropertyCollection))]
[assembly: TypeForwardedTo(typeof(ReadOnlyException))]
[assembly: TypeForwardedTo(typeof(RowNotInTableException))]
[assembly: TypeForwardedTo(typeof(Rule))]
[assembly: TypeForwardedTo(typeof(SchemaSerializationMode))]
[assembly: TypeForwardedTo(typeof(SchemaType))]
[assembly: TypeForwardedTo(typeof(SerializationFormat))]
[assembly: TypeForwardedTo(typeof(SqlDbType))]
[assembly: TypeForwardedTo(typeof(INullable))]
[assembly: TypeForwardedTo(typeof(SqlAlreadyFilledException))]
[assembly: TypeForwardedTo(typeof(SqlBinary))]
[assembly: TypeForwardedTo(typeof(SqlBoolean))]
[assembly: TypeForwardedTo(typeof(SqlByte))]
[assembly: TypeForwardedTo(typeof(SqlBytes))]
[assembly: TypeForwardedTo(typeof(SqlChars))]
[assembly: TypeForwardedTo(typeof(SqlCompareOptions))]
[assembly: TypeForwardedTo(typeof(SqlDateTime))]
[assembly: TypeForwardedTo(typeof(SqlDecimal))]
[assembly: TypeForwardedTo(typeof(SqlDouble))]
[assembly: TypeForwardedTo(typeof(SqlGuid))]
[assembly: TypeForwardedTo(typeof(SqlInt16))]
[assembly: TypeForwardedTo(typeof(SqlInt32))]
[assembly: TypeForwardedTo(typeof(SqlInt64))]
[assembly: TypeForwardedTo(typeof(SqlMoney))]
[assembly: TypeForwardedTo(typeof(SqlNotFilledException))]
[assembly: TypeForwardedTo(typeof(SqlNullValueException))]
[assembly: TypeForwardedTo(typeof(SqlSingle))]
[assembly: TypeForwardedTo(typeof(SqlString))]
[assembly: TypeForwardedTo(typeof(SqlTruncateException))]
[assembly: TypeForwardedTo(typeof(SqlTypeException))]
[assembly: TypeForwardedTo(typeof(SqlXml))]
[assembly: TypeForwardedTo(typeof(StorageState))]
[assembly: TypeForwardedTo(typeof(StateChangeEventArgs))]
[assembly: TypeForwardedTo(typeof(StateChangeEventHandler))]
[assembly: TypeForwardedTo(typeof(StatementCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(StatementCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(StatementType))]
[assembly: TypeForwardedTo(typeof(StrongTypingException))]
[assembly: TypeForwardedTo(typeof(SyntaxErrorException))]
[assembly: TypeForwardedTo(typeof(TypedTableBase<>))]
[assembly: TypeForwardedTo(typeof(TypedTableBaseExtensions))]
[assembly: TypeForwardedTo(typeof(UniqueConstraint))]
[assembly: TypeForwardedTo(typeof(UpdateRowSource))]
[assembly: TypeForwardedTo(typeof(UpdateStatus))]
[assembly: TypeForwardedTo(typeof(VersionNotFoundException))]
[assembly: TypeForwardedTo(typeof(XmlReadMode))]
[assembly: TypeForwardedTo(typeof(XmlWriteMode))]
[assembly: TypeForwardedTo(typeof(DataMisalignedException))]
[assembly: TypeForwardedTo(typeof(DateTime))]
[assembly: TypeForwardedTo(typeof(DateTimeKind))]
[assembly: TypeForwardedTo(typeof(DateTimeOffset))]
[assembly: TypeForwardedTo(typeof(DayOfWeek))]
[assembly: TypeForwardedTo(typeof(DBNull))]
[assembly: TypeForwardedTo(typeof(decimal))]
[assembly: TypeForwardedTo(typeof(Delegate))]
[assembly: TypeForwardedTo(typeof(BooleanSwitch))]
[assembly: TypeForwardedTo(typeof(AllowNullAttribute))]
[assembly: TypeForwardedTo(typeof(DisallowNullAttribute))]
[assembly: TypeForwardedTo(typeof(DoesNotReturnAttribute))]
[assembly: TypeForwardedTo(typeof(DoesNotReturnIfAttribute))]
[assembly: TypeForwardedTo(typeof(ExcludeFromCodeCoverageAttribute))]
[assembly: TypeForwardedTo(typeof(MaybeNullAttribute))]
[assembly: TypeForwardedTo(typeof(MaybeNullWhenAttribute))]
[assembly: TypeForwardedTo(typeof(NotNullAttribute))]
[assembly: TypeForwardedTo(typeof(NotNullIfNotNullAttribute))]
[assembly: TypeForwardedTo(typeof(NotNullWhenAttribute))]
[assembly: TypeForwardedTo(typeof(SuppressMessageAttribute))]
[assembly: TypeForwardedTo(typeof(ConditionalAttribute))]
[assembly: TypeForwardedTo(typeof(Contract))]
[assembly: TypeForwardedTo(typeof(ContractAbbreviatorAttribute))]
[assembly: TypeForwardedTo(typeof(ContractArgumentValidatorAttribute))]
[assembly: TypeForwardedTo(typeof(ContractClassAttribute))]
[assembly: TypeForwardedTo(typeof(ContractClassForAttribute))]
[assembly: TypeForwardedTo(typeof(ContractFailedEventArgs))]
[assembly: TypeForwardedTo(typeof(ContractFailureKind))]
[assembly: TypeForwardedTo(typeof(ContractInvariantMethodAttribute))]
[assembly: TypeForwardedTo(typeof(ContractOptionAttribute))]
[assembly: TypeForwardedTo(typeof(ContractPublicPropertyNameAttribute))]
[assembly: TypeForwardedTo(typeof(ContractReferenceAssemblyAttribute))]
[assembly: TypeForwardedTo(typeof(ContractRuntimeIgnoredAttribute))]
[assembly: TypeForwardedTo(typeof(ContractVerificationAttribute))]
[assembly: TypeForwardedTo(typeof(PureAttribute))]
[assembly: TypeForwardedTo(typeof(CorrelationManager))]
[assembly: TypeForwardedTo(typeof(DataReceivedEventArgs))]
[assembly: TypeForwardedTo(typeof(DataReceivedEventHandler))]
[assembly: TypeForwardedTo(typeof(Debug))]
[assembly: TypeForwardedTo(typeof(DebuggableAttribute))]
[assembly: TypeForwardedTo(typeof(Debugger))]
[assembly: TypeForwardedTo(typeof(DebuggerBrowsableAttribute))]
[assembly: TypeForwardedTo(typeof(DebuggerBrowsableState))]
[assembly: TypeForwardedTo(typeof(DebuggerDisplayAttribute))]
[assembly: TypeForwardedTo(typeof(DebuggerHiddenAttribute))]
[assembly: TypeForwardedTo(typeof(DebuggerNonUserCodeAttribute))]
[assembly: TypeForwardedTo(typeof(DebuggerStepperBoundaryAttribute))]
[assembly: TypeForwardedTo(typeof(DebuggerStepThroughAttribute))]
[assembly: TypeForwardedTo(typeof(DebuggerTypeProxyAttribute))]
[assembly: TypeForwardedTo(typeof(DebuggerVisualizerAttribute))]
[assembly: TypeForwardedTo(typeof(DefaultTraceListener))]
[assembly: TypeForwardedTo(typeof(DelimitedListTraceListener))]
[assembly: TypeForwardedTo(typeof(EventTypeFilter))]
[assembly: TypeForwardedTo(typeof(FileVersionInfo))]
[assembly: TypeForwardedTo(typeof(MonitoringDescriptionAttribute))]
[assembly: TypeForwardedTo(typeof(Process))]
[assembly: TypeForwardedTo(typeof(ProcessModule))]
[assembly: TypeForwardedTo(typeof(ProcessModuleCollection))]
[assembly: TypeForwardedTo(typeof(ProcessPriorityClass))]
[assembly: TypeForwardedTo(typeof(ProcessStartInfo))]
[assembly: TypeForwardedTo(typeof(ProcessThread))]
[assembly: TypeForwardedTo(typeof(ProcessThreadCollection))]
[assembly: TypeForwardedTo(typeof(ProcessWindowStyle))]
[assembly: TypeForwardedTo(typeof(SourceFilter))]
[assembly: TypeForwardedTo(typeof(SourceLevels))]
[assembly: TypeForwardedTo(typeof(SourceSwitch))]
[assembly: TypeForwardedTo(typeof(StackFrame))]
[assembly: TypeForwardedTo(typeof(StackFrameExtensions))]
[assembly: TypeForwardedTo(typeof(StackTrace))]
[assembly: TypeForwardedTo(typeof(Stopwatch))]
[assembly: TypeForwardedTo(typeof(Switch))]
[assembly: TypeForwardedTo(typeof(SwitchAttribute))]
[assembly: TypeForwardedTo(typeof(SwitchLevelAttribute))]
[assembly: TypeForwardedTo(typeof(ISymbolBinder))]
[assembly: TypeForwardedTo(typeof(ISymbolBinder1))]
[assembly: TypeForwardedTo(typeof(ISymbolDocument))]
[assembly: TypeForwardedTo(typeof(ISymbolDocumentWriter))]
[assembly: TypeForwardedTo(typeof(ISymbolMethod))]
[assembly: TypeForwardedTo(typeof(ISymbolNamespace))]
[assembly: TypeForwardedTo(typeof(ISymbolReader))]
[assembly: TypeForwardedTo(typeof(ISymbolScope))]
[assembly: TypeForwardedTo(typeof(ISymbolVariable))]
[assembly: TypeForwardedTo(typeof(ISymbolWriter))]
[assembly: TypeForwardedTo(typeof(SymAddressKind))]
[assembly: TypeForwardedTo(typeof(SymbolToken))]
[assembly: TypeForwardedTo(typeof(SymDocumentType))]
[assembly: TypeForwardedTo(typeof(SymLanguageType))]
[assembly: TypeForwardedTo(typeof(SymLanguageVendor))]
[assembly: TypeForwardedTo(typeof(TextWriterTraceListener))]
[assembly: TypeForwardedTo(typeof(ThreadPriorityLevel))]
[assembly: TypeForwardedTo(typeof(System.Diagnostics.ThreadState))]
[assembly: TypeForwardedTo(typeof(ThreadWaitReason))]
[assembly: TypeForwardedTo(typeof(Trace))]
[assembly: TypeForwardedTo(typeof(TraceEventCache))]
[assembly: TypeForwardedTo(typeof(TraceEventType))]
[assembly: TypeForwardedTo(typeof(TraceFilter))]
[assembly: TypeForwardedTo(typeof(TraceLevel))]
[assembly: TypeForwardedTo(typeof(TraceListener))]
[assembly: TypeForwardedTo(typeof(TraceListenerCollection))]
[assembly: TypeForwardedTo(typeof(TraceOptions))]
[assembly: TypeForwardedTo(typeof(TraceSource))]
[assembly: TypeForwardedTo(typeof(TraceSwitch))]
[assembly: TypeForwardedTo(typeof(DiagnosticCounter))]
[assembly: TypeForwardedTo(typeof(EventActivityOptions))]
[assembly: TypeForwardedTo(typeof(EventAttribute))]
[assembly: TypeForwardedTo(typeof(EventChannel))]
[assembly: TypeForwardedTo(typeof(EventCommand))]
[assembly: TypeForwardedTo(typeof(EventCommandEventArgs))]
[assembly: TypeForwardedTo(typeof(EventCounter))]
[assembly: TypeForwardedTo(typeof(EventDataAttribute))]
[assembly: TypeForwardedTo(typeof(EventFieldAttribute))]
[assembly: TypeForwardedTo(typeof(EventFieldFormat))]
[assembly: TypeForwardedTo(typeof(EventFieldTags))]
[assembly: TypeForwardedTo(typeof(EventIgnoreAttribute))]
[assembly: TypeForwardedTo(typeof(EventKeywords))]
[assembly: TypeForwardedTo(typeof(EventLevel))]
[assembly: TypeForwardedTo(typeof(EventListener))]
[assembly: TypeForwardedTo(typeof(EventManifestOptions))]
[assembly: TypeForwardedTo(typeof(EventOpcode))]
[assembly: TypeForwardedTo(typeof(EventSource))]
[assembly: TypeForwardedTo(typeof(EventSourceAttribute))]
[assembly: TypeForwardedTo(typeof(EventSourceCreatedEventArgs))]
[assembly: TypeForwardedTo(typeof(EventSourceException))]
[assembly: TypeForwardedTo(typeof(EventSourceOptions))]
[assembly: TypeForwardedTo(typeof(EventSourceSettings))]
[assembly: TypeForwardedTo(typeof(EventTags))]
[assembly: TypeForwardedTo(typeof(EventTask))]
[assembly: TypeForwardedTo(typeof(EventWrittenEventArgs))]
[assembly: TypeForwardedTo(typeof(IncrementingEventCounter))]
[assembly: TypeForwardedTo(typeof(IncrementingPollingCounter))]
[assembly: TypeForwardedTo(typeof(NonEventAttribute))]
[assembly: TypeForwardedTo(typeof(PollingCounter))]
[assembly: TypeForwardedTo(typeof(DivideByZeroException))]
[assembly: TypeForwardedTo(typeof(DllNotFoundException))]
[assembly: TypeForwardedTo(typeof(double))]
[assembly: TypeForwardedTo(typeof(Color))]
[assembly: TypeForwardedTo(typeof(ColorConverter))]
[assembly: TypeForwardedTo(typeof(KnownColor))]
[assembly: TypeForwardedTo(typeof(Point))]
[assembly: TypeForwardedTo(typeof(PointConverter))]
[assembly: TypeForwardedTo(typeof(PointF))]
[assembly: TypeForwardedTo(typeof(Rectangle))]
[assembly: TypeForwardedTo(typeof(RectangleConverter))]
[assembly: TypeForwardedTo(typeof(RectangleF))]
[assembly: TypeForwardedTo(typeof(Size))]
[assembly: TypeForwardedTo(typeof(SizeConverter))]
[assembly: TypeForwardedTo(typeof(SizeF))]
[assembly: TypeForwardedTo(typeof(SizeFConverter))]
[assembly: TypeForwardedTo(typeof(DuplicateWaitObjectException))]
[assembly: TypeForwardedTo(typeof(BinaryOperationBinder))]
[assembly: TypeForwardedTo(typeof(BindingRestrictions))]
[assembly: TypeForwardedTo(typeof(CallInfo))]
[assembly: TypeForwardedTo(typeof(ConvertBinder))]
[assembly: TypeForwardedTo(typeof(CreateInstanceBinder))]
[assembly: TypeForwardedTo(typeof(DeleteIndexBinder))]
[assembly: TypeForwardedTo(typeof(DeleteMemberBinder))]
[assembly: TypeForwardedTo(typeof(DynamicMetaObject))]
[assembly: TypeForwardedTo(typeof(DynamicMetaObjectBinder))]
[assembly: TypeForwardedTo(typeof(DynamicObject))]
[assembly: TypeForwardedTo(typeof(ExpandoObject))]
[assembly: TypeForwardedTo(typeof(GetIndexBinder))]
[assembly: TypeForwardedTo(typeof(GetMemberBinder))]
[assembly: TypeForwardedTo(typeof(IDynamicMetaObjectProvider))]
[assembly: TypeForwardedTo(typeof(IInvokeOnGetBinder))]
[assembly: TypeForwardedTo(typeof(InvokeBinder))]
[assembly: TypeForwardedTo(typeof(InvokeMemberBinder))]
[assembly: TypeForwardedTo(typeof(SetIndexBinder))]
[assembly: TypeForwardedTo(typeof(SetMemberBinder))]
[assembly: TypeForwardedTo(typeof(UnaryOperationBinder))]
[assembly: TypeForwardedTo(typeof(EntryPointNotFoundException))]
[assembly: TypeForwardedTo(typeof(Enum))]
[assembly: TypeForwardedTo(typeof(Environment))]
[assembly: TypeForwardedTo(typeof(EnvironmentVariableTarget))]
[assembly: TypeForwardedTo(typeof(EventArgs))]
[assembly: TypeForwardedTo(typeof(EventHandler))]
[assembly: TypeForwardedTo(typeof(EventHandler<>))]
[assembly: TypeForwardedTo(typeof(Exception))]
[assembly: TypeForwardedTo(typeof(ExecutionEngineException))]
[assembly: TypeForwardedTo(typeof(FieldAccessException))]
[assembly: TypeForwardedTo(typeof(FileStyleUriParser))]
[assembly: TypeForwardedTo(typeof(FlagsAttribute))]
[assembly: TypeForwardedTo(typeof(FormatException))]
[assembly: TypeForwardedTo(typeof(FormattableString))]
[assembly: TypeForwardedTo(typeof(FtpStyleUriParser))]
[assembly: TypeForwardedTo(typeof(Func<>))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , , , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, >))]
[assembly: TypeForwardedTo(typeof(Func<, , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , , , , , >))]
[assembly: TypeForwardedTo(typeof(GC))]
[assembly: TypeForwardedTo(typeof(GCCollectionMode))]
[assembly: TypeForwardedTo(typeof(GCNotificationStatus))]
[assembly: TypeForwardedTo(typeof(GenericUriParser))]
[assembly: TypeForwardedTo(typeof(GenericUriParserOptions))]
[assembly: TypeForwardedTo(typeof(Calendar))]
[assembly: TypeForwardedTo(typeof(CalendarAlgorithmType))]
[assembly: TypeForwardedTo(typeof(CalendarWeekRule))]
[assembly: TypeForwardedTo(typeof(CharUnicodeInfo))]
[assembly: TypeForwardedTo(typeof(ChineseLunisolarCalendar))]
[assembly: TypeForwardedTo(typeof(CompareInfo))]
[assembly: TypeForwardedTo(typeof(CompareOptions))]
[assembly: TypeForwardedTo(typeof(CultureInfo))]
[assembly: TypeForwardedTo(typeof(CultureNotFoundException))]
[assembly: TypeForwardedTo(typeof(CultureTypes))]
[assembly: TypeForwardedTo(typeof(DateTimeFormatInfo))]
[assembly: TypeForwardedTo(typeof(DateTimeStyles))]
[assembly: TypeForwardedTo(typeof(DaylightTime))]
[assembly: TypeForwardedTo(typeof(DigitShapes))]
[assembly: TypeForwardedTo(typeof(EastAsianLunisolarCalendar))]
[assembly: TypeForwardedTo(typeof(GlobalizationExtensions))]
[assembly: TypeForwardedTo(typeof(GregorianCalendar))]
[assembly: TypeForwardedTo(typeof(GregorianCalendarTypes))]
[assembly: TypeForwardedTo(typeof(HebrewCalendar))]
[assembly: TypeForwardedTo(typeof(HijriCalendar))]
[assembly: TypeForwardedTo(typeof(IdnMapping))]
[assembly: TypeForwardedTo(typeof(ISOWeek))]
[assembly: TypeForwardedTo(typeof(JapaneseCalendar))]
[assembly: TypeForwardedTo(typeof(JapaneseLunisolarCalendar))]
[assembly: TypeForwardedTo(typeof(JulianCalendar))]
[assembly: TypeForwardedTo(typeof(KoreanCalendar))]
[assembly: TypeForwardedTo(typeof(KoreanLunisolarCalendar))]
[assembly: TypeForwardedTo(typeof(NumberFormatInfo))]
[assembly: TypeForwardedTo(typeof(NumberStyles))]
[assembly: TypeForwardedTo(typeof(PersianCalendar))]
[assembly: TypeForwardedTo(typeof(RegionInfo))]
[assembly: TypeForwardedTo(typeof(SortKey))]
[assembly: TypeForwardedTo(typeof(SortVersion))]
[assembly: TypeForwardedTo(typeof(StringInfo))]
[assembly: TypeForwardedTo(typeof(TaiwanCalendar))]
[assembly: TypeForwardedTo(typeof(TaiwanLunisolarCalendar))]
[assembly: TypeForwardedTo(typeof(TextElementEnumerator))]
[assembly: TypeForwardedTo(typeof(TextInfo))]
[assembly: TypeForwardedTo(typeof(ThaiBuddhistCalendar))]
[assembly: TypeForwardedTo(typeof(TimeSpanStyles))]
[assembly: TypeForwardedTo(typeof(UmAlQuraCalendar))]
[assembly: TypeForwardedTo(typeof(UnicodeCategory))]
[assembly: TypeForwardedTo(typeof(GopherStyleUriParser))]
[assembly: TypeForwardedTo(typeof(Guid))]
[assembly: TypeForwardedTo(typeof(HashCode))]
[assembly: TypeForwardedTo(typeof(HttpStyleUriParser))]
[assembly: TypeForwardedTo(typeof(IAsyncDisposable))]
[assembly: TypeForwardedTo(typeof(IAsyncResult))]
[assembly: TypeForwardedTo(typeof(ICloneable))]
[assembly: TypeForwardedTo(typeof(IComparable))]
[assembly: TypeForwardedTo(typeof(IComparable<>))]
[assembly: TypeForwardedTo(typeof(IConvertible))]
[assembly: TypeForwardedTo(typeof(ICustomFormatter))]
[assembly: TypeForwardedTo(typeof(IDisposable))]
[assembly: TypeForwardedTo(typeof(IEquatable<>))]
[assembly: TypeForwardedTo(typeof(IFormatProvider))]
[assembly: TypeForwardedTo(typeof(IFormattable))]
[assembly: TypeForwardedTo(typeof(Index))]
[assembly: TypeForwardedTo(typeof(IndexOutOfRangeException))]
[assembly: TypeForwardedTo(typeof(InsufficientExecutionStackException))]
[assembly: TypeForwardedTo(typeof(InsufficientMemoryException))]
[assembly: TypeForwardedTo(typeof(short))]
[assembly: TypeForwardedTo(typeof(int))]
[assembly: TypeForwardedTo(typeof(long))]
[assembly: TypeForwardedTo(typeof(IntPtr))]
[assembly: TypeForwardedTo(typeof(InvalidCastException))]
[assembly: TypeForwardedTo(typeof(InvalidOperationException))]
[assembly: TypeForwardedTo(typeof(InvalidProgramException))]
[assembly: TypeForwardedTo(typeof(InvalidTimeZoneException))]
[assembly: TypeForwardedTo(typeof(BinaryReader))]
[assembly: TypeForwardedTo(typeof(BinaryWriter))]
[assembly: TypeForwardedTo(typeof(BufferedStream))]
[assembly: TypeForwardedTo(typeof(BrotliDecoder))]
[assembly: TypeForwardedTo(typeof(BrotliEncoder))]
[assembly: TypeForwardedTo(typeof(BrotliStream))]
[assembly: TypeForwardedTo(typeof(CompressionLevel))]
[assembly: TypeForwardedTo(typeof(CompressionMode))]
[assembly: TypeForwardedTo(typeof(DeflateStream))]
[assembly: TypeForwardedTo(typeof(GZipStream))]
[assembly: TypeForwardedTo(typeof(ZipArchive))]
[assembly: TypeForwardedTo(typeof(ZipArchiveEntry))]
[assembly: TypeForwardedTo(typeof(ZipArchiveMode))]
[assembly: TypeForwardedTo(typeof(ZipFile))]
[assembly: TypeForwardedTo(typeof(ZipFileExtensions))]
[assembly: TypeForwardedTo(typeof(Directory))]
[assembly: TypeForwardedTo(typeof(DirectoryInfo))]
[assembly: TypeForwardedTo(typeof(DirectoryNotFoundException))]
[assembly: TypeForwardedTo(typeof(DriveInfo))]
[assembly: TypeForwardedTo(typeof(DriveNotFoundException))]
[assembly: TypeForwardedTo(typeof(DriveType))]
[assembly: TypeForwardedTo(typeof(EndOfStreamException))]
[assembly: TypeForwardedTo(typeof(FileSystemEntry))]
[assembly: TypeForwardedTo(typeof(FileSystemEnumerable<>))]
[assembly: TypeForwardedTo(typeof(FileSystemEnumerator<>))]
[assembly: TypeForwardedTo(typeof(FileSystemName))]
[assembly: TypeForwardedTo(typeof(EnumerationOptions))]
[assembly: TypeForwardedTo(typeof(ErrorEventArgs))]
[assembly: TypeForwardedTo(typeof(ErrorEventHandler))]
[assembly: TypeForwardedTo(typeof(File))]
[assembly: TypeForwardedTo(typeof(FileAccess))]
[assembly: TypeForwardedTo(typeof(FileAttributes))]
[assembly: TypeForwardedTo(typeof(FileInfo))]
[assembly: TypeForwardedTo(typeof(FileLoadException))]
[assembly: TypeForwardedTo(typeof(FileMode))]
[assembly: TypeForwardedTo(typeof(FileNotFoundException))]
[assembly: TypeForwardedTo(typeof(FileOptions))]
[assembly: TypeForwardedTo(typeof(FileShare))]
[assembly: TypeForwardedTo(typeof(FileStream))]
[assembly: TypeForwardedTo(typeof(FileSystemEventArgs))]
[assembly: TypeForwardedTo(typeof(FileSystemEventHandler))]
[assembly: TypeForwardedTo(typeof(FileSystemInfo))]
[assembly: TypeForwardedTo(typeof(FileSystemWatcher))]
[assembly: TypeForwardedTo(typeof(HandleInheritability))]
[assembly: TypeForwardedTo(typeof(InternalBufferOverflowException))]
[assembly: TypeForwardedTo(typeof(InvalidDataException))]
[assembly: TypeForwardedTo(typeof(IOException))]
[assembly: TypeForwardedTo(typeof(INormalizeForIsolatedStorage))]
[assembly: TypeForwardedTo(typeof(IsolatedStorage))]
[assembly: TypeForwardedTo(typeof(IsolatedStorageException))]
[assembly: TypeForwardedTo(typeof(IsolatedStorageFile))]
[assembly: TypeForwardedTo(typeof(IsolatedStorageFileStream))]
[assembly: TypeForwardedTo(typeof(IsolatedStorageScope))]
[assembly: TypeForwardedTo(typeof(MatchCasing))]
[assembly: TypeForwardedTo(typeof(MatchType))]
[assembly: TypeForwardedTo(typeof(MemoryMappedFile))]
[assembly: TypeForwardedTo(typeof(MemoryMappedFileAccess))]
[assembly: TypeForwardedTo(typeof(MemoryMappedFileOptions))]
[assembly: TypeForwardedTo(typeof(MemoryMappedFileRights))]
[assembly: TypeForwardedTo(typeof(MemoryMappedViewAccessor))]
[assembly: TypeForwardedTo(typeof(MemoryMappedViewStream))]
[assembly: TypeForwardedTo(typeof(MemoryStream))]
[assembly: TypeForwardedTo(typeof(NotifyFilters))]
[assembly: TypeForwardedTo(typeof(Path))]
[assembly: TypeForwardedTo(typeof(PathTooLongException))]
[assembly: TypeForwardedTo(typeof(AnonymousPipeClientStream))]
[assembly: TypeForwardedTo(typeof(AnonymousPipeServerStream))]
[assembly: TypeForwardedTo(typeof(NamedPipeClientStream))]
[assembly: TypeForwardedTo(typeof(NamedPipeServerStream))]
[assembly: TypeForwardedTo(typeof(PipeDirection))]
[assembly: TypeForwardedTo(typeof(PipeOptions))]
[assembly: TypeForwardedTo(typeof(PipeStream))]
[assembly: TypeForwardedTo(typeof(PipeStreamImpersonationWorker))]
[assembly: TypeForwardedTo(typeof(PipeTransmissionMode))]
[assembly: TypeForwardedTo(typeof(RenamedEventArgs))]
[assembly: TypeForwardedTo(typeof(RenamedEventHandler))]
[assembly: TypeForwardedTo(typeof(SearchOption))]
[assembly: TypeForwardedTo(typeof(SeekOrigin))]
[assembly: TypeForwardedTo(typeof(Stream))]
[assembly: TypeForwardedTo(typeof(StreamReader))]
[assembly: TypeForwardedTo(typeof(StreamWriter))]
[assembly: TypeForwardedTo(typeof(StringReader))]
[assembly: TypeForwardedTo(typeof(StringWriter))]
[assembly: TypeForwardedTo(typeof(TextReader))]
[assembly: TypeForwardedTo(typeof(TextWriter))]
[assembly: TypeForwardedTo(typeof(UnmanagedMemoryAccessor))]
[assembly: TypeForwardedTo(typeof(UnmanagedMemoryStream))]
[assembly: TypeForwardedTo(typeof(WaitForChangedResult))]
[assembly: TypeForwardedTo(typeof(WatcherChangeTypes))]
[assembly: TypeForwardedTo(typeof(IObservable<>))]
[assembly: TypeForwardedTo(typeof(IObserver<>))]
[assembly: TypeForwardedTo(typeof(IProgress<>))]
[assembly: TypeForwardedTo(typeof(IServiceProvider))]
[assembly: TypeForwardedTo(typeof(Lazy<>))]
[assembly: TypeForwardedTo(typeof(Lazy<, >))]
[assembly: TypeForwardedTo(typeof(LdapStyleUriParser))]
[assembly: TypeForwardedTo(typeof(Enumerable))]
[assembly: TypeForwardedTo(typeof(EnumerableExecutor))]
[assembly: TypeForwardedTo(typeof(EnumerableExecutor<>))]
[assembly: TypeForwardedTo(typeof(EnumerableQuery))]
[assembly: TypeForwardedTo(typeof(EnumerableQuery<>))]
[assembly: TypeForwardedTo(typeof(BinaryExpression))]
[assembly: TypeForwardedTo(typeof(BlockExpression))]
[assembly: TypeForwardedTo(typeof(CatchBlock))]
[assembly: TypeForwardedTo(typeof(ConditionalExpression))]
[assembly: TypeForwardedTo(typeof(ConstantExpression))]
[assembly: TypeForwardedTo(typeof(DebugInfoExpression))]
[assembly: TypeForwardedTo(typeof(DefaultExpression))]
[assembly: TypeForwardedTo(typeof(DynamicExpression))]
[assembly: TypeForwardedTo(typeof(DynamicExpressionVisitor))]
[assembly: TypeForwardedTo(typeof(ElementInit))]
[assembly: TypeForwardedTo(typeof(Expression))]
[assembly: TypeForwardedTo(typeof(Expression<>))]
[assembly: TypeForwardedTo(typeof(ExpressionType))]
[assembly: TypeForwardedTo(typeof(ExpressionVisitor))]
[assembly: TypeForwardedTo(typeof(GotoExpression))]
[assembly: TypeForwardedTo(typeof(GotoExpressionKind))]
[assembly: TypeForwardedTo(typeof(IArgumentProvider))]
[assembly: TypeForwardedTo(typeof(IDynamicExpression))]
[assembly: TypeForwardedTo(typeof(IndexExpression))]
[assembly: TypeForwardedTo(typeof(InvocationExpression))]
[assembly: TypeForwardedTo(typeof(LabelExpression))]
[assembly: TypeForwardedTo(typeof(LabelTarget))]
[assembly: TypeForwardedTo(typeof(LambdaExpression))]
[assembly: TypeForwardedTo(typeof(ListInitExpression))]
[assembly: TypeForwardedTo(typeof(LoopExpression))]
[assembly: TypeForwardedTo(typeof(MemberAssignment))]
[assembly: TypeForwardedTo(typeof(MemberBinding))]
[assembly: TypeForwardedTo(typeof(MemberBindingType))]
[assembly: TypeForwardedTo(typeof(MemberExpression))]
[assembly: TypeForwardedTo(typeof(MemberInitExpression))]
[assembly: TypeForwardedTo(typeof(MemberListBinding))]
[assembly: TypeForwardedTo(typeof(MemberMemberBinding))]
[assembly: TypeForwardedTo(typeof(MethodCallExpression))]
[assembly: TypeForwardedTo(typeof(NewArrayExpression))]
[assembly: TypeForwardedTo(typeof(NewExpression))]
[assembly: TypeForwardedTo(typeof(ParameterExpression))]
[assembly: TypeForwardedTo(typeof(RuntimeVariablesExpression))]
[assembly: TypeForwardedTo(typeof(SwitchCase))]
[assembly: TypeForwardedTo(typeof(SwitchExpression))]
[assembly: TypeForwardedTo(typeof(SymbolDocumentInfo))]
[assembly: TypeForwardedTo(typeof(TryExpression))]
[assembly: TypeForwardedTo(typeof(TypeBinaryExpression))]
[assembly: TypeForwardedTo(typeof(UnaryExpression))]
[assembly: TypeForwardedTo(typeof(IGrouping<, >))]
[assembly: TypeForwardedTo(typeof(ILookup<, >))]
[assembly: TypeForwardedTo(typeof(IOrderedEnumerable<>))]
[assembly: TypeForwardedTo(typeof(IOrderedQueryable))]
[assembly: TypeForwardedTo(typeof(IOrderedQueryable<>))]
[assembly: TypeForwardedTo(typeof(IQueryable))]
[assembly: TypeForwardedTo(typeof(IQueryable<>))]
[assembly: TypeForwardedTo(typeof(IQueryProvider))]
[assembly: TypeForwardedTo(typeof(Lookup<, >))]
[assembly: TypeForwardedTo(typeof(OrderedParallelQuery<>))]
[assembly: TypeForwardedTo(typeof(ParallelEnumerable))]
[assembly: TypeForwardedTo(typeof(ParallelExecutionMode))]
[assembly: TypeForwardedTo(typeof(ParallelMergeOptions))]
[assembly: TypeForwardedTo(typeof(ParallelQuery))]
[assembly: TypeForwardedTo(typeof(ParallelQuery<>))]
[assembly: TypeForwardedTo(typeof(Queryable))]
[assembly: TypeForwardedTo(typeof(LoaderOptimization))]
[assembly: TypeForwardedTo(typeof(LoaderOptimizationAttribute))]
[assembly: TypeForwardedTo(typeof(LocalDataStoreSlot))]
[assembly: TypeForwardedTo(typeof(MarshalByRefObject))]
[assembly: TypeForwardedTo(typeof(Math))]
[assembly: TypeForwardedTo(typeof(MathF))]
[assembly: TypeForwardedTo(typeof(MemberAccessException))]
[assembly: TypeForwardedTo(typeof(Memory<>))]
[assembly: TypeForwardedTo(typeof(MemoryExtensions))]
[assembly: TypeForwardedTo(typeof(MethodAccessException))]
[assembly: TypeForwardedTo(typeof(MidpointRounding))]
[assembly: TypeForwardedTo(typeof(MissingFieldException))]
[assembly: TypeForwardedTo(typeof(MissingMemberException))]
[assembly: TypeForwardedTo(typeof(MissingMethodException))]
[assembly: TypeForwardedTo(typeof(ModuleHandle))]
[assembly: TypeForwardedTo(typeof(MTAThreadAttribute))]
[assembly: TypeForwardedTo(typeof(MulticastDelegate))]
[assembly: TypeForwardedTo(typeof(MulticastNotSupportedException))]
[assembly: TypeForwardedTo(typeof(AuthenticationManager))]
[assembly: TypeForwardedTo(typeof(AuthenticationSchemes))]
[assembly: TypeForwardedTo(typeof(AuthenticationSchemeSelector))]
[assembly: TypeForwardedTo(typeof(Authorization))]
[assembly: TypeForwardedTo(typeof(BindIPEndPoint))]
[assembly: TypeForwardedTo(typeof(HttpCacheAgeControl))]
[assembly: TypeForwardedTo(typeof(HttpRequestCacheLevel))]
[assembly: TypeForwardedTo(typeof(HttpRequestCachePolicy))]
[assembly: TypeForwardedTo(typeof(RequestCacheLevel))]
[assembly: TypeForwardedTo(typeof(RequestCachePolicy))]
[assembly: TypeForwardedTo(typeof(Cookie))]
[assembly: TypeForwardedTo(typeof(CookieCollection))]
[assembly: TypeForwardedTo(typeof(CookieContainer))]
[assembly: TypeForwardedTo(typeof(CookieException))]
[assembly: TypeForwardedTo(typeof(CredentialCache))]
[assembly: TypeForwardedTo(typeof(DecompressionMethods))]
[assembly: TypeForwardedTo(typeof(Dns))]
[assembly: TypeForwardedTo(typeof(DnsEndPoint))]
[assembly: TypeForwardedTo(typeof(DownloadDataCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(DownloadDataCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(DownloadProgressChangedEventArgs))]
[assembly: TypeForwardedTo(typeof(DownloadProgressChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(DownloadStringCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(DownloadStringCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(EndPoint))]
[assembly: TypeForwardedTo(typeof(FileWebRequest))]
[assembly: TypeForwardedTo(typeof(FileWebResponse))]
[assembly: TypeForwardedTo(typeof(FtpStatusCode))]
[assembly: TypeForwardedTo(typeof(FtpWebRequest))]
[assembly: TypeForwardedTo(typeof(FtpWebResponse))]
[assembly: TypeForwardedTo(typeof(GlobalProxySelection))]
[assembly: TypeForwardedTo(typeof(ByteArrayContent))]
[assembly: TypeForwardedTo(typeof(ClientCertificateOption))]
[assembly: TypeForwardedTo(typeof(DelegatingHandler))]
[assembly: TypeForwardedTo(typeof(FormUrlEncodedContent))]
[assembly: TypeForwardedTo(typeof(AuthenticationHeaderValue))]
[assembly: TypeForwardedTo(typeof(CacheControlHeaderValue))]
[assembly: TypeForwardedTo(typeof(ContentDispositionHeaderValue))]
[assembly: TypeForwardedTo(typeof(ContentRangeHeaderValue))]
[assembly: TypeForwardedTo(typeof(EntityTagHeaderValue))]
[assembly: TypeForwardedTo(typeof(HttpContentHeaders))]
[assembly: TypeForwardedTo(typeof(HttpHeaders))]
[assembly: TypeForwardedTo(typeof(HttpHeaderValueCollection<>))]
[assembly: TypeForwardedTo(typeof(HttpRequestHeaders))]
[assembly: TypeForwardedTo(typeof(HttpResponseHeaders))]
[assembly: TypeForwardedTo(typeof(MediaTypeHeaderValue))]
[assembly: TypeForwardedTo(typeof(MediaTypeWithQualityHeaderValue))]
[assembly: TypeForwardedTo(typeof(NameValueHeaderValue))]
[assembly: TypeForwardedTo(typeof(NameValueWithParametersHeaderValue))]
[assembly: TypeForwardedTo(typeof(ProductHeaderValue))]
[assembly: TypeForwardedTo(typeof(ProductInfoHeaderValue))]
[assembly: TypeForwardedTo(typeof(RangeConditionHeaderValue))]
[assembly: TypeForwardedTo(typeof(RangeHeaderValue))]
[assembly: TypeForwardedTo(typeof(RangeItemHeaderValue))]
[assembly: TypeForwardedTo(typeof(RetryConditionHeaderValue))]
[assembly: TypeForwardedTo(typeof(StringWithQualityHeaderValue))]
[assembly: TypeForwardedTo(typeof(TransferCodingHeaderValue))]
[assembly: TypeForwardedTo(typeof(TransferCodingWithQualityHeaderValue))]
[assembly: TypeForwardedTo(typeof(ViaHeaderValue))]
[assembly: TypeForwardedTo(typeof(WarningHeaderValue))]
[assembly: TypeForwardedTo(typeof(HttpClient))]
[assembly: TypeForwardedTo(typeof(HttpClientHandler))]
[assembly: TypeForwardedTo(typeof(HttpCompletionOption))]
[assembly: TypeForwardedTo(typeof(HttpContent))]
[assembly: TypeForwardedTo(typeof(HttpMessageHandler))]
[assembly: TypeForwardedTo(typeof(HttpMessageInvoker))]
[assembly: TypeForwardedTo(typeof(HttpMethod))]
[assembly: TypeForwardedTo(typeof(HttpRequestException))]
[assembly: TypeForwardedTo(typeof(HttpRequestMessage))]
[assembly: TypeForwardedTo(typeof(HttpResponseMessage))]
[assembly: TypeForwardedTo(typeof(MessageProcessingHandler))]
[assembly: TypeForwardedTo(typeof(MultipartContent))]
[assembly: TypeForwardedTo(typeof(MultipartFormDataContent))]
[assembly: TypeForwardedTo(typeof(ReadOnlyMemoryContent))]
[assembly: TypeForwardedTo(typeof(StreamContent))]
[assembly: TypeForwardedTo(typeof(StringContent))]
[assembly: TypeForwardedTo(typeof(HttpContinueDelegate))]
[assembly: TypeForwardedTo(typeof(HttpListener))]
[assembly: TypeForwardedTo(typeof(HttpListenerBasicIdentity))]
[assembly: TypeForwardedTo(typeof(HttpListenerContext))]
[assembly: TypeForwardedTo(typeof(HttpListenerException))]
[assembly: TypeForwardedTo(typeof(HttpListenerPrefixCollection))]
[assembly: TypeForwardedTo(typeof(HttpListenerRequest))]
[assembly: TypeForwardedTo(typeof(HttpListenerResponse))]
[assembly: TypeForwardedTo(typeof(HttpListenerTimeoutManager))]
[assembly: TypeForwardedTo(typeof(HttpRequestHeader))]
[assembly: TypeForwardedTo(typeof(HttpResponseHeader))]
[assembly: TypeForwardedTo(typeof(HttpStatusCode))]
[assembly: TypeForwardedTo(typeof(HttpVersion))]
[assembly: TypeForwardedTo(typeof(HttpWebRequest))]
[assembly: TypeForwardedTo(typeof(HttpWebResponse))]
[assembly: TypeForwardedTo(typeof(IAuthenticationModule))]
[assembly: TypeForwardedTo(typeof(ICredentialPolicy))]
[assembly: TypeForwardedTo(typeof(ICredentials))]
[assembly: TypeForwardedTo(typeof(ICredentialsByHost))]
[assembly: TypeForwardedTo(typeof(IPAddress))]
[assembly: TypeForwardedTo(typeof(IPEndPoint))]
[assembly: TypeForwardedTo(typeof(IPHostEntry))]
[assembly: TypeForwardedTo(typeof(IWebProxy))]
[assembly: TypeForwardedTo(typeof(IWebProxyScript))]
[assembly: TypeForwardedTo(typeof(IWebRequestCreate))]
[assembly: TypeForwardedTo(typeof(AlternateView))]
[assembly: TypeForwardedTo(typeof(AlternateViewCollection))]
[assembly: TypeForwardedTo(typeof(Attachment))]
[assembly: TypeForwardedTo(typeof(AttachmentBase))]
[assembly: TypeForwardedTo(typeof(AttachmentCollection))]
[assembly: TypeForwardedTo(typeof(DeliveryNotificationOptions))]
[assembly: TypeForwardedTo(typeof(LinkedResource))]
[assembly: TypeForwardedTo(typeof(LinkedResourceCollection))]
[assembly: TypeForwardedTo(typeof(MailAddress))]
[assembly: TypeForwardedTo(typeof(MailAddressCollection))]
[assembly: TypeForwardedTo(typeof(MailMessage))]
[assembly: TypeForwardedTo(typeof(MailPriority))]
[assembly: TypeForwardedTo(typeof(SendCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(SmtpClient))]
[assembly: TypeForwardedTo(typeof(SmtpDeliveryFormat))]
[assembly: TypeForwardedTo(typeof(SmtpDeliveryMethod))]
[assembly: TypeForwardedTo(typeof(SmtpException))]
[assembly: TypeForwardedTo(typeof(SmtpFailedRecipientException))]
[assembly: TypeForwardedTo(typeof(SmtpFailedRecipientsException))]
[assembly: TypeForwardedTo(typeof(SmtpStatusCode))]
[assembly: TypeForwardedTo(typeof(ContentDisposition))]
[assembly: TypeForwardedTo(typeof(ContentType))]
[assembly: TypeForwardedTo(typeof(DispositionTypeNames))]
[assembly: TypeForwardedTo(typeof(MediaTypeNames))]
[assembly: TypeForwardedTo(typeof(TransferEncoding))]
[assembly: TypeForwardedTo(typeof(NetworkCredential))]
[assembly: TypeForwardedTo(typeof(DuplicateAddressDetectionState))]
[assembly: TypeForwardedTo(typeof(GatewayIPAddressInformation))]
[assembly: TypeForwardedTo(typeof(GatewayIPAddressInformationCollection))]
[assembly: TypeForwardedTo(typeof(IcmpV4Statistics))]
[assembly: TypeForwardedTo(typeof(IcmpV6Statistics))]
[assembly: TypeForwardedTo(typeof(IPAddressCollection))]
[assembly: TypeForwardedTo(typeof(IPAddressInformation))]
[assembly: TypeForwardedTo(typeof(IPAddressInformationCollection))]
[assembly: TypeForwardedTo(typeof(IPGlobalProperties))]
[assembly: TypeForwardedTo(typeof(IPGlobalStatistics))]
[assembly: TypeForwardedTo(typeof(IPInterfaceProperties))]
[assembly: TypeForwardedTo(typeof(IPInterfaceStatistics))]
[assembly: TypeForwardedTo(typeof(IPStatus))]
[assembly: TypeForwardedTo(typeof(IPv4InterfaceProperties))]
[assembly: TypeForwardedTo(typeof(IPv4InterfaceStatistics))]
[assembly: TypeForwardedTo(typeof(IPv6InterfaceProperties))]
[assembly: TypeForwardedTo(typeof(MulticastIPAddressInformation))]
[assembly: TypeForwardedTo(typeof(MulticastIPAddressInformationCollection))]
[assembly: TypeForwardedTo(typeof(NetBiosNodeType))]
[assembly: TypeForwardedTo(typeof(NetworkAddressChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(NetworkAvailabilityChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(NetworkAvailabilityEventArgs))]
[assembly: TypeForwardedTo(typeof(NetworkChange))]
[assembly: TypeForwardedTo(typeof(NetworkInformationException))]
[assembly: TypeForwardedTo(typeof(NetworkInterface))]
[assembly: TypeForwardedTo(typeof(NetworkInterfaceComponent))]
[assembly: TypeForwardedTo(typeof(NetworkInterfaceType))]
[assembly: TypeForwardedTo(typeof(OperationalStatus))]
[assembly: TypeForwardedTo(typeof(PhysicalAddress))]
[assembly: TypeForwardedTo(typeof(Ping))]
[assembly: TypeForwardedTo(typeof(PingCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(PingCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(PingException))]
[assembly: TypeForwardedTo(typeof(PingOptions))]
[assembly: TypeForwardedTo(typeof(PingReply))]
[assembly: TypeForwardedTo(typeof(PrefixOrigin))]
[assembly: TypeForwardedTo(typeof(ScopeLevel))]
[assembly: TypeForwardedTo(typeof(SuffixOrigin))]
[assembly: TypeForwardedTo(typeof(TcpConnectionInformation))]
[assembly: TypeForwardedTo(typeof(TcpState))]
[assembly: TypeForwardedTo(typeof(TcpStatistics))]
[assembly: TypeForwardedTo(typeof(UdpStatistics))]
[assembly: TypeForwardedTo(typeof(UnicastIPAddressInformation))]
[assembly: TypeForwardedTo(typeof(UnicastIPAddressInformationCollection))]
[assembly: TypeForwardedTo(typeof(OpenReadCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(OpenReadCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(OpenWriteCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(OpenWriteCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(ProtocolViolationException))]
[assembly: TypeForwardedTo(typeof(AuthenticatedStream))]
[assembly: TypeForwardedTo(typeof(AuthenticationLevel))]
[assembly: TypeForwardedTo(typeof(EncryptionPolicy))]
[assembly: TypeForwardedTo(typeof(LocalCertificateSelectionCallback))]
[assembly: TypeForwardedTo(typeof(NegotiateStream))]
[assembly: TypeForwardedTo(typeof(ProtectionLevel))]
[assembly: TypeForwardedTo(typeof(RemoteCertificateValidationCallback))]
[assembly: TypeForwardedTo(typeof(ServerCertificateSelectionCallback))]
[assembly: TypeForwardedTo(typeof(SslApplicationProtocol))]
[assembly: TypeForwardedTo(typeof(SslClientAuthenticationOptions))]
[assembly: TypeForwardedTo(typeof(SslPolicyErrors))]
[assembly: TypeForwardedTo(typeof(SslServerAuthenticationOptions))]
[assembly: TypeForwardedTo(typeof(SslStream))]
[assembly: TypeForwardedTo(typeof(SecurityProtocolType))]
[assembly: TypeForwardedTo(typeof(ServicePoint))]
[assembly: TypeForwardedTo(typeof(ServicePointManager))]
[assembly: TypeForwardedTo(typeof(SocketAddress))]
[assembly: TypeForwardedTo(typeof(AddressFamily))]
[assembly: TypeForwardedTo(typeof(IOControlCode))]
[assembly: TypeForwardedTo(typeof(IPPacketInformation))]
[assembly: TypeForwardedTo(typeof(IPProtectionLevel))]
[assembly: TypeForwardedTo(typeof(IPv6MulticastOption))]
[assembly: TypeForwardedTo(typeof(LingerOption))]
[assembly: TypeForwardedTo(typeof(MulticastOption))]
[assembly: TypeForwardedTo(typeof(NetworkStream))]
[assembly: TypeForwardedTo(typeof(ProtocolFamily))]
[assembly: TypeForwardedTo(typeof(ProtocolType))]
[assembly: TypeForwardedTo(typeof(SelectMode))]
[assembly: TypeForwardedTo(typeof(SendPacketsElement))]
[assembly: TypeForwardedTo(typeof(Socket))]
[assembly: TypeForwardedTo(typeof(SocketAsyncEventArgs))]
[assembly: TypeForwardedTo(typeof(SocketAsyncOperation))]
[assembly: TypeForwardedTo(typeof(SocketError))]
[assembly: TypeForwardedTo(typeof(SocketException))]
[assembly: TypeForwardedTo(typeof(SocketFlags))]
[assembly: TypeForwardedTo(typeof(SocketInformation))]
[assembly: TypeForwardedTo(typeof(SocketInformationOptions))]
[assembly: TypeForwardedTo(typeof(SocketOptionLevel))]
[assembly: TypeForwardedTo(typeof(SocketOptionName))]
[assembly: TypeForwardedTo(typeof(SocketReceiveFromResult))]
[assembly: TypeForwardedTo(typeof(SocketReceiveMessageFromResult))]
[assembly: TypeForwardedTo(typeof(SocketShutdown))]
[assembly: TypeForwardedTo(typeof(SocketTaskExtensions))]
[assembly: TypeForwardedTo(typeof(SocketType))]
[assembly: TypeForwardedTo(typeof(TcpClient))]
[assembly: TypeForwardedTo(typeof(TcpListener))]
[assembly: TypeForwardedTo(typeof(TransmitFileOptions))]
[assembly: TypeForwardedTo(typeof(UdpClient))]
[assembly: TypeForwardedTo(typeof(UdpReceiveResult))]
[assembly: TypeForwardedTo(typeof(UnixDomainSocketEndPoint))]
[assembly: TypeForwardedTo(typeof(TransportContext))]
[assembly: TypeForwardedTo(typeof(UploadDataCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(UploadDataCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(UploadFileCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(UploadFileCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(UploadProgressChangedEventArgs))]
[assembly: TypeForwardedTo(typeof(UploadProgressChangedEventHandler))]
[assembly: TypeForwardedTo(typeof(UploadStringCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(UploadStringCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(UploadValuesCompletedEventArgs))]
[assembly: TypeForwardedTo(typeof(UploadValuesCompletedEventHandler))]
[assembly: TypeForwardedTo(typeof(WebClient))]
[assembly: TypeForwardedTo(typeof(WebException))]
[assembly: TypeForwardedTo(typeof(WebExceptionStatus))]
[assembly: TypeForwardedTo(typeof(WebHeaderCollection))]
[assembly: TypeForwardedTo(typeof(WebProxy))]
[assembly: TypeForwardedTo(typeof(WebRequest))]
[assembly: TypeForwardedTo(typeof(WebRequestMethods))]
[assembly: TypeForwardedTo(typeof(WebResponse))]
[assembly: TypeForwardedTo(typeof(ClientWebSocket))]
[assembly: TypeForwardedTo(typeof(ClientWebSocketOptions))]
[assembly: TypeForwardedTo(typeof(HttpListenerWebSocketContext))]
[assembly: TypeForwardedTo(typeof(ValueWebSocketReceiveResult))]
[assembly: TypeForwardedTo(typeof(WebSocket))]
[assembly: TypeForwardedTo(typeof(WebSocketCloseStatus))]
[assembly: TypeForwardedTo(typeof(WebSocketContext))]
[assembly: TypeForwardedTo(typeof(WebSocketError))]
[assembly: TypeForwardedTo(typeof(WebSocketException))]
[assembly: TypeForwardedTo(typeof(WebSocketMessageType))]
[assembly: TypeForwardedTo(typeof(WebSocketReceiveResult))]
[assembly: TypeForwardedTo(typeof(WebSocketState))]
[assembly: TypeForwardedTo(typeof(WebUtility))]
[assembly: TypeForwardedTo(typeof(NetPipeStyleUriParser))]
[assembly: TypeForwardedTo(typeof(NetTcpStyleUriParser))]
[assembly: TypeForwardedTo(typeof(NewsStyleUriParser))]
[assembly: TypeForwardedTo(typeof(NonSerializedAttribute))]
[assembly: TypeForwardedTo(typeof(NotFiniteNumberException))]
[assembly: TypeForwardedTo(typeof(NotImplementedException))]
[assembly: TypeForwardedTo(typeof(NotSupportedException))]
[assembly: TypeForwardedTo(typeof(Nullable))]
[assembly: TypeForwardedTo(typeof(Nullable<>))]
[assembly: TypeForwardedTo(typeof(NullReferenceException))]
[assembly: TypeForwardedTo(typeof(BigInteger))]
[assembly: TypeForwardedTo(typeof(Complex))]
[assembly: TypeForwardedTo(typeof(Matrix3x2))]
[assembly: TypeForwardedTo(typeof(Matrix4x4))]
[assembly: TypeForwardedTo(typeof(Plane))]
[assembly: TypeForwardedTo(typeof(Quaternion))]
[assembly: TypeForwardedTo(typeof(Vector))]
[assembly: TypeForwardedTo(typeof(Vector<>))]
[assembly: TypeForwardedTo(typeof(Vector2))]
[assembly: TypeForwardedTo(typeof(Vector3))]
[assembly: TypeForwardedTo(typeof(Vector4))]
[assembly: TypeForwardedTo(typeof(object))]
[assembly: TypeForwardedTo(typeof(ObjectDisposedException))]
[assembly: TypeForwardedTo(typeof(ObsoleteAttribute))]
[assembly: TypeForwardedTo(typeof(OperatingSystem))]
[assembly: TypeForwardedTo(typeof(OperationCanceledException))]
[assembly: TypeForwardedTo(typeof(OutOfMemoryException))]
[assembly: TypeForwardedTo(typeof(OverflowException))]
[assembly: TypeForwardedTo(typeof(ParamArrayAttribute))]
[assembly: TypeForwardedTo(typeof(PlatformID))]
[assembly: TypeForwardedTo(typeof(PlatformNotSupportedException))]
[assembly: TypeForwardedTo(typeof(Predicate<>))]
[assembly: TypeForwardedTo(typeof(Progress<>))]
[assembly: TypeForwardedTo(typeof(Random))]
[assembly: TypeForwardedTo(typeof(Range))]
[assembly: TypeForwardedTo(typeof(RankException))]
[assembly: TypeForwardedTo(typeof(ReadOnlyMemory<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySpan<>))]
[assembly: TypeForwardedTo(typeof(AmbiguousMatchException))]
[assembly: TypeForwardedTo(typeof(Assembly))]
[assembly: TypeForwardedTo(typeof(AssemblyAlgorithmIdAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyCompanyAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyConfigurationAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyContentType))]
[assembly: TypeForwardedTo(typeof(AssemblyCopyrightAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyCultureAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyDefaultAliasAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyDelaySignAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyDescriptionAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyFileVersionAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyFlagsAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyInformationalVersionAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyKeyFileAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyKeyNameAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyMetadataAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyName))]
[assembly: TypeForwardedTo(typeof(AssemblyNameFlags))]
[assembly: TypeForwardedTo(typeof(AssemblyNameProxy))]
[assembly: TypeForwardedTo(typeof(AssemblyProductAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblySignatureKeyAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyTitleAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyTrademarkAttribute))]
[assembly: TypeForwardedTo(typeof(AssemblyVersionAttribute))]
[assembly: TypeForwardedTo(typeof(Binder))]
[assembly: TypeForwardedTo(typeof(BindingFlags))]
[assembly: TypeForwardedTo(typeof(CallingConventions))]
[assembly: TypeForwardedTo(typeof(ConstructorInfo))]
[assembly: TypeForwardedTo(typeof(CustomAttributeData))]
[assembly: TypeForwardedTo(typeof(CustomAttributeExtensions))]
[assembly: TypeForwardedTo(typeof(CustomAttributeFormatException))]
[assembly: TypeForwardedTo(typeof(CustomAttributeNamedArgument))]
[assembly: TypeForwardedTo(typeof(CustomAttributeTypedArgument))]
[assembly: TypeForwardedTo(typeof(DefaultMemberAttribute))]
[assembly: TypeForwardedTo(typeof(DispatchProxy))]
[assembly: TypeForwardedTo(typeof(AssemblyBuilder))]
[assembly: TypeForwardedTo(typeof(AssemblyBuilderAccess))]
[assembly: TypeForwardedTo(typeof(ConstructorBuilder))]
[assembly: TypeForwardedTo(typeof(CustomAttributeBuilder))]
[assembly: TypeForwardedTo(typeof(DynamicILInfo))]
[assembly: TypeForwardedTo(typeof(DynamicMethod))]
[assembly: TypeForwardedTo(typeof(EnumBuilder))]
[assembly: TypeForwardedTo(typeof(EventBuilder))]
[assembly: TypeForwardedTo(typeof(EventToken))]
[assembly: TypeForwardedTo(typeof(ExceptionHandler))]
[assembly: TypeForwardedTo(typeof(FieldBuilder))]
[assembly: TypeForwardedTo(typeof(FieldToken))]
[assembly: TypeForwardedTo(typeof(FlowControl))]
[assembly: TypeForwardedTo(typeof(GenericTypeParameterBuilder))]
[assembly: TypeForwardedTo(typeof(ILGenerator))]
[assembly: TypeForwardedTo(typeof(Label))]
[assembly: TypeForwardedTo(typeof(LocalBuilder))]
[assembly: TypeForwardedTo(typeof(MethodBuilder))]
[assembly: TypeForwardedTo(typeof(MethodToken))]
[assembly: TypeForwardedTo(typeof(ModuleBuilder))]
[assembly: TypeForwardedTo(typeof(OpCode))]
[assembly: TypeForwardedTo(typeof(OpCodes))]
[assembly: TypeForwardedTo(typeof(OpCodeType))]
[assembly: TypeForwardedTo(typeof(OperandType))]
[assembly: TypeForwardedTo(typeof(PackingSize))]
[assembly: TypeForwardedTo(typeof(ParameterBuilder))]
[assembly: TypeForwardedTo(typeof(ParameterToken))]
[assembly: TypeForwardedTo(typeof(PropertyBuilder))]
[assembly: TypeForwardedTo(typeof(PropertyToken))]
[assembly: TypeForwardedTo(typeof(SignatureHelper))]
[assembly: TypeForwardedTo(typeof(SignatureToken))]
[assembly: TypeForwardedTo(typeof(StackBehaviour))]
[assembly: TypeForwardedTo(typeof(StringToken))]
[assembly: TypeForwardedTo(typeof(TypeBuilder))]
[assembly: TypeForwardedTo(typeof(TypeToken))]
[assembly: TypeForwardedTo(typeof(EventAttributes))]
[assembly: TypeForwardedTo(typeof(EventInfo))]
[assembly: TypeForwardedTo(typeof(ExceptionHandlingClause))]
[assembly: TypeForwardedTo(typeof(ExceptionHandlingClauseOptions))]
[assembly: TypeForwardedTo(typeof(FieldAttributes))]
[assembly: TypeForwardedTo(typeof(FieldInfo))]
[assembly: TypeForwardedTo(typeof(GenericParameterAttributes))]
[assembly: TypeForwardedTo(typeof(ICustomAttributeProvider))]
[assembly: TypeForwardedTo(typeof(ImageFileMachine))]
[assembly: TypeForwardedTo(typeof(InterfaceMapping))]
[assembly: TypeForwardedTo(typeof(IntrospectionExtensions))]
[assembly: TypeForwardedTo(typeof(InvalidFilterCriteriaException))]
[assembly: TypeForwardedTo(typeof(IReflect))]
[assembly: TypeForwardedTo(typeof(IReflectableType))]
[assembly: TypeForwardedTo(typeof(LocalVariableInfo))]
[assembly: TypeForwardedTo(typeof(ManifestResourceInfo))]
[assembly: TypeForwardedTo(typeof(MemberFilter))]
[assembly: TypeForwardedTo(typeof(MemberInfo))]
[assembly: TypeForwardedTo(typeof(MemberTypes))]
[assembly: TypeForwardedTo(typeof(MethodAttributes))]
[assembly: TypeForwardedTo(typeof(MethodBase))]
[assembly: TypeForwardedTo(typeof(MethodBody))]
[assembly: TypeForwardedTo(typeof(MethodImplAttributes))]
[assembly: TypeForwardedTo(typeof(MethodInfo))]
[assembly: TypeForwardedTo(typeof(Missing))]
[assembly: TypeForwardedTo(typeof(Module))]
[assembly: TypeForwardedTo(typeof(ModuleResolveEventHandler))]
[assembly: TypeForwardedTo(typeof(ObfuscateAssemblyAttribute))]
[assembly: TypeForwardedTo(typeof(ObfuscationAttribute))]
[assembly: TypeForwardedTo(typeof(ParameterAttributes))]
[assembly: TypeForwardedTo(typeof(ParameterInfo))]
[assembly: TypeForwardedTo(typeof(ParameterModifier))]
[assembly: TypeForwardedTo(typeof(Pointer))]
[assembly: TypeForwardedTo(typeof(PortableExecutableKinds))]
[assembly: TypeForwardedTo(typeof(ProcessorArchitecture))]
[assembly: TypeForwardedTo(typeof(PropertyAttributes))]
[assembly: TypeForwardedTo(typeof(PropertyInfo))]
[assembly: TypeForwardedTo(typeof(ReflectionContext))]
[assembly: TypeForwardedTo(typeof(ReflectionTypeLoadException))]
[assembly: TypeForwardedTo(typeof(ResourceAttributes))]
[assembly: TypeForwardedTo(typeof(ResourceLocation))]
[assembly: TypeForwardedTo(typeof(RuntimeReflectionExtensions))]
[assembly: TypeForwardedTo(typeof(StrongNameKeyPair))]
[assembly: TypeForwardedTo(typeof(TargetException))]
[assembly: TypeForwardedTo(typeof(TargetInvocationException))]
[assembly: TypeForwardedTo(typeof(TargetParameterCountException))]
[assembly: TypeForwardedTo(typeof(TypeAttributes))]
[assembly: TypeForwardedTo(typeof(TypeDelegator))]
[assembly: TypeForwardedTo(typeof(TypeFilter))]
[assembly: TypeForwardedTo(typeof(TypeInfo))]
[assembly: TypeForwardedTo(typeof(ResolveEventArgs))]
[assembly: TypeForwardedTo(typeof(ResolveEventHandler))]
[assembly: TypeForwardedTo(typeof(IResourceReader))]
[assembly: TypeForwardedTo(typeof(IResourceWriter))]
[assembly: TypeForwardedTo(typeof(MissingManifestResourceException))]
[assembly: TypeForwardedTo(typeof(MissingSatelliteAssemblyException))]
[assembly: TypeForwardedTo(typeof(NeutralResourcesLanguageAttribute))]
[assembly: TypeForwardedTo(typeof(ResourceManager))]
[assembly: TypeForwardedTo(typeof(ResourceReader))]
[assembly: TypeForwardedTo(typeof(ResourceSet))]
[assembly: TypeForwardedTo(typeof(ResourceWriter))]
[assembly: TypeForwardedTo(typeof(SatelliteContractVersionAttribute))]
[assembly: TypeForwardedTo(typeof(UltimateResourceFallbackLocation))]
[assembly: TypeForwardedTo(typeof(AmbiguousImplementationException))]
[assembly: TypeForwardedTo(typeof(AssemblyTargetedPatchBandAttribute))]
[assembly: TypeForwardedTo(typeof(AccessedThroughPropertyAttribute))]
[assembly: TypeForwardedTo(typeof(AsyncIteratorMethodBuilder))]
[assembly: TypeForwardedTo(typeof(AsyncIteratorStateMachineAttribute))]
[assembly: TypeForwardedTo(typeof(AsyncMethodBuilderAttribute))]
[assembly: TypeForwardedTo(typeof(AsyncStateMachineAttribute))]
[assembly: TypeForwardedTo(typeof(AsyncTaskMethodBuilder))]
[assembly: TypeForwardedTo(typeof(AsyncTaskMethodBuilder<>))]
[assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder))]
[assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder<>))]
[assembly: TypeForwardedTo(typeof(AsyncVoidMethodBuilder))]
[assembly: TypeForwardedTo(typeof(CallConvCdecl))]
[assembly: TypeForwardedTo(typeof(CallConvFastcall))]
[assembly: TypeForwardedTo(typeof(CallConvStdcall))]
[assembly: TypeForwardedTo(typeof(CallConvThiscall))]
[assembly: TypeForwardedTo(typeof(CallerFilePathAttribute))]
[assembly: TypeForwardedTo(typeof(CallerLineNumberAttribute))]
[assembly: TypeForwardedTo(typeof(CallerMemberNameAttribute))]
[assembly: TypeForwardedTo(typeof(CallSite))]
[assembly: TypeForwardedTo(typeof(CallSite<>))]
[assembly: TypeForwardedTo(typeof(CallSiteBinder))]
[assembly: TypeForwardedTo(typeof(CallSiteHelpers))]
[assembly: TypeForwardedTo(typeof(CompilationRelaxations))]
[assembly: TypeForwardedTo(typeof(CompilationRelaxationsAttribute))]
[assembly: TypeForwardedTo(typeof(CompilerGeneratedAttribute))]
[assembly: TypeForwardedTo(typeof(CompilerGlobalScopeAttribute))]
[assembly: TypeForwardedTo(typeof(CompilerMarshalOverride))]
[assembly: TypeForwardedTo(typeof(ConditionalWeakTable<, >))]
[assembly: TypeForwardedTo(typeof(ConfiguredAsyncDisposable))]
[assembly: TypeForwardedTo(typeof(ConfiguredCancelableAsyncEnumerable<>))]
[assembly: TypeForwardedTo(typeof(ConfiguredTaskAwaitable))]
[assembly: TypeForwardedTo(typeof(ConfiguredTaskAwaitable<>))]
[assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable))]
[assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable<>))]
[assembly: TypeForwardedTo(typeof(ContractHelper))]
[assembly: TypeForwardedTo(typeof(CustomConstantAttribute))]
[assembly: TypeForwardedTo(typeof(DateTimeConstantAttribute))]
[assembly: TypeForwardedTo(typeof(DebugInfoGenerator))]
[assembly: TypeForwardedTo(typeof(DecimalConstantAttribute))]
[assembly: TypeForwardedTo(typeof(DefaultDependencyAttribute))]
[assembly: TypeForwardedTo(typeof(DependencyAttribute))]
[assembly: TypeForwardedTo(typeof(DisablePrivateReflectionAttribute))]
[assembly: TypeForwardedTo(typeof(DiscardableAttribute))]
[assembly: TypeForwardedTo(typeof(DynamicAttribute))]
[assembly: TypeForwardedTo(typeof(EnumeratorCancellationAttribute))]
[assembly: TypeForwardedTo(typeof(ExtensionAttribute))]
[assembly: TypeForwardedTo(typeof(FixedAddressValueTypeAttribute))]
[assembly: TypeForwardedTo(typeof(FixedBufferAttribute))]
[assembly: TypeForwardedTo(typeof(FormattableStringFactory))]
[assembly: TypeForwardedTo(typeof(HasCopySemanticsAttribute))]
[assembly: TypeForwardedTo(typeof(IAsyncStateMachine))]
[assembly: TypeForwardedTo(typeof(ICriticalNotifyCompletion))]
[assembly: TypeForwardedTo(typeof(IndexerNameAttribute))]
[assembly: TypeForwardedTo(typeof(INotifyCompletion))]
[assembly: TypeForwardedTo(typeof(InternalsVisibleToAttribute))]
[assembly: TypeForwardedTo(typeof(IRuntimeVariables))]
[assembly: TypeForwardedTo(typeof(IsBoxed))]
[assembly: TypeForwardedTo(typeof(IsByRefLikeAttribute))]
[assembly: TypeForwardedTo(typeof(IsByValue))]
[assembly: TypeForwardedTo(typeof(IsConst))]
[assembly: TypeForwardedTo(typeof(IsCopyConstructed))]
[assembly: TypeForwardedTo(typeof(IsExplicitlyDereferenced))]
[assembly: TypeForwardedTo(typeof(IsImplicitlyDereferenced))]
[assembly: TypeForwardedTo(typeof(IsJitIntrinsic))]
[assembly: TypeForwardedTo(typeof(IsLong))]
[assembly: TypeForwardedTo(typeof(IsPinned))]
[assembly: TypeForwardedTo(typeof(IsReadOnlyAttribute))]
[assembly: TypeForwardedTo(typeof(IsSignUnspecifiedByte))]
[assembly: TypeForwardedTo(typeof(IStrongBox))]
[assembly: TypeForwardedTo(typeof(IsUdtReturn))]
[assembly: TypeForwardedTo(typeof(IsVolatile))]
[assembly: TypeForwardedTo(typeof(IteratorStateMachineAttribute))]
[assembly: TypeForwardedTo(typeof(ITuple))]
[assembly: TypeForwardedTo(typeof(IUnknownConstantAttribute))]
[assembly: TypeForwardedTo(typeof(LoadHint))]
[assembly: TypeForwardedTo(typeof(MethodCodeType))]
[assembly: TypeForwardedTo(typeof(MethodImplAttribute))]
[assembly: TypeForwardedTo(typeof(MethodImplOptions))]
[assembly: TypeForwardedTo(typeof(NativeCppClassAttribute))]
[assembly: TypeForwardedTo(typeof(ReadOnlyCollectionBuilder<>))]
[assembly: TypeForwardedTo(typeof(ReferenceAssemblyAttribute))]
[assembly: TypeForwardedTo(typeof(RequiredAttributeAttribute))]
[assembly: TypeForwardedTo(typeof(RuleCache<>))]
[assembly: TypeForwardedTo(typeof(RuntimeCompatibilityAttribute))]
[assembly: TypeForwardedTo(typeof(RuntimeFeature))]
[assembly: TypeForwardedTo(typeof(RuntimeHelpers))]
[assembly: TypeForwardedTo(typeof(RuntimeWrappedException))]
[assembly: TypeForwardedTo(typeof(ScopelessEnumAttribute))]
[assembly: TypeForwardedTo(typeof(SpecialNameAttribute))]
[assembly: TypeForwardedTo(typeof(StateMachineAttribute))]
[assembly: TypeForwardedTo(typeof(StringFreezingAttribute))]
[assembly: TypeForwardedTo(typeof(StrongBox<>))]
[assembly: TypeForwardedTo(typeof(SuppressIldasmAttribute))]
[assembly: TypeForwardedTo(typeof(SwitchExpressionException))]
[assembly: TypeForwardedTo(typeof(TaskAwaiter))]
[assembly: TypeForwardedTo(typeof(TaskAwaiter<>))]
[assembly: TypeForwardedTo(typeof(TupleElementNamesAttribute))]
[assembly: TypeForwardedTo(typeof(TypeForwardedFromAttribute))]
[assembly: TypeForwardedTo(typeof(TypeForwardedToAttribute))]
[assembly: TypeForwardedTo(typeof(UnsafeValueTypeAttribute))]
[assembly: TypeForwardedTo(typeof(ValueTaskAwaiter))]
[assembly: TypeForwardedTo(typeof(ValueTaskAwaiter<>))]
[assembly: TypeForwardedTo(typeof(YieldAwaitable))]
[assembly: TypeForwardedTo(typeof(Cer))]
[assembly: TypeForwardedTo(typeof(Consistency))]
[assembly: TypeForwardedTo(typeof(CriticalFinalizerObject))]
[assembly: TypeForwardedTo(typeof(PrePrepareMethodAttribute))]
[assembly: TypeForwardedTo(typeof(ReliabilityContractAttribute))]
[assembly: TypeForwardedTo(typeof(ExceptionDispatchInfo))]
[assembly: TypeForwardedTo(typeof(FirstChanceExceptionEventArgs))]
[assembly: TypeForwardedTo(typeof(HandleProcessCorruptedStateExceptionsAttribute))]
[assembly: TypeForwardedTo(typeof(GCLargeObjectHeapCompactionMode))]
[assembly: TypeForwardedTo(typeof(GCLatencyMode))]
[assembly: TypeForwardedTo(typeof(GCSettings))]
[assembly: TypeForwardedTo(typeof(AllowReversePInvokeCallsAttribute))]
[assembly: TypeForwardedTo(typeof(Architecture))]
[assembly: TypeForwardedTo(typeof(ArrayWithOffset))]
[assembly: TypeForwardedTo(typeof(AutomationProxyAttribute))]
[assembly: TypeForwardedTo(typeof(BestFitMappingAttribute))]
[assembly: TypeForwardedTo(typeof(BStrWrapper))]
[assembly: TypeForwardedTo(typeof(CallingConvention))]
[assembly: TypeForwardedTo(typeof(CharSet))]
[assembly: TypeForwardedTo(typeof(ClassInterfaceAttribute))]
[assembly: TypeForwardedTo(typeof(ClassInterfaceType))]
[assembly: TypeForwardedTo(typeof(CoClassAttribute))]
[assembly: TypeForwardedTo(typeof(ComAliasNameAttribute))]
[assembly: TypeForwardedTo(typeof(ComAwareEventInfo))]
[assembly: TypeForwardedTo(typeof(ComCompatibleVersionAttribute))]
[assembly: TypeForwardedTo(typeof(ComConversionLossAttribute))]
[assembly: TypeForwardedTo(typeof(ComDefaultInterfaceAttribute))]
[assembly: TypeForwardedTo(typeof(ComEventInterfaceAttribute))]
[assembly: TypeForwardedTo(typeof(ComEventsHelper))]
[assembly: TypeForwardedTo(typeof(COMException))]
[assembly: TypeForwardedTo(typeof(ComImportAttribute))]
[assembly: TypeForwardedTo(typeof(ComInterfaceType))]
[assembly: TypeForwardedTo(typeof(ComMemberType))]
[assembly: TypeForwardedTo(typeof(ComRegisterFunctionAttribute))]
[assembly: TypeForwardedTo(typeof(ComSourceInterfacesAttribute))]
[assembly: TypeForwardedTo(typeof(ADVF))]
[assembly: TypeForwardedTo(typeof(BIND_OPTS))]
[assembly: TypeForwardedTo(typeof(BINDPTR))]
[assembly: TypeForwardedTo(typeof(CALLCONV))]
[assembly: TypeForwardedTo(typeof(CONNECTDATA))]
[assembly: TypeForwardedTo(typeof(DATADIR))]
[assembly: TypeForwardedTo(typeof(DESCKIND))]
[assembly: TypeForwardedTo(typeof(DISPPARAMS))]
[assembly: TypeForwardedTo(typeof(DVASPECT))]
[assembly: TypeForwardedTo(typeof(ELEMDESC))]
[assembly: TypeForwardedTo(typeof(EXCEPINFO))]
[assembly: TypeForwardedTo(typeof(FILETIME))]
[assembly: TypeForwardedTo(typeof(FORMATETC))]
[assembly: TypeForwardedTo(typeof(FUNCDESC))]
[assembly: TypeForwardedTo(typeof(FUNCFLAGS))]
[assembly: TypeForwardedTo(typeof(FUNCKIND))]
[assembly: TypeForwardedTo(typeof(IAdviseSink))]
[assembly: TypeForwardedTo(typeof(IBindCtx))]
[assembly: TypeForwardedTo(typeof(IConnectionPoint))]
[assembly: TypeForwardedTo(typeof(IConnectionPointContainer))]
[assembly: TypeForwardedTo(typeof(IDataObject))]
[assembly: TypeForwardedTo(typeof(IDLDESC))]
[assembly: TypeForwardedTo(typeof(IDLFLAG))]
[assembly: TypeForwardedTo(typeof(IEnumConnectionPoints))]
[assembly: TypeForwardedTo(typeof(IEnumConnections))]
[assembly: TypeForwardedTo(typeof(IEnumFORMATETC))]
[assembly: TypeForwardedTo(typeof(IEnumMoniker))]
[assembly: TypeForwardedTo(typeof(IEnumSTATDATA))]
[assembly: TypeForwardedTo(typeof(IEnumString))]
[assembly: TypeForwardedTo(typeof(IEnumVARIANT))]
[assembly: TypeForwardedTo(typeof(IMoniker))]
[assembly: TypeForwardedTo(typeof(IMPLTYPEFLAGS))]
[assembly: TypeForwardedTo(typeof(INVOKEKIND))]
[assembly: TypeForwardedTo(typeof(IPersistFile))]
[assembly: TypeForwardedTo(typeof(IRunningObjectTable))]
[assembly: TypeForwardedTo(typeof(IStream))]
[assembly: TypeForwardedTo(typeof(ITypeComp))]
[assembly: TypeForwardedTo(typeof(ITypeInfo))]
[assembly: TypeForwardedTo(typeof(ITypeInfo2))]
[assembly: TypeForwardedTo(typeof(ITypeLib))]
[assembly: TypeForwardedTo(typeof(ITypeLib2))]
[assembly: TypeForwardedTo(typeof(LIBFLAGS))]
[assembly: TypeForwardedTo(typeof(PARAMDESC))]
[assembly: TypeForwardedTo(typeof(PARAMFLAG))]
[assembly: TypeForwardedTo(typeof(STATDATA))]
[assembly: TypeForwardedTo(typeof(STATSTG))]
[assembly: TypeForwardedTo(typeof(STGMEDIUM))]
[assembly: TypeForwardedTo(typeof(SYSKIND))]
[assembly: TypeForwardedTo(typeof(TYMED))]
[assembly: TypeForwardedTo(typeof(TYPEATTR))]
[assembly: TypeForwardedTo(typeof(TYPEDESC))]
[assembly: TypeForwardedTo(typeof(TYPEFLAGS))]
[assembly: TypeForwardedTo(typeof(TYPEKIND))]
[assembly: TypeForwardedTo(typeof(TYPELIBATTR))]
[assembly: TypeForwardedTo(typeof(VARDESC))]
[assembly: TypeForwardedTo(typeof(VARFLAGS))]
[assembly: TypeForwardedTo(typeof(VARKIND))]
[assembly: TypeForwardedTo(typeof(ComUnregisterFunctionAttribute))]
[assembly: TypeForwardedTo(typeof(ComVisibleAttribute))]
[assembly: TypeForwardedTo(typeof(CriticalHandle))]
[assembly: TypeForwardedTo(typeof(CurrencyWrapper))]
[assembly: TypeForwardedTo(typeof(CustomQueryInterfaceMode))]
[assembly: TypeForwardedTo(typeof(CustomQueryInterfaceResult))]
[assembly: TypeForwardedTo(typeof(DefaultCharSetAttribute))]
[assembly: TypeForwardedTo(typeof(DefaultDllImportSearchPathsAttribute))]
[assembly: TypeForwardedTo(typeof(DefaultParameterValueAttribute))]
[assembly: TypeForwardedTo(typeof(DispatchWrapper))]
[assembly: TypeForwardedTo(typeof(DispIdAttribute))]
[assembly: TypeForwardedTo(typeof(DllImportAttribute))]
[assembly: TypeForwardedTo(typeof(DllImportSearchPath))]
[assembly: TypeForwardedTo(typeof(ErrorWrapper))]
[assembly: TypeForwardedTo(typeof(ExternalException))]
[assembly: TypeForwardedTo(typeof(FieldOffsetAttribute))]
[assembly: TypeForwardedTo(typeof(GCHandle))]
[assembly: TypeForwardedTo(typeof(GCHandleType))]
[assembly: TypeForwardedTo(typeof(GuidAttribute))]
[assembly: TypeForwardedTo(typeof(HandleCollector))]
[assembly: TypeForwardedTo(typeof(HandleRef))]
[assembly: TypeForwardedTo(typeof(ICustomAdapter))]
[assembly: TypeForwardedTo(typeof(ICustomFactory))]
[assembly: TypeForwardedTo(typeof(ICustomMarshaler))]
[assembly: TypeForwardedTo(typeof(ICustomQueryInterface))]
[assembly: TypeForwardedTo(typeof(ImportedFromTypeLibAttribute))]
[assembly: TypeForwardedTo(typeof(InAttribute))]
[assembly: TypeForwardedTo(typeof(InterfaceTypeAttribute))]
[assembly: TypeForwardedTo(typeof(InvalidComObjectException))]
[assembly: TypeForwardedTo(typeof(InvalidOleVariantTypeException))]
[assembly: TypeForwardedTo(typeof(LayoutKind))]
[assembly: TypeForwardedTo(typeof(LCIDConversionAttribute))]
[assembly: TypeForwardedTo(typeof(ManagedToNativeComInteropStubAttribute))]
[assembly: TypeForwardedTo(typeof(Marshal))]
[assembly: TypeForwardedTo(typeof(MarshalAsAttribute))]
[assembly: TypeForwardedTo(typeof(MarshalDirectiveException))]
[assembly: TypeForwardedTo(typeof(MemoryMarshal))]
[assembly: TypeForwardedTo(typeof(OptionalAttribute))]
[assembly: TypeForwardedTo(typeof(OSPlatform))]
[assembly: TypeForwardedTo(typeof(OutAttribute))]
[assembly: TypeForwardedTo(typeof(PreserveSigAttribute))]
[assembly: TypeForwardedTo(typeof(PrimaryInteropAssemblyAttribute))]
[assembly: TypeForwardedTo(typeof(ProgIdAttribute))]
[assembly: TypeForwardedTo(typeof(RuntimeEnvironment))]
[assembly: TypeForwardedTo(typeof(RuntimeInformation))]
[assembly: TypeForwardedTo(typeof(SafeArrayRankMismatchException))]
[assembly: TypeForwardedTo(typeof(SafeArrayTypeMismatchException))]
[assembly: TypeForwardedTo(typeof(SafeBuffer))]
[assembly: TypeForwardedTo(typeof(SafeHandle))]
[assembly: TypeForwardedTo(typeof(SEHException))]
[assembly: TypeForwardedTo(typeof(SequenceMarshal))]
[assembly: TypeForwardedTo(typeof(StructLayoutAttribute))]
[assembly: TypeForwardedTo(typeof(TypeIdentifierAttribute))]
[assembly: TypeForwardedTo(typeof(TypeLibFuncAttribute))]
[assembly: TypeForwardedTo(typeof(TypeLibFuncFlags))]
[assembly: TypeForwardedTo(typeof(TypeLibImportClassAttribute))]
[assembly: TypeForwardedTo(typeof(TypeLibTypeAttribute))]
[assembly: TypeForwardedTo(typeof(TypeLibTypeFlags))]
[assembly: TypeForwardedTo(typeof(TypeLibVarAttribute))]
[assembly: TypeForwardedTo(typeof(TypeLibVarFlags))]
[assembly: TypeForwardedTo(typeof(TypeLibVersionAttribute))]
[assembly: TypeForwardedTo(typeof(UnknownWrapper))]
[assembly: TypeForwardedTo(typeof(UnmanagedFunctionPointerAttribute))]
[assembly: TypeForwardedTo(typeof(UnmanagedType))]
[assembly: TypeForwardedTo(typeof(VarEnum))]
[assembly: TypeForwardedTo(typeof(VariantWrapper))]
[assembly: TypeForwardedTo(typeof(MemoryFailPoint))]
[assembly: TypeForwardedTo(typeof(CollectionDataContractAttribute))]
[assembly: TypeForwardedTo(typeof(ContractNamespaceAttribute))]
[assembly: TypeForwardedTo(typeof(DataContractAttribute))]
[assembly: TypeForwardedTo(typeof(DataContractResolver))]
[assembly: TypeForwardedTo(typeof(DataContractSerializer))]
[assembly: TypeForwardedTo(typeof(DataContractSerializerExtensions))]
[assembly: TypeForwardedTo(typeof(DataContractSerializerSettings))]
[assembly: TypeForwardedTo(typeof(DataMemberAttribute))]
[assembly: TypeForwardedTo(typeof(DateTimeFormat))]
[assembly: TypeForwardedTo(typeof(EmitTypeInformation))]
[assembly: TypeForwardedTo(typeof(EnumMemberAttribute))]
[assembly: TypeForwardedTo(typeof(ExportOptions))]
[assembly: TypeForwardedTo(typeof(ExtensionDataObject))]
[assembly: TypeForwardedTo(typeof(Formatter))]
[assembly: TypeForwardedTo(typeof(FormatterConverter))]
[assembly: TypeForwardedTo(typeof(BinaryFormatter))]
[assembly: TypeForwardedTo(typeof(FormatterAssemblyStyle))]
[assembly: TypeForwardedTo(typeof(FormatterTypeStyle))]
[assembly: TypeForwardedTo(typeof(IFieldInfo))]
[assembly: TypeForwardedTo(typeof(TypeFilterLevel))]
[assembly: TypeForwardedTo(typeof(FormatterServices))]
[assembly: TypeForwardedTo(typeof(IDeserializationCallback))]
[assembly: TypeForwardedTo(typeof(IExtensibleDataObject))]
[assembly: TypeForwardedTo(typeof(IFormatter))]
[assembly: TypeForwardedTo(typeof(IFormatterConverter))]
[assembly: TypeForwardedTo(typeof(IgnoreDataMemberAttribute))]
[assembly: TypeForwardedTo(typeof(InvalidDa

BepInEx/core/OllamaSharp.dll

Decompiled 2 weeks ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.AI;
using OllamaSharp.AsyncEnumerableExtensions;
using OllamaSharp.MicrosoftAi;
using OllamaSharp.Models;
using OllamaSharp.Models.Chat;
using OllamaSharp.Models.Chat.Converter;
using OllamaSharp.Models.Exceptions;
using OllamaSharp.Tools;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: InternalsVisibleTo("Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a171f1618f5d4caf94ac5e1323ed80e3e2b686509951a686b66491108cf673ec16a8507ae06e7a4cc81ac14b057659e84401f1d56e17023037c160f4e3e35f6de81c479a778c78a184d15b4ccce943d2202eeeaec0c63028e1061ef5ca236b7a7d7fc52eef66d1fc65ebb89560b8dffb2353dfd2394ef2b1ec41bc3accab7df0")]
[assembly: AssemblyCompany("Andreas Wäscher, Milkey Tan, Jerrett Davis")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Andreas Wäscher")]
[assembly: AssemblyDescription("The easiest way to use the Ollama API in .NET")]
[assembly: AssemblyFileVersion("5.4.12.0")]
[assembly: AssemblyInformationalVersion("5.4.12+2d1a46ad0a3dffa6362cf217d6774f365b3f7ee8")]
[assembly: AssemblyProduct("OllamaSharp")]
[assembly: AssemblyTitle("OllamaSharp")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/awaescher/OllamaSharp")]
[assembly: AssemblyVersion("5.4.12.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	internal static class IsExternalInit
	{
	}
}
namespace OllamaSharp
{
	public static class IAsyncEnumerableExtensions
	{
		public static Task<string> StreamToEndAsync(this IAsyncEnumerable<string> stream, Action<string>? itemCallback = null)
		{
			return stream.StreamToEndAsync(new StringAppender(), itemCallback);
		}

		public static Task<GenerateDoneResponseStream?> StreamToEndAsync(this IAsyncEnumerable<GenerateResponseStream?> stream, Action<GenerateResponseStream?>? itemCallback = null)
		{
			return stream.StreamToEndAsync<GenerateResponseStream, GenerateDoneResponseStream>(new GenerateResponseStreamAppender(), itemCallback);
		}

		public static Task<ChatDoneResponseStream?> StreamToEndAsync(this IAsyncEnumerable<ChatResponseStream?> stream, Action<ChatResponseStream?>? itemCallback = null)
		{
			return stream.StreamToEndAsync<ChatResponseStream, ChatDoneResponseStream>(new ChatResponseStreamAppender(), itemCallback);
		}

		internal static async Task<Tout> StreamToEndAsync<Tin, Tout>(this IAsyncEnumerable<Tin> stream, IAppender<Tin, Tout> appender, Action<Tin>? itemCallback = null)
		{
			await foreach (Tin item in stream.ConfigureAwait(continueOnCapturedContext: false))
			{
				appender.Append(item);
				itemCallback?.Invoke(item);
			}
			return appender.Complete();
		}

		public static Task<ChatResponseUpdate?> StreamToEndAsync(this IAsyncEnumerable<ChatResponseUpdate?> stream, Action<ChatResponseUpdate?>? itemCallback = null)
		{
			return stream.StreamToEndAsync<ChatResponseUpdate, ChatResponseUpdate>(new ChatResponseUpdateAppender(), itemCallback);
		}
	}
	internal static class ByteArrayExtensions
	{
		public static string ToBase64(this IEnumerable<byte> bytes)
		{
			return Convert.ToBase64String(bytes.ToArray());
		}

		public static IEnumerable<string>? ToBase64(this IEnumerable<IEnumerable<byte>>? byteArrays)
		{
			return byteArrays?.Select((IEnumerable<byte> bytes) => bytes.ToBase64());
		}
	}
	public class Chat
	{
		[CompilerGenerated]
		private sealed class <SendAsAsync>d__45 : IAsyncEnumerable<string>, IAsyncEnumerator<string>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private string <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private object format;

			public object <>3__format;

			public Chat <>4__this;

			private ChatRole role;

			public ChatRole <>3__role;

			private string message;

			public string <>3__message;

			private IEnumerable<string> imagesAsBase64;

			public IEnumerable<string> <>3__imagesAsBase64;

			private IEnumerable<object> tools;

			public IEnumerable<object> <>3__tools;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private MessageBuilder <messageBuilder>5__2;

			private ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator <>7__wrap2;

			private object <>7__wrap3;

			private int <>7__wrap4;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2;

			private List<Message> <toolResultMessages>5__6;

			private IEnumerator<Message.ToolCall> <>7__wrap6;

			private Message.ToolCall <toolCall>5__8;

			private ConfiguredTaskAwaitable<ToolResult>.ConfiguredTaskAwaiter <>u__3;

			private ConfiguredCancelableAsyncEnumerable<string>.Enumerator <>7__wrap8;

			string IAsyncEnumerator<string>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <SendAsAsync>d__45(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				Chat chat = <>4__this;
				try
				{
					ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter;
					object obj;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							if (format is CancellationToken)
							{
								throw new NotSupportedException("Argument \"format\" cannot be of type CancellationToken. Make sure you use the correct method overload of ChatSendAsync() or ChatSendAsAsync().");
							}
							chat.Messages.Add(new Message(role, this.message, imagesAsBase64?.ToArray()));
							ChatRequest request = new ChatRequest
							{
								Messages = chat.Messages,
								Model = chat.Model,
								Stream = true,
								Tools = tools,
								Format = format,
								Options = chat.Options,
								Think = chat.Think
							};
							<messageBuilder>5__2 = new MessageBuilder();
							<>7__wrap2 = chat.Client.ChatAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
							<>7__wrap3 = null;
							<>7__wrap4 = 0;
							goto case -4;
						}
						goto end_IL_000e;
					case -4:
					case 0:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -4)
							{
								if (num != 0)
								{
									goto IL_0211;
								}
								awaiter2 = <>u__1;
								<>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
								num = (<>1__state = -1);
								goto IL_027c;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_0211;
							}
							goto end_IL_0130;
							IL_0211:
							<>2__current = null;
							awaiter2 = <>7__wrap2.MoveNextAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter2;
								<SendAsAsync>d__45 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_027c;
							IL_027c:
							if (awaiter2.GetResult())
							{
								ChatResponseStream current = <>7__wrap2.Current;
								if (current != null)
								{
									<messageBuilder>5__2.Append(current);
									ThinkValue? think = chat.Think;
									if (!(think.HasValue ? ((bool?)think.GetValueOrDefault()) : null).GetValueOrDefault() || string.IsNullOrEmpty(current.Message.Thinking))
									{
										<>2__current = current.Message.Content ?? string.Empty;
										num = (<>1__state = -4);
										goto IL_083e;
									}
									chat.OnThink?.Invoke(chat, current.Message.Thinking);
								}
								goto IL_0211;
							}
							end_IL_0130:;
						}
						catch (object obj2)
						{
							<>7__wrap3 = obj2;
						}
						<>2__current = null;
						awaiter = <>7__wrap2.DisposeAsync().GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__2 = awaiter;
							<SendAsAsync>d__45 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
							return;
						}
						goto IL_0301;
					case 1:
						awaiter = <>u__2;
						<>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_0301;
					case 2:
						try
						{
							if (num != 2)
							{
								goto IL_04e3;
							}
							ConfiguredTaskAwaitable<ToolResult>.ConfiguredTaskAwaiter awaiter3 = <>u__3;
							<>u__3 = default(ConfiguredTaskAwaitable<ToolResult>.ConfiguredTaskAwaiter);
							num = (<>1__state = -1);
							goto IL_0489;
							IL_04e3:
							if (<>7__wrap6.MoveNext())
							{
								<toolCall>5__8 = <>7__wrap6.Current;
								chat.OnToolCall?.Invoke(chat, <toolCall>5__8);
								<>2__current = null;
								awaiter3 = chat.ToolInvoker.InvokeAsync(<toolCall>5__8, tools ?? Array.Empty<object>(), cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
								if (!awaiter3.IsCompleted)
								{
									num = (<>1__state = 2);
									<>u__3 = awaiter3;
									<SendAsAsync>d__45 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine);
									return;
								}
								goto IL_0489;
							}
							goto end_IL_03c8;
							IL_0489:
							ToolResult result = awaiter3.GetResult();
							<toolResultMessages>5__6.Add(new Message(ChatRole.Tool, $"Tool: {StringifyToolCall(<toolCall>5__8)}:\nResult: {result.Result}"));
							chat.OnToolResult?.Invoke(chat, result);
							<toolCall>5__8 = null;
							goto IL_04e3;
							end_IL_03c8:;
						}
						finally
						{
							if (num == -1 && <>7__wrap6 != null)
							{
								<>7__wrap6.Dispose();
							}
						}
						if (!<>w__disposeMode)
						{
							<>7__wrap6 = null;
							if (!<toolResultMessages>5__6.Any())
							{
								break;
							}
							chat.Messages.AddRange(<toolResultMessages>5__6.Take(<toolResultMessages>5__6.Count - 1));
							<>7__wrap8 = chat.SendAsAsync(ChatRole.Tool, <toolResultMessages>5__6.Last().Content ?? "", tools, null, null, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
							<>7__wrap3 = null;
							<>7__wrap4 = 0;
							goto case -5;
						}
						goto end_IL_000e;
					case -5:
					case 3:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -5)
							{
								if (num != 3)
								{
									goto IL_05f2;
								}
								awaiter2 = <>u__1;
								<>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
								num = (<>1__state = -1);
								goto IL_065d;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_05f2;
							}
							goto end_IL_05aa;
							IL_05f2:
							<>2__current = null;
							awaiter2 = <>7__wrap8.MoveNextAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 3);
								<>u__1 = awaiter2;
								<SendAsAsync>d__45 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_065d;
							IL_065d:
							if (awaiter2.GetResult())
							{
								string current2 = <>7__wrap8.Current;
								<>2__current = current2;
								num = (<>1__state = -5);
								goto IL_083e;
							}
							end_IL_05aa:;
						}
						catch (object obj2)
						{
							<>7__wrap3 = obj2;
						}
						<>2__current = null;
						awaiter = <>7__wrap8.DisposeAsync().GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 4);
							<>u__2 = awaiter;
							<SendAsAsync>d__45 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
							return;
						}
						goto IL_06e2;
					case 4:
						{
							awaiter = <>u__2;
							<>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
							num = (<>1__state = -1);
							goto IL_06e2;
						}
						IL_06e2:
						awaiter.GetResult();
						obj = <>7__wrap3;
						if (obj != null)
						{
							ExceptionDispatchInfo.Capture((obj as Exception) ?? throw obj).Throw();
						}
						_ = <>7__wrap4;
						if (!<>w__disposeMode)
						{
							<>7__wrap3 = null;
							<>7__wrap8 = default(ConfiguredCancelableAsyncEnumerable<string>.Enumerator);
							break;
						}
						goto end_IL_000e;
						IL_0301:
						awaiter.GetResult();
						obj = <>7__wrap3;
						if (obj != null)
						{
							ExceptionDispatchInfo.Capture((obj as Exception) ?? throw obj).Throw();
						}
						_ = <>7__wrap4;
						if (!<>w__disposeMode)
						{
							<>7__wrap3 = null;
							<>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
							if (<messageBuilder>5__2.HasValue)
							{
								Message message = <messageBuilder>5__2.ToMessage();
								chat.Messages.Add(message);
								if (chat.ToolInvoker != null)
								{
									IEnumerable<Message.ToolCall>? toolCalls = message.ToolCalls;
									if (toolCalls != null && toolCalls.Any() && chat.AllowRecursiveToolCalls)
									{
										<toolResultMessages>5__6 = new List<Message>();
										<>7__wrap6 = message.ToolCalls.GetEnumerator();
										goto case 2;
									}
								}
							}
						}
						goto end_IL_000e;
					}
					<toolResultMessages>5__6 = null;
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<messageBuilder>5__2 = null;
					<>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
					<>7__wrap3 = null;
					<toolResultMessages>5__6 = null;
					<>7__wrap6 = null;
					<toolCall>5__8 = null;
					<>7__wrap8 = default(ConfiguredCancelableAsyncEnumerable<string>.Enumerator);
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<messageBuilder>5__2 = null;
				<>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
				<>7__wrap3 = null;
				<toolResultMessages>5__6 = null;
				<>7__wrap6 = null;
				<toolCall>5__8 = null;
				<>7__wrap8 = default(ConfiguredCancelableAsyncEnumerable<string>.Enumerator);
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_083e:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<string> IAsyncEnumerable<string>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<SendAsAsync>d__45 <SendAsAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<SendAsAsync>d__ = this;
				}
				else
				{
					<SendAsAsync>d__ = new <SendAsAsync>d__45(-3)
					{
						<>4__this = <>4__this
					};
				}
				<SendAsAsync>d__.role = <>3__role;
				<SendAsAsync>d__.message = <>3__message;
				<SendAsAsync>d__.tools = <>3__tools;
				<SendAsAsync>d__.imagesAsBase64 = <>3__imagesAsBase64;
				<SendAsAsync>d__.format = <>3__format;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<SendAsAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<SendAsAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<SendAsAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <SendAsAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<string>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<SendAsAsync>d__45 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<SendAsAsync>d__45 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		public List<Message> Messages { get; set; } = new List<Message>();


		public IOllamaApiClient Client { get; }

		public string Model { get; set; }

		public RequestOptions? Options { get; set; }

		public IToolInvoker ToolInvoker { get; set; } = new DefaultToolInvoker();


		public ThinkValue? Think { get; set; }

		public bool AllowRecursiveToolCalls { get; set; } = true;


		public event EventHandler<string>? OnThink;

		public event EventHandler<Message.ToolCall>? OnToolCall;

		public event EventHandler<ToolResult>? OnToolResult;

		public Chat(IOllamaApiClient client)
		{
			Client = client ?? throw new ArgumentNullException("client");
			Model = Client.SelectedModel;
		}

		public Chat(IOllamaApiClient client, string systemPrompt)
			: this(client)
		{
			if (!string.IsNullOrWhiteSpace(systemPrompt))
			{
				Messages.Add(new Message(ChatRole.System, systemPrompt));
			}
		}

		public IAsyncEnumerable<string> SendAsync(string message, CancellationToken cancellationToken = default(CancellationToken))
		{
			return SendAsync(message, null, null, null, cancellationToken);
		}

		public IAsyncEnumerable<string> SendAsync(string message, IEnumerable<IEnumerable<byte>>? imagesAsBytes, CancellationToken cancellationToken = default(CancellationToken))
		{
			return SendAsync(message, imagesAsBytes?.ToBase64(), cancellationToken);
		}

		public IAsyncEnumerable<string> SendAsync(string message, IEnumerable<string>? imagesAsBase64, CancellationToken cancellationToken = default(CancellationToken))
		{
			return SendAsync(message, null, imagesAsBase64, null, cancellationToken);
		}

		public IAsyncEnumerable<string> SendAsync(string message, IEnumerable<object>? tools, IEnumerable<string>? imagesAsBase64 = null, object? format = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			return SendAsAsync(ChatRole.User, message, tools, imagesAsBase64, format, cancellationToken);
		}

		public IAsyncEnumerable<string> SendAsAsync(ChatRole role, string message, CancellationToken cancellationToken = default(CancellationToken))
		{
			return SendAsAsync(role, message, null, null, null, cancellationToken);
		}

		public IAsyncEnumerable<string> SendAsAsync(ChatRole role, string message, IEnumerable<IEnumerable<byte>>? imagesAsBytes, CancellationToken cancellationToken = default(CancellationToken))
		{
			return SendAsAsync(role, message, imagesAsBytes?.ToBase64(), cancellationToken);
		}

		public IAsyncEnumerable<string> SendAsAsync(ChatRole role, string message, IEnumerable<string>? imagesAsBase64, CancellationToken cancellationToken = default(CancellationToken))
		{
			return SendAsAsync(role, message, null, imagesAsBase64, null, cancellationToken);
		}

		[AsyncIteratorStateMachine(typeof(<SendAsAsync>d__45))]
		public IAsyncEnumerable<string> SendAsAsync(ChatRole role, string message, IEnumerable<object>? tools, IEnumerable<string>? imagesAsBase64 = null, object? format = null, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			return new <SendAsAsync>d__45(-2)
			{
				<>4__this = this,
				<>3__role = role,
				<>3__message = message,
				<>3__tools = tools,
				<>3__imagesAsBase64 = imagesAsBase64,
				<>3__format = format,
				<>3__cancellationToken = cancellationToken
			};
		}

		private static string StringifyToolCall(Message.ToolCall toolCall)
		{
			return (toolCall.Function?.Name ?? "(unnamed tool)") + "(" + string.Join(", ", toolCall.Function?.Arguments?.Select((KeyValuePair<string, object> kvp) => $"{kvp.Key}: {kvp.Value}") ?? Array.Empty<string>()) + ")";
		}
	}
	internal static class CollectionExtensions
	{
		public static void AddRangeIfNotNull<T>(this List<T> list, IEnumerable<T>? items)
		{
			if (items != null)
			{
				list.AddRange(items);
			}
		}

		public static void ForEachItem<T>(this IEnumerable<T> collection, Action<T> action)
		{
			foreach (T item in collection)
			{
				action(item);
			}
		}
	}
	internal static class HttpRequestMessageExtensions
	{
		public static void ApplyCustomHeaders(this HttpRequestMessage requestMessage, Dictionary<string, string> headers, OllamaRequest? ollamaRequest)
		{
			HttpRequestMessage requestMessage2 = requestMessage;
			headers.Concat(ollamaRequest?.CustomHeaders ?? new Dictionary<string, string>()).ForEachItem<KeyValuePair<string, string>>(delegate(KeyValuePair<string, string> header)
			{
				requestMessage2.Headers.AddOrUpdateHeaderValue(header.Key, header.Value);
			});
		}

		private static void AddOrUpdateHeaderValue(this HttpRequestHeaders requestMessageHeaders, string headerKey, string headerValue)
		{
			requestMessageHeaders.Remove(headerKey);
			requestMessageHeaders.Add(headerKey, headerValue);
		}
	}
	public interface IOllamaApiClient
	{
		Uri Uri { get; }

		string SelectedModel { get; set; }

		IAsyncEnumerable<ChatResponseStream?> ChatAsync(ChatRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken));

		Task CopyModelAsync(CopyModelRequest request, CancellationToken cancellationToken = default(CancellationToken));

		IAsyncEnumerable<CreateModelResponse?> CreateModelAsync(CreateModelRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken));

		Task DeleteModelAsync(DeleteModelRequest request, CancellationToken cancellationToken = default(CancellationToken));

		Task<EmbedResponse> EmbedAsync(EmbedRequest request, CancellationToken cancellationToken = default(CancellationToken));

		Task<IEnumerable<Model>> ListLocalModelsAsync(CancellationToken cancellationToken = default(CancellationToken));

		Task<IEnumerable<RunningModel>> ListRunningModelsAsync(CancellationToken cancellationToken = default(CancellationToken));

		IAsyncEnumerable<PullModelResponse?> PullModelAsync(PullModelRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken));

		IAsyncEnumerable<PushModelResponse?> PushModelAsync(PushModelRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken));

		Task<ShowModelResponse> ShowModelAsync(ShowModelRequest request, CancellationToken cancellationToken = default(CancellationToken));

		IAsyncEnumerable<GenerateResponseStream?> GenerateAsync(GenerateRequest request, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken));

		Task<bool> IsRunningAsync(CancellationToken cancellationToken = default(CancellationToken));

		Task<string> GetVersionAsync(CancellationToken cancellationToken = default(CancellationToken));

		Task PushBlobAsync(string digest, byte[] bytes, CancellationToken cancellationToken = default(CancellationToken));

		Task<bool> IsBlobExistsAsync(string digest, CancellationToken cancellationToken = default(CancellationToken));
	}
	public static class ChatOptionsExtensions
	{
		public static ChatOptions AddOllamaOption(this ChatOptions chatOptions, OllamaOption option, object? value)
		{
			//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: Expected O, but got Unknown
			//IL_0017: Expected O, but got Unknown
			if (chatOptions.AdditionalProperties == null)
			{
				AdditionalPropertiesDictionary val = new AdditionalPropertiesDictionary();
				AdditionalPropertiesDictionary val2 = val;
				chatOptions.AdditionalProperties = val;
			}
			((AdditionalPropertiesDictionary<object>)(object)chatOptions.AdditionalProperties)[option.Name] = value;
			return chatOptions;
		}
	}
	public class OllamaApiClient : IOllamaApiClient, IChatClient, IDisposable, IEmbeddingGenerator<string, Embedding<float>>, IEmbeddingGenerator
	{
		public class Configuration
		{
			public Uri Uri { get; set; }

			public string Model { get; set; }

			public JsonSerializerContext? JsonSerializerContext { get; set; }
		}

		[CompilerGenerated]
		private sealed class <ChatAsync>d__34 : IAsyncEnumerable<ChatResponseStream>, IAsyncEnumerator<ChatResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private ChatResponseStream <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private ChatRequest request;

			public ChatRequest <>3__request;

			public OllamaApiClient <>4__this;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private HttpRequestMessage <requestMessage>5__2;

			private HttpResponseMessage <response>5__3;

			private ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter <>u__1;

			private ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator <>7__wrap3;

			private object <>7__wrap4;

			private int <>7__wrap5;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__2;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__3;

			ChatResponseStream IAsyncEnumerator<ChatResponseStream>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <ChatAsync>d__34(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				OllamaApiClient ollamaApiClient = <>4__this;
				try
				{
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							if (string.IsNullOrEmpty(request.Model))
							{
								request.Model = ollamaApiClient.SelectedModel;
							}
							<requestMessage>5__2 = new HttpRequestMessage(HttpMethod.Post, "api/chat");
							break;
						}
						goto end_IL_000e;
					case -4:
					case 0:
					case 1:
					case 2:
						break;
					}
					try
					{
						ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter awaiter;
						HttpResponseMessage result;
						switch (num)
						{
						default:
						{
							<requestMessage>5__2.Content = new StringContent(JsonSerializer.Serialize(request, ollamaApiClient.OutgoingJsonSerializerOptions), Encoding.UTF8, "application/json");
							HttpCompletionOption completionOption = (request.Stream ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead);
							<>2__current = null;
							awaiter = ollamaApiClient.SendToOllamaAsync(<requestMessage>5__2, request, completionOption, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter;
								<ChatAsync>d__34 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
								return;
							}
							goto IL_0163;
						}
						case 0:
							awaiter = <>u__1;
							<>u__1 = default(ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter);
							num = (<>1__state = -1);
							goto IL_0163;
						case -4:
						case 1:
						case 2:
							break;
							IL_0163:
							result = awaiter.GetResult();
							<response>5__3 = result;
							break;
						}
						try
						{
							ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -4 && num != 1)
							{
								if (num == 2)
								{
									awaiter2 = <>u__3;
									<>u__3 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
									num = (<>1__state = -1);
									goto IL_02f1;
								}
								<>7__wrap3 = ollamaApiClient.ProcessStreamedChatResponseAsync(<response>5__3, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
								<>7__wrap4 = null;
								<>7__wrap5 = 0;
							}
							try
							{
								ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter3;
								if (num != -4)
								{
									if (num != 1)
									{
										goto IL_0201;
									}
									awaiter3 = <>u__2;
									<>u__2 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
									num = (<>1__state = -1);
									goto IL_026c;
								}
								num = (<>1__state = -1);
								if (!<>w__disposeMode)
								{
									goto IL_0201;
								}
								goto end_IL_01b9;
								IL_0201:
								<>2__current = null;
								awaiter3 = <>7__wrap3.MoveNextAsync().GetAwaiter();
								if (!awaiter3.IsCompleted)
								{
									num = (<>1__state = 1);
									<>u__2 = awaiter3;
									<ChatAsync>d__34 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine);
									return;
								}
								goto IL_026c;
								IL_026c:
								if (!awaiter3.GetResult())
								{
									goto end_IL_01b9;
								}
								ChatResponseStream current = <>7__wrap3.Current;
								<>2__current = current;
								num = (<>1__state = -4);
								goto end_IL_0173;
								end_IL_01b9:;
							}
							catch (object obj)
							{
								<>7__wrap4 = obj;
							}
							<>2__current = null;
							awaiter2 = <>7__wrap3.DisposeAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 2);
								<>u__3 = awaiter2;
								<ChatAsync>d__34 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_02f1;
							IL_02f1:
							awaiter2.GetResult();
							object obj2 = <>7__wrap4;
							if (obj2 != null)
							{
								ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw();
							}
							_ = <>7__wrap5;
							if (<>w__disposeMode)
							{
								goto IL_035c;
							}
							<>7__wrap4 = null;
							<>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
							goto end_IL_000e;
							end_IL_0173:;
						}
						finally
						{
							if (num == -1 && <response>5__3 != null)
							{
								((IDisposable)<response>5__3).Dispose();
							}
						}
						goto end_IL_0082;
						IL_035c:
						_ = <>w__disposeMode;
						goto IL_037d;
						end_IL_0082:;
					}
					finally
					{
						if (num == -1 && <requestMessage>5__2 != null)
						{
							((IDisposable)<requestMessage>5__2).Dispose();
						}
					}
					goto IL_045f;
					IL_037d:
					if (!<>w__disposeMode)
					{
						<requestMessage>5__2 = null;
						<response>5__3 = null;
						throw null;
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<requestMessage>5__2 = null;
					<response>5__3 = null;
					<>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
					<>7__wrap4 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<requestMessage>5__2 = null;
				<response>5__3 = null;
				<>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
				<>7__wrap4 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_045f:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<ChatResponseStream> IAsyncEnumerable<ChatResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<ChatAsync>d__34 <ChatAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<ChatAsync>d__ = this;
				}
				else
				{
					<ChatAsync>d__ = new <ChatAsync>d__34(-3)
					{
						<>4__this = <>4__this
					};
				}
				<ChatAsync>d__.request = <>3__request;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<ChatAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<ChatAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<ChatAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <ChatAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<ChatResponseStream>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<ChatAsync>d__34 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<ChatAsync>d__34 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		[CompilerGenerated]
		private sealed class <CreateModelAsync>d__24 : IAsyncEnumerable<CreateModelResponse>, IAsyncEnumerator<CreateModelResponse>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private CreateModelResponse <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			public OllamaApiClient <>4__this;

			private CreateModelRequest request;

			public CreateModelRequest <>3__request;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private ConfiguredCancelableAsyncEnumerable<CreateModelResponse>.Enumerator <>7__wrap1;

			private object <>7__wrap2;

			private int <>7__wrap3;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2;

			CreateModelResponse IAsyncEnumerator<CreateModelResponse>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <CreateModelAsync>d__24(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				OllamaApiClient ollamaApiClient = <>4__this;
				try
				{
					ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							<>7__wrap1 = ollamaApiClient.StreamPostAsync<CreateModelRequest, CreateModelResponse>("api/create", request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
							<>7__wrap2 = null;
							<>7__wrap3 = 0;
							goto case -4;
						}
						goto end_IL_000e;
					case -4:
					case 0:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -4)
							{
								if (num != 0)
								{
									goto IL_00c4;
								}
								awaiter2 = <>u__1;
								<>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
								num = (<>1__state = -1);
								goto IL_012f;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_00c4;
							}
							goto end_IL_007f;
							IL_00c4:
							<>2__current = null;
							awaiter2 = <>7__wrap1.MoveNextAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter2;
								<CreateModelAsync>d__24 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_012f;
							IL_012f:
							if (awaiter2.GetResult())
							{
								CreateModelResponse current = <>7__wrap1.Current;
								<>2__current = current;
								num = (<>1__state = -4);
								goto IL_02b0;
							}
							end_IL_007f:;
						}
						catch (object obj)
						{
							<>7__wrap2 = obj;
						}
						<>2__current = null;
						awaiter = <>7__wrap1.DisposeAsync().GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__2 = awaiter;
							<CreateModelAsync>d__24 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
							return;
						}
						break;
					case 1:
						awaiter = <>u__2;
						<>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
						num = (<>1__state = -1);
						break;
					}
					awaiter.GetResult();
					object obj2 = <>7__wrap2;
					if (obj2 != null)
					{
						ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw();
					}
					_ = <>7__wrap3;
					if (!<>w__disposeMode)
					{
						<>7__wrap2 = null;
						<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<CreateModelResponse>.Enumerator);
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<CreateModelResponse>.Enumerator);
					<>7__wrap2 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<CreateModelResponse>.Enumerator);
				<>7__wrap2 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_02b0:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<CreateModelResponse> IAsyncEnumerable<CreateModelResponse>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<CreateModelAsync>d__24 <CreateModelAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<CreateModelAsync>d__ = this;
				}
				else
				{
					<CreateModelAsync>d__ = new <CreateModelAsync>d__24(-3)
					{
						<>4__this = <>4__this
					};
				}
				<CreateModelAsync>d__.request = <>3__request;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<CreateModelAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<CreateModelAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<CreateModelAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <CreateModelAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<CreateModelResponse>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<CreateModelAsync>d__24 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<CreateModelAsync>d__24 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		[CompilerGenerated]
		private sealed class <GenerateAsync>d__33 : IAsyncEnumerable<GenerateResponseStream>, IAsyncEnumerator<GenerateResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private GenerateResponseStream <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private GenerateRequest request;

			public GenerateRequest <>3__request;

			public OllamaApiClient <>4__this;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator <>7__wrap1;

			private object <>7__wrap2;

			private int <>7__wrap3;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2;

			GenerateResponseStream IAsyncEnumerator<GenerateResponseStream>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GenerateAsync>d__33(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				OllamaApiClient ollamaApiClient = <>4__this;
				try
				{
					ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							if (string.IsNullOrEmpty(request.Model))
							{
								request.Model = ollamaApiClient.SelectedModel;
							}
							<>7__wrap1 = ollamaApiClient.GenerateCompletionAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
							<>7__wrap2 = null;
							<>7__wrap3 = 0;
							goto case -4;
						}
						goto end_IL_000e;
					case -4:
					case 0:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -4)
							{
								if (num != 0)
								{
									goto IL_00e2;
								}
								awaiter2 = <>u__1;
								<>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
								num = (<>1__state = -1);
								goto IL_014d;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_00e2;
							}
							goto end_IL_009d;
							IL_00e2:
							<>2__current = null;
							awaiter2 = <>7__wrap1.MoveNextAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter2;
								<GenerateAsync>d__33 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_014d;
							IL_014d:
							if (awaiter2.GetResult())
							{
								GenerateResponseStream current = <>7__wrap1.Current;
								<>2__current = current;
								num = (<>1__state = -4);
								goto IL_02ce;
							}
							end_IL_009d:;
						}
						catch (object obj)
						{
							<>7__wrap2 = obj;
						}
						<>2__current = null;
						awaiter = <>7__wrap1.DisposeAsync().GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__2 = awaiter;
							<GenerateAsync>d__33 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
							return;
						}
						break;
					case 1:
						awaiter = <>u__2;
						<>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
						num = (<>1__state = -1);
						break;
					}
					awaiter.GetResult();
					object obj2 = <>7__wrap2;
					if (obj2 != null)
					{
						ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw();
					}
					_ = <>7__wrap3;
					if (!<>w__disposeMode)
					{
						<>7__wrap2 = null;
						<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator);
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator);
					<>7__wrap2 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>7__wrap1 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator);
				<>7__wrap2 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_02ce:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<GenerateResponseStream> IAsyncEnumerable<GenerateResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<GenerateAsync>d__33 <GenerateAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<GenerateAsync>d__ = this;
				}
				else
				{
					<GenerateAsync>d__ = new <GenerateAsync>d__33(-3)
					{
						<>4__this = <>4__this
					};
				}
				<GenerateAsync>d__.request = <>3__request;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<GenerateAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<GenerateAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<GenerateAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <GenerateAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<GenerateResponseStream>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<GenerateAsync>d__33 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<GenerateAsync>d__33 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		[CompilerGenerated]
		private sealed class <GenerateCompletionAsync>d__39 : IAsyncEnumerable<GenerateResponseStream>, IAsyncEnumerator<GenerateResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private GenerateResponseStream <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			public OllamaApiClient <>4__this;

			private GenerateRequest generateRequest;

			public GenerateRequest <>3__generateRequest;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private HttpRequestMessage <requestMessage>5__2;

			private HttpResponseMessage <response>5__3;

			private ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter <>u__1;

			private ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator <>7__wrap3;

			private object <>7__wrap4;

			private int <>7__wrap5;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__2;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__3;

			GenerateResponseStream IAsyncEnumerator<GenerateResponseStream>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <GenerateCompletionAsync>d__39(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				OllamaApiClient ollamaApiClient = <>4__this;
				try
				{
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							<requestMessage>5__2 = ollamaApiClient.CreateRequestMessage(HttpMethod.Post, "api/generate", generateRequest);
							break;
						}
						goto end_IL_000e;
					case -4:
					case 0:
					case 1:
					case 2:
						break;
					}
					try
					{
						ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter awaiter;
						HttpResponseMessage result;
						switch (num)
						{
						default:
						{
							HttpCompletionOption completionOption = (generateRequest.Stream ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead);
							<>2__current = null;
							awaiter = ollamaApiClient.SendToOllamaAsync(<requestMessage>5__2, generateRequest, completionOption, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter;
								<GenerateCompletionAsync>d__39 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
								return;
							}
							goto IL_011c;
						}
						case 0:
							awaiter = <>u__1;
							<>u__1 = default(ConfiguredTaskAwaitable<HttpResponseMessage>.ConfiguredTaskAwaiter);
							num = (<>1__state = -1);
							goto IL_011c;
						case -4:
						case 1:
						case 2:
							break;
							IL_011c:
							result = awaiter.GetResult();
							<response>5__3 = result;
							break;
						}
						try
						{
							ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -4 && num != 1)
							{
								if (num == 2)
								{
									awaiter2 = <>u__3;
									<>u__3 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
									num = (<>1__state = -1);
									goto IL_02aa;
								}
								<>7__wrap3 = ollamaApiClient.ProcessStreamedCompletionResponseAsync(<response>5__3, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
								<>7__wrap4 = null;
								<>7__wrap5 = 0;
							}
							try
							{
								ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter3;
								if (num != -4)
								{
									if (num != 1)
									{
										goto IL_01ba;
									}
									awaiter3 = <>u__2;
									<>u__2 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
									num = (<>1__state = -1);
									goto IL_0225;
								}
								num = (<>1__state = -1);
								if (!<>w__disposeMode)
								{
									goto IL_01ba;
								}
								goto end_IL_0172;
								IL_01ba:
								<>2__current = null;
								awaiter3 = <>7__wrap3.MoveNextAsync().GetAwaiter();
								if (!awaiter3.IsCompleted)
								{
									num = (<>1__state = 1);
									<>u__2 = awaiter3;
									<GenerateCompletionAsync>d__39 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter3, ref stateMachine);
									return;
								}
								goto IL_0225;
								IL_0225:
								if (!awaiter3.GetResult())
								{
									goto end_IL_0172;
								}
								GenerateResponseStream current = <>7__wrap3.Current;
								<>2__current = current;
								num = (<>1__state = -4);
								goto end_IL_012c;
								end_IL_0172:;
							}
							catch (object obj)
							{
								<>7__wrap4 = obj;
							}
							<>2__current = null;
							awaiter2 = <>7__wrap3.DisposeAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 2);
								<>u__3 = awaiter2;
								<GenerateCompletionAsync>d__39 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_02aa;
							IL_02aa:
							awaiter2.GetResult();
							object obj2 = <>7__wrap4;
							if (obj2 != null)
							{
								ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw();
							}
							_ = <>7__wrap5;
							if (<>w__disposeMode)
							{
								goto IL_0315;
							}
							<>7__wrap4 = null;
							<>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator);
							goto end_IL_000e;
							end_IL_012c:;
						}
						finally
						{
							if (num == -1 && <response>5__3 != null)
							{
								((IDisposable)<response>5__3).Dispose();
							}
						}
						goto end_IL_0066;
						IL_0315:
						_ = <>w__disposeMode;
						goto IL_0336;
						end_IL_0066:;
					}
					finally
					{
						if (num == -1 && <requestMessage>5__2 != null)
						{
							((IDisposable)<requestMessage>5__2).Dispose();
						}
					}
					goto IL_0418;
					IL_0336:
					if (!<>w__disposeMode)
					{
						<requestMessage>5__2 = null;
						<response>5__3 = null;
						throw null;
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<requestMessage>5__2 = null;
					<response>5__3 = null;
					<>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator);
					<>7__wrap4 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<requestMessage>5__2 = null;
				<response>5__3 = null;
				<>7__wrap3 = default(ConfiguredCancelableAsyncEnumerable<GenerateResponseStream>.Enumerator);
				<>7__wrap4 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_0418:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<GenerateResponseStream> IAsyncEnumerable<GenerateResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<GenerateCompletionAsync>d__39 <GenerateCompletionAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<GenerateCompletionAsync>d__ = this;
				}
				else
				{
					<GenerateCompletionAsync>d__ = new <GenerateCompletionAsync>d__39(-3)
					{
						<>4__this = <>4__this
					};
				}
				<GenerateCompletionAsync>d__.generateRequest = <>3__generateRequest;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<GenerateCompletionAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<GenerateCompletionAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<GenerateCompletionAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <GenerateCompletionAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<GenerateResponseStream>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<GenerateCompletionAsync>d__39 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<GenerateCompletionAsync>d__39 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		[CompilerGenerated]
		private sealed class <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 : IAsyncEnumerable<ChatResponseUpdate>, IAsyncEnumerator<ChatResponseUpdate>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private ChatResponseUpdate <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			public OllamaApiClient <>4__this;

			private IEnumerable<ChatMessage> messages;

			public IEnumerable<ChatMessage> <>3__messages;

			private ChatOptions options;

			public ChatOptions <>3__options;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private string <responseId>5__2;

			private ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator <>7__wrap2;

			private object <>7__wrap3;

			private int <>7__wrap4;

			private ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter <>u__1;

			private ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter <>u__2;

			ChatResponseUpdate IAsyncEnumerator<ChatResponseUpdate>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				OllamaApiClient ollamaApiClient = <>4__this;
				try
				{
					ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter awaiter;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							ChatRequest request = AbstractionMapper.ToOllamaSharpChatRequest((IChatClient?)(object)ollamaApiClient, messages, options, stream: true, ollamaApiClient.OutgoingJsonSerializerOptions);
							<responseId>5__2 = Guid.NewGuid().ToString("N");
							<>7__wrap2 = ollamaApiClient.ChatAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAsyncEnumerator();
							<>7__wrap3 = null;
							<>7__wrap4 = 0;
							goto case -4;
						}
						goto end_IL_000e;
					case -4:
					case 0:
						try
						{
							ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter awaiter2;
							if (num != -4)
							{
								if (num != 0)
								{
									goto IL_00fa;
								}
								awaiter2 = <>u__1;
								<>u__1 = default(ConfiguredValueTaskAwaitable<bool>.ConfiguredValueTaskAwaiter);
								num = (<>1__state = -1);
								goto IL_0165;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_00fa;
							}
							goto end_IL_00a8;
							IL_00fa:
							<>2__current = null;
							awaiter2 = <>7__wrap2.MoveNextAsync().GetAwaiter();
							if (!awaiter2.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter2;
								<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
								return;
							}
							goto IL_0165;
							IL_0165:
							if (awaiter2.GetResult())
							{
								ChatResponseStream current = <>7__wrap2.Current;
								<>2__current = AbstractionMapper.ToChatResponseUpdate(current, <responseId>5__2);
								num = (<>1__state = -4);
								goto IL_02f4;
							}
							end_IL_00a8:;
						}
						catch (object obj)
						{
							<>7__wrap3 = obj;
						}
						<>2__current = null;
						awaiter = <>7__wrap2.DisposeAsync().GetAwaiter();
						if (!awaiter.IsCompleted)
						{
							num = (<>1__state = 1);
							<>u__2 = awaiter;
							<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 stateMachine = this;
							<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
							return;
						}
						break;
					case 1:
						awaiter = <>u__2;
						<>u__2 = default(ConfiguredValueTaskAwaitable.ConfiguredValueTaskAwaiter);
						num = (<>1__state = -1);
						break;
					}
					awaiter.GetResult();
					object obj2 = <>7__wrap3;
					if (obj2 != null)
					{
						ExceptionDispatchInfo.Capture((obj2 as Exception) ?? throw obj2).Throw();
					}
					_ = <>7__wrap4;
					if (!<>w__disposeMode)
					{
						<>7__wrap3 = null;
						<>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<responseId>5__2 = null;
					<>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
					<>7__wrap3 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<responseId>5__2 = null;
				<>7__wrap2 = default(ConfiguredCancelableAsyncEnumerable<ChatResponseStream>.Enumerator);
				<>7__wrap3 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_02f4:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<ChatResponseUpdate> IAsyncEnumerable<ChatResponseUpdate>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__ = this;
				}
				else
				{
					<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__ = new <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55(-3)
					{
						<>4__this = <>4__this
					};
				}
				<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.messages = <>3__messages;
				<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.options = <>3__options;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<ChatResponseUpdate>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<Microsoft-Extensions-AI-IChatClient-GetStreamingResponseAsync>d__55 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		[CompilerGenerated]
		private sealed class <ProcessStreamedChatResponseAsync>d__49 : IAsyncEnumerable<ChatResponseStream>, IAsyncEnumerator<ChatResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private ChatResponseStream <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private HttpResponseMessage response;

			public HttpResponseMessage <>3__response;

			public OllamaApiClient <>4__this;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private Stream <stream>5__2;

			private StreamReader <reader>5__3;

			private ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter <>u__1;

			private ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter <>u__2;

			ChatResponseStream IAsyncEnumerator<ChatResponseStream>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <ProcessStreamedChatResponseAsync>d__49(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				OllamaApiClient ollamaApiClient = <>4__this;
				try
				{
					ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter awaiter;
					Stream result;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							<>2__current = null;
							awaiter = response.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter;
								<ProcessStreamedChatResponseAsync>d__49 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
								return;
							}
							goto IL_00b8;
						}
						goto end_IL_000e;
					case 0:
						awaiter = <>u__1;
						<>u__1 = default(ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_00b8;
					case -4:
					case 1:
						break;
						IL_00b8:
						result = awaiter.GetResult();
						<stream>5__2 = result;
						break;
					}
					try
					{
						if (num != -4 && num != 1)
						{
							<reader>5__3 = new StreamReader(<stream>5__2);
						}
						try
						{
							ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter awaiter2;
							if (num != -4)
							{
								if (num != 1)
								{
									goto IL_01ca;
								}
								awaiter2 = <>u__2;
								<>u__2 = default(ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter);
								num = (<>1__state = -1);
								goto IL_0165;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_01ca;
							}
							goto end_IL_00e3;
							IL_01ca:
							if (!<reader>5__3.EndOfStream && !cancellationToken.IsCancellationRequested)
							{
								<>2__current = null;
								awaiter2 = <reader>5__3.ReadLineAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
								if (!awaiter2.IsCompleted)
								{
									num = (<>1__state = 1);
									<>u__2 = awaiter2;
									<ProcessStreamedChatResponseAsync>d__49 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
									return;
								}
								goto IL_0165;
							}
							goto end_IL_00c8;
							IL_0165:
							string json = awaiter2.GetResult() ?? "";
							ChatResponseStream chatResponseStream = JsonSerializer.Deserialize<ChatResponseStream>(json, ollamaApiClient.IncomingJsonSerializerOptions);
							<>2__current = ((chatResponseStream != null && chatResponseStream.Done) ? JsonSerializer.Deserialize<ChatDoneResponseStream>(json, ollamaApiClient.IncomingJsonSerializerOptions) : chatResponseStream);
							num = (<>1__state = -4);
							goto IL_02e3;
							end_IL_00e3:;
						}
						finally
						{
							if (num == -1 && <reader>5__3 != null)
							{
								((IDisposable)<reader>5__3).Dispose();
							}
						}
						_ = <>w__disposeMode;
						goto IL_0227;
						end_IL_00c8:;
					}
					finally
					{
						if (num == -1 && <stream>5__2 != null)
						{
							((IDisposable)<stream>5__2).Dispose();
						}
					}
					goto end_IL_000e;
					IL_0227:
					if (!<>w__disposeMode)
					{
						<stream>5__2 = null;
						<reader>5__3 = null;
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<stream>5__2 = null;
					<reader>5__3 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<stream>5__2 = null;
				<reader>5__3 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_02e3:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<ChatResponseStream> IAsyncEnumerable<ChatResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<ProcessStreamedChatResponseAsync>d__49 <ProcessStreamedChatResponseAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<ProcessStreamedChatResponseAsync>d__ = this;
				}
				else
				{
					<ProcessStreamedChatResponseAsync>d__ = new <ProcessStreamedChatResponseAsync>d__49(-3)
					{
						<>4__this = <>4__this
					};
				}
				<ProcessStreamedChatResponseAsync>d__.response = <>3__response;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<ProcessStreamedChatResponseAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<ProcessStreamedChatResponseAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<ProcessStreamedChatResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <ProcessStreamedChatResponseAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<ChatResponseStream>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<ProcessStreamedChatResponseAsync>d__49 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<ProcessStreamedChatResponseAsync>d__49 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		[CompilerGenerated]
		private sealed class <ProcessStreamedCompletionResponseAsync>d__48 : IAsyncEnumerable<GenerateResponseStream>, IAsyncEnumerator<GenerateResponseStream>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private GenerateResponseStream <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private HttpResponseMessage response;

			public HttpResponseMessage <>3__response;

			public OllamaApiClient <>4__this;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private Stream <stream>5__2;

			private StreamReader <reader>5__3;

			private ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter <>u__1;

			private ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter <>u__2;

			GenerateResponseStream IAsyncEnumerator<GenerateResponseStream>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <ProcessStreamedCompletionResponseAsync>d__48(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				OllamaApiClient ollamaApiClient = <>4__this;
				try
				{
					ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter awaiter;
					Stream result;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							<>2__current = null;
							awaiter = response.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter;
								<ProcessStreamedCompletionResponseAsync>d__48 stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
								return;
							}
							goto IL_00b8;
						}
						goto end_IL_000e;
					case 0:
						awaiter = <>u__1;
						<>u__1 = default(ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_00b8;
					case -4:
					case 1:
						break;
						IL_00b8:
						result = awaiter.GetResult();
						<stream>5__2 = result;
						break;
					}
					try
					{
						if (num != -4 && num != 1)
						{
							<reader>5__3 = new StreamReader(<stream>5__2);
						}
						try
						{
							ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter awaiter2;
							if (num != -4)
							{
								if (num != 1)
								{
									goto IL_01ca;
								}
								awaiter2 = <>u__2;
								<>u__2 = default(ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter);
								num = (<>1__state = -1);
								goto IL_0165;
							}
							num = (<>1__state = -1);
							if (!<>w__disposeMode)
							{
								goto IL_01ca;
							}
							goto end_IL_00e3;
							IL_01ca:
							if (!<reader>5__3.EndOfStream && !cancellationToken.IsCancellationRequested)
							{
								<>2__current = null;
								awaiter2 = <reader>5__3.ReadLineAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
								if (!awaiter2.IsCompleted)
								{
									num = (<>1__state = 1);
									<>u__2 = awaiter2;
									<ProcessStreamedCompletionResponseAsync>d__48 stateMachine = this;
									<>t__builder.AwaitUnsafeOnCompleted(ref awaiter2, ref stateMachine);
									return;
								}
								goto IL_0165;
							}
							goto end_IL_00c8;
							IL_0165:
							string json = awaiter2.GetResult() ?? "";
							GenerateResponseStream generateResponseStream = JsonSerializer.Deserialize<GenerateResponseStream>(json, ollamaApiClient.IncomingJsonSerializerOptions);
							<>2__current = ((generateResponseStream != null && generateResponseStream.Done) ? JsonSerializer.Deserialize<GenerateDoneResponseStream>(json, ollamaApiClient.IncomingJsonSerializerOptions) : generateResponseStream);
							num = (<>1__state = -4);
							goto IL_02e3;
							end_IL_00e3:;
						}
						finally
						{
							if (num == -1 && <reader>5__3 != null)
							{
								((IDisposable)<reader>5__3).Dispose();
							}
						}
						_ = <>w__disposeMode;
						goto IL_0227;
						end_IL_00c8:;
					}
					finally
					{
						if (num == -1 && <stream>5__2 != null)
						{
							((IDisposable)<stream>5__2).Dispose();
						}
					}
					goto end_IL_000e;
					IL_0227:
					if (!<>w__disposeMode)
					{
						<stream>5__2 = null;
						<reader>5__3 = null;
					}
					end_IL_000e:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<stream>5__2 = null;
					<reader>5__3 = null;
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = null;
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<stream>5__2 = null;
				<reader>5__3 = null;
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = null;
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_02e3:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<GenerateResponseStream> IAsyncEnumerable<GenerateResponseStream>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<ProcessStreamedCompletionResponseAsync>d__48 <ProcessStreamedCompletionResponseAsync>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<ProcessStreamedCompletionResponseAsync>d__ = this;
				}
				else
				{
					<ProcessStreamedCompletionResponseAsync>d__ = new <ProcessStreamedCompletionResponseAsync>d__48(-3)
					{
						<>4__this = <>4__this
					};
				}
				<ProcessStreamedCompletionResponseAsync>d__.response = <>3__response;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<ProcessStreamedCompletionResponseAsync>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<ProcessStreamedCompletionResponseAsync>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<ProcessStreamedCompletionResponseAsync>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <ProcessStreamedCompletionResponseAsync>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<GenerateResponseStream>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<ProcessStreamedCompletionResponseAsync>d__48 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<ProcessStreamedCompletionResponseAsync>d__48 stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		[CompilerGenerated]
		private sealed class <ProcessStreamedResponseAsync>d__47<TLine> : IAsyncEnumerable<TLine>, IAsyncEnumerator<TLine>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine where TLine : notnull
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private TLine <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private HttpResponseMessage response;

			public HttpResponseMessage <>3__response;

			public OllamaApiClient <>4__this;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private StreamReader <reader>5__2;

			private ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter <>u__1;

			private ConfiguredTaskAwaitable<string>.ConfiguredTaskAwaiter <>u__2;

			TLine IAsyncEnumerator<TLine>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <ProcessStreamedResponseAsync>d__47(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				OllamaApiClient ollamaApiClient = <>4__this;
				try
				{
					ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter awaiter;
					Stream result;
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							<>2__current = default(TLine);
							awaiter = response.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter;
								<ProcessStreamedResponseAsync>d__47<TLine> stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
								return;
							}
							goto IL_00bd;
						}
						goto end_IL_000e;
					case 0:
						awaiter = <>u__1;
						<>u__1 = default(ConfiguredTaskAwaitable<Stream>.ConfiguredTaskAwaiter);
						num = (<>1__state = -1);
						goto IL_00bd;
					case -4:
					case 1:
						break;
						IL_00bd:
						result = awaiter.GetResult();
						<reader>5__2 = new S

BepInEx/core/OpenAI.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Metrics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.ServerSentEvents;
using System.Net.WebSockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using System.Xml;
using Microsoft.CodeAnalysis;
using OpenAI;
using OpenAI.Assistants;
using OpenAI.Audio;
using OpenAI.Batch;
using OpenAI.Chat;
using OpenAI.Containers;
using OpenAI.Conversations;
using OpenAI.Embeddings;
using OpenAI.Evals;
using OpenAI.Files;
using OpenAI.FineTuning;
using OpenAI.Graders;
using OpenAI.Images;
using OpenAI.Internal;
using OpenAI.LegacyCompletions;
using OpenAI.Models;
using OpenAI.Moderations;
using OpenAI.Realtime;
using OpenAI.Responses;
using OpenAI.Telemetry;
using OpenAI.VectorStores;
using OpenAI.Videos;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("OpenAI")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2024 OpenAI (https://openai.com)")]
[assembly: AssemblyDescription("\n    The official .NET library for the OpenAI service API.\n    ")]
[assembly: AssemblyFileVersion("2.8.0.0")]
[assembly: AssemblyInformationalVersion("2.8.0+8639c48b359cb3b6b5b9e072116db68e73954717")]
[assembly: AssemblyProduct("OpenAI")]
[assembly: AssemblyTitle("SDK Code Generation OpenAI")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/openai/openai-dotnet")]
[assembly: InternalsVisibleTo("Azure.AI.OpenAI, PublicKey=0024000004800000940000000602000000240000525341310004000001000100097ad52abbeaa2e1a1982747cc0106534f65cfea6707eaed696a3a63daea80de2512746801a7e47f88e7781e71af960d89ba2e25561f70b0e2dbc93319e0af1961a719ccf5a4d28709b2b57a5d29b7c09dc8d269a490ebe2651c4b6e6738c27c5fb2c02469fe9757f0a3479ac310d6588a50a28d7dd431b907fd325e18b9e8ed")]
[assembly: ModelReaderWriterContextType(typeof(OpenAIContext))]
[assembly: AssemblyVersion("2.8.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	internal static class IsExternalInit
	{
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	internal sealed class ExperimentalAttribute : Attribute
	{
		public string DiagnosticId { get; }

		public string? UrlFormat { get; set; }

		public ExperimentalAttribute(string diagnosticId)
		{
			DiagnosticId = diagnosticId;
		}
	}
}
namespace OpenAI
{
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	[CodeGenType("CreateThreadAndRunRequestAccept")]
	internal readonly struct AcceptHeaderValue
	{
	}
	internal static class CancellationTokenExtensions
	{
		private static RequestOptions _streamRequestOptions;

		private static RequestOptions StreamRequestOptions
		{
			get
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				//IL_000e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0015: Unknown result type (might be due to invalid IL or missing references)
				//IL_001b: Expected O, but got Unknown
				object obj = _streamRequestOptions;
				if (obj == null)
				{
					RequestOptions val = new RequestOptions
					{
						BufferResponse = false
					};
					_streamRequestOptions = val;
					obj = (object)val;
				}
				return (RequestOptions)obj;
			}
		}

		public static RequestOptions ToRequestOptions(this CancellationToken cancellationToken, bool streaming = false)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Expected O, but got Unknown
			if (cancellationToken == default(CancellationToken))
			{
				if (!streaming)
				{
					return null;
				}
				return StreamRequestOptions;
			}
			return new RequestOptions
			{
				CancellationToken = cancellationToken,
				BufferResponse = !streaming
			};
		}

		public static RequestOptions ToRequestOptions(this CancellationToken cancellationToken)
		{
			//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_0018: Expected O, but got Unknown
			if (!cancellationToken.CanBeCanceled)
			{
				return null;
			}
			return new RequestOptions
			{
				CancellationToken = cancellationToken
			};
		}
	}
	internal static class ClientPipelineExtensions
	{
		public static async ValueTask<PipelineResponse> ProcessMessageAsync(this ClientPipeline pipeline, PipelineMessage message, RequestOptions options)
		{
			await pipeline.SendAsync(message).ConfigureAwait(continueOnCapturedContext: false);
			if (message.Response.IsError)
			{
				if (options == null || (options.ErrorOptions & 1) != 1)
				{
					string text = await TryBufferResponseAndCreateErrorAsync(message).ConfigureAwait(continueOnCapturedContext: false);
					ClientResultException val = ((text == null || string.IsNullOrEmpty(text)) ? new ClientResultException(message.Response, (Exception)null) : new ClientResultException(text, message.Response, (Exception)null));
					throw val;
				}
			}
			return message.BufferResponse ? message.Response : message.ExtractResponse();
		}

		public static PipelineResponse ProcessMessage(this ClientPipeline pipeline, PipelineMessage message, RequestOptions options)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Expected O, but got Unknown
			pipeline.Send(message);
			if (message.Response.IsError && (options == null || (options.ErrorOptions & 1) != 1))
			{
				string text = TryBufferResponseAndCreateError(message);
				ClientResultException val = ((text == null || string.IsNullOrEmpty(text)) ? new ClientResultException(message.Response, (Exception)null) : new ClientResultException(text, message.Response, (Exception)null));
				throw val;
			}
			if (!message.BufferResponse)
			{
				return message.ExtractResponse();
			}
			return message.Response;
		}

		private static string TryBufferResponseAndCreateError(PipelineMessage message)
		{
			message.Response.BufferContent(default(CancellationToken));
			return TryCreateErrorMessageFromResponse(message.Response);
		}

		private static async Task<string> TryBufferResponseAndCreateErrorAsync(PipelineMessage message)
		{
			await message.Response.BufferContentAsync(default(CancellationToken)).ConfigureAwait(continueOnCapturedContext: false);
			return TryCreateErrorMessageFromResponse(message.Response);
		}

		private static string TryCreateErrorMessageFromResponse(PipelineResponse response)
		{
			return OpenAIError.TryCreateFromResponse(response)?.ToExceptionMessage(response.Status);
		}

		public static async ValueTask<ClientResult<bool>> ProcessHeadAsBoolMessageAsync(this ClientPipeline pipeline, PipelineMessage message, RequestOptions options)
		{
			PipelineResponse val = await pipeline.ProcessMessageAsync(message, options).ConfigureAwait(continueOnCapturedContext: false);
			switch (val.Status)
			{
			case 200:
			case 201:
			case 202:
			case 203:
			case 204:
			case 205:
			case 206:
			case 207:
			case 208:
			case 209:
			case 210:
			case 211:
			case 212:
			case 213:
			case 214:
			case 215:
			case 216:
			case 217:
			case 218:
			case 219:
			case 220:
			case 221:
			case 222:
			case 223:
			case 224:
			case 225:
			case 226:
			case 227:
			case 228:
			case 229:
			case 230:
			case 231:
			case 232:
			case 233:
			case 234:
			case 235:
			case 236:
			case 237:
			case 238:
			case 239:
			case 240:
			case 241:
			case 242:
			case 243:
			case 244:
			case 245:
			case 246:
			case 247:
			case 248:
			case 249:
			case 250:
			case 251:
			case 252:
			case 253:
			case 254:
			case 255:
			case 256:
			case 257:
			case 258:
			case 259:
			case 260:
			case 261:
			case 262:
			case 263:
			case 264:
			case 265:
			case 266:
			case 267:
			case 268:
			case 269:
			case 270:
			case 271:
			case 272:
			case 273:
			case 274:
			case 275:
			case 276:
			case 277:
			case 278:
			case 279:
			case 280:
			case 281:
			case 282:
			case 283:
			case 284:
			case 285:
			case 286:
			case 287:
			case 288:
			case 289:
			case 290:
			case 291:
			case 292:
			case 293:
			case 294:
			case 295:
			case 296:
			case 297:
			case 298:
			case 299:
				return ClientResult.FromValue<bool>(true, val);
			case 400:
			case 401:
			case 402:
			case 403:
			case 404:
			case 405:
			case 406:
			case 407:
			case 408:
			case 409:
			case 410:
			case 411:
			case 412:
			case 413:
			case 414:
			case 415:
			case 416:
			case 417:
			case 418:
			case 419:
			case 420:
			case 421:
			case 422:
			case 423:
			case 424:
			case 425:
			case 426:
			case 427:
			case 428:
			case 429:
			case 430:
			case 431:
			case 432:
			case 433:
			case 434:
			case 435:
			case 436:
			case 437:
			case 438:
			case 439:
			case 440:
			case 441:
			case 442:
			case 443:
			case 444:
			case 445:
			case 446:
			case 447:
			case 448:
			case 449:
			case 450:
			case 451:
			case 452:
			case 453:
			case 454:
			case 455:
			case 456:
			case 457:
			case 458:
			case 459:
			case 460:
			case 461:
			case 462:
			case 463:
			case 464:
			case 465:
			case 466:
			case 467:
			case 468:
			case 469:
			case 470:
			case 471:
			case 472:
			case 473:
			case 474:
			case 475:
			case 476:
			case 477:
			case 478:
			case 479:
			case 480:
			case 481:
			case 482:
			case 483:
			case 484:
			case 485:
			case 486:
			case 487:
			case 488:
			case 489:
			case 490:
			case 491:
			case 492:
			case 493:
			case 494:
			case 495:
			case 496:
			case 497:
			case 498:
			case 499:
				return ClientResult.FromValue<bool>(false, val);
			default:
				return new ErrorResult<bool>(val, new ClientResultException(val, (Exception)null));
			}
		}

		public static ClientResult<bool> ProcessHeadAsBoolMessage(this ClientPipeline pipeline, PipelineMessage message, RequestOptions options)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			PipelineResponse val = pipeline.ProcessMessage(message, options);
			switch (val.Status)
			{
			case 200:
			case 201:
			case 202:
			case 203:
			case 204:
			case 205:
			case 206:
			case 207:
			case 208:
			case 209:
			case 210:
			case 211:
			case 212:
			case 213:
			case 214:
			case 215:
			case 216:
			case 217:
			case 218:
			case 219:
			case 220:
			case 221:
			case 222:
			case 223:
			case 224:
			case 225:
			case 226:
			case 227:
			case 228:
			case 229:
			case 230:
			case 231:
			case 232:
			case 233:
			case 234:
			case 235:
			case 236:
			case 237:
			case 238:
			case 239:
			case 240:
			case 241:
			case 242:
			case 243:
			case 244:
			case 245:
			case 246:
			case 247:
			case 248:
			case 249:
			case 250:
			case 251:
			case 252:
			case 253:
			case 254:
			case 255:
			case 256:
			case 257:
			case 258:
			case 259:
			case 260:
			case 261:
			case 262:
			case 263:
			case 264:
			case 265:
			case 266:
			case 267:
			case 268:
			case 269:
			case 270:
			case 271:
			case 272:
			case 273:
			case 274:
			case 275:
			case 276:
			case 277:
			case 278:
			case 279:
			case 280:
			case 281:
			case 282:
			case 283:
			case 284:
			case 285:
			case 286:
			case 287:
			case 288:
			case 289:
			case 290:
			case 291:
			case 292:
			case 293:
			case 294:
			case 295:
			case 296:
			case 297:
			case 298:
			case 299:
				return ClientResult.FromValue<bool>(true, val);
			case 400:
			case 401:
			case 402:
			case 403:
			case 404:
			case 405:
			case 406:
			case 407:
			case 408:
			case 409:
			case 410:
			case 411:
			case 412:
			case 413:
			case 414:
			case 415:
			case 416:
			case 417:
			case 418:
			case 419:
			case 420:
			case 421:
			case 422:
			case 423:
			case 424:
			case 425:
			case 426:
			case 427:
			case 428:
			case 429:
			case 430:
			case 431:
			case 432:
			case 433:
			case 434:
			case 435:
			case 436:
			case 437:
			case 438:
			case 439:
			case 440:
			case 441:
			case 442:
			case 443:
			case 444:
			case 445:
			case 446:
			case 447:
			case 448:
			case 449:
			case 450:
			case 451:
			case 452:
			case 453:
			case 454:
			case 455:
			case 456:
			case 457:
			case 458:
			case 459:
			case 460:
			case 461:
			case 462:
			case 463:
			case 464:
			case 465:
			case 466:
			case 467:
			case 468:
			case 469:
			case 470:
			case 471:
			case 472:
			case 473:
			case 474:
			case 475:
			case 476:
			case 477:
			case 478:
			case 479:
			case 480:
			case 481:
			case 482:
			case 483:
			case 484:
			case 485:
			case 486:
			case 487:
			case 488:
			case 489:
			case 490:
			case 491:
			case 492:
			case 493:
			case 494:
			case 495:
			case 496:
			case 497:
			case 498:
			case 499:
				return ClientResult.FromValue<bool>(false, val);
			default:
				return new ErrorResult<bool>(val, new ClientResultException(val, (Exception)null));
			}
		}
	}
	internal static class IEnumerableExtensions
	{
		[CompilerGenerated]
		private sealed class <ToAsyncEnumerable>d__0<T> : IAsyncEnumerable<T>, IAsyncEnumerator<T>, IAsyncDisposable, IValueTaskSource<bool>, IValueTaskSource, IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncIteratorMethodBuilder <>t__builder;

			public ManualResetValueTaskSourceCore<bool> <>v__promiseOfValueOrEnd;

			private T <>2__current;

			private bool <>w__disposeMode;

			private CancellationTokenSource <>x__combinedTokens;

			private int <>l__initialThreadId;

			private IEnumerable<T> enumerable;

			public IEnumerable<T> <>3__enumerable;

			private CancellationToken cancellationToken;

			public CancellationToken <>3__cancellationToken;

			private IEnumerator<T> <>7__wrap1;

			private T <item>5__3;

			private ConfiguredTaskAwaitable.ConfiguredTaskAwaiter <>u__1;

			T IAsyncEnumerator<T>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

			[DebuggerHidden]
			public <ToAsyncEnumerable>d__0(int <>1__state)
			{
				<>t__builder = AsyncIteratorMethodBuilder.Create();
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			private void MoveNext()
			{
				int num = <>1__state;
				try
				{
					switch (num)
					{
					default:
						if (!<>w__disposeMode)
						{
							num = (<>1__state = -1);
							<>7__wrap1 = enumerable.GetEnumerator();
							break;
						}
						goto end_IL_0007;
					case -4:
					case 0:
						break;
					}
					try
					{
						ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter;
						if (num != -4)
						{
							if (num != 0)
							{
								goto IL_011e;
							}
							awaiter = <>u__1;
							<>u__1 = default(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter);
							num = (<>1__state = -1);
							goto IL_00df;
						}
						num = (<>1__state = -1);
						if (!<>w__disposeMode)
						{
							<item>5__3 = default(T);
							goto IL_011e;
						}
						goto end_IL_004c;
						IL_00df:
						awaiter.GetResult();
						<>2__current = <item>5__3;
						num = (<>1__state = -4);
						goto IL_0211;
						IL_011e:
						if (<>7__wrap1.MoveNext())
						{
							<item>5__3 = <>7__wrap1.Current;
							<>2__current = default(T);
							awaiter = Task.Delay(0, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter;
								<ToAsyncEnumerable>d__0<T> stateMachine = this;
								<>t__builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
								return;
							}
							goto IL_00df;
						}
						end_IL_004c:;
					}
					finally
					{
						if (num == -1 && <>7__wrap1 != null)
						{
							<>7__wrap1.Dispose();
						}
					}
					if (!<>w__disposeMode)
					{
						<>7__wrap1 = null;
					}
					end_IL_0007:;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>7__wrap1 = null;
					<item>5__3 = default(T);
					if (<>x__combinedTokens != null)
					{
						<>x__combinedTokens.Dispose();
						<>x__combinedTokens = null;
					}
					<>2__current = default(T);
					<>t__builder.Complete();
					<>v__promiseOfValueOrEnd.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>7__wrap1 = null;
				<item>5__3 = default(T);
				if (<>x__combinedTokens != null)
				{
					<>x__combinedTokens.Dispose();
					<>x__combinedTokens = null;
				}
				<>2__current = default(T);
				<>t__builder.Complete();
				<>v__promiseOfValueOrEnd.SetResult(result: false);
				return;
				IL_0211:
				<>v__promiseOfValueOrEnd.SetResult(result: true);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}

			[DebuggerHidden]
			IAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
			{
				<ToAsyncEnumerable>d__0<T> <ToAsyncEnumerable>d__;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = -3;
					<>t__builder = AsyncIteratorMethodBuilder.Create();
					<>w__disposeMode = false;
					<ToAsyncEnumerable>d__ = this;
				}
				else
				{
					<ToAsyncEnumerable>d__ = new <ToAsyncEnumerable>d__0<T>(-3);
				}
				<ToAsyncEnumerable>d__.enumerable = <>3__enumerable;
				if (<>3__cancellationToken.Equals(default(CancellationToken)))
				{
					<ToAsyncEnumerable>d__.cancellationToken = cancellationToken;
				}
				else if (cancellationToken.Equals(<>3__cancellationToken) || cancellationToken.Equals(default(CancellationToken)))
				{
					<ToAsyncEnumerable>d__.cancellationToken = <>3__cancellationToken;
				}
				else
				{
					<>x__combinedTokens = CancellationTokenSource.CreateLinkedTokenSource(<>3__cancellationToken, cancellationToken);
					<ToAsyncEnumerable>d__.cancellationToken = <>x__combinedTokens.Token;
				}
				return <ToAsyncEnumerable>d__;
			}

			[DebuggerHidden]
			ValueTask<bool> IAsyncEnumerator<T>.MoveNextAsync()
			{
				if (<>1__state == -2)
				{
					return default(ValueTask<bool>);
				}
				<>v__promiseOfValueOrEnd.Reset();
				<ToAsyncEnumerable>d__0<T> stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				short version = <>v__promiseOfValueOrEnd.Version;
				if (<>v__promiseOfValueOrEnd.GetStatus(version) == ValueTaskSourceStatus.Succeeded)
				{
					return new ValueTask<bool>(<>v__promiseOfValueOrEnd.GetResult(version));
				}
				return new ValueTask<bool>(this, version);
			}

			[DebuggerHidden]
			bool IValueTaskSource<bool>.GetResult(short token)
			{
				return <>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource<bool>.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource<bool>.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			void IValueTaskSource.GetResult(short token)
			{
				<>v__promiseOfValueOrEnd.GetResult(token);
			}

			[DebuggerHidden]
			ValueTaskSourceStatus IValueTaskSource.GetStatus(short token)
			{
				return <>v__promiseOfValueOrEnd.GetStatus(token);
			}

			[DebuggerHidden]
			void IValueTaskSource.OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				<>v__promiseOfValueOrEnd.OnCompleted(continuation, state, token, flags);
			}

			[DebuggerHidden]
			ValueTask IAsyncDisposable.DisposeAsync()
			{
				if (<>1__state >= -1)
				{
					throw new NotSupportedException();
				}
				if (<>1__state == -2)
				{
					return default(ValueTask);
				}
				<>w__disposeMode = true;
				<>v__promiseOfValueOrEnd.Reset();
				<ToAsyncEnumerable>d__0<T> stateMachine = this;
				<>t__builder.MoveNext(ref stateMachine);
				return new ValueTask(this, <>v__promiseOfValueOrEnd.Version);
			}
		}

		[AsyncIteratorStateMachine(typeof(<ToAsyncEnumerable>d__0<>))]
		public static IAsyncEnumerable<T> ToAsyncEnumerable<T>(this IEnumerable<T> enumerable, [EnumeratorCancellation] CancellationToken cancellationToken)
		{
			return new <ToAsyncEnumerable>d__0<T>(-2)
			{
				<>3__enumerable = enumerable,
				<>3__cancellationToken = cancellationToken
			};
		}
	}
	internal interface IInternalListResponse<T>
	{
		IReadOnlyList<T> Data { get; }

		string FirstId { get; }

		string LastId { get; }

		bool HasMore { get; }
	}
	[CodeGenType("FunctionObject")]
	internal class InternalFunctionDefinition : IJsonModel<InternalFunctionDefinition>, IPersistableModel<InternalFunctionDefinition>
	{
		[Experimental("SCME0001")]
		private JsonPatch _patch;

		[CodeGenMember("Parameters")]
		internal BinaryData Parameters { get; set; }

		[JsonIgnore]
		[EditorBrowsable(EditorBrowsableState.Never)]
		[Experimental("SCME0001")]
		public ref JsonPatch Patch => ref _patch;

		public string Description { get; set; }

		public string Name { get; set; }

		public bool? Strict { get; set; }

		public InternalFunctionDefinition(string name)
		{
			Name = name;
		}

		internal InternalFunctionDefinition(string description, string name, BinaryData parameters, bool? strict, in JsonPatch patch)
		{
			//IL_0026: 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)
			Description = description;
			Name = name;
			Parameters = parameters;
			Strict = strict;
			_patch = patch;
		}

		internal InternalFunctionDefinition()
		{
		}

		void IJsonModel<InternalFunctionDefinition>.Write(Utf8JsonWriter writer, ModelReaderWriterOptions options)
		{
			if (((JsonPatch)(ref Patch)).Contains("$"u8))
			{
				writer.WriteRawValue(BinaryData.op_Implicit(((JsonPatch)(ref Patch)).GetJson("$"u8)));
				return;
			}
			writer.WriteStartObject();
			JsonModelWriteCore(writer, options);
			writer.WriteEndObject();
		}

		protected virtual void JsonModelWriteCore(Utf8JsonWriter writer, ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? ((IPersistableModel<InternalFunctionDefinition>)this).GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model InternalFunctionDefinition does not support writing '" + text + "' format.");
			}
			if (Optional.IsDefined(Description) && !((JsonPatch)(ref Patch)).Contains("$.description"u8))
			{
				writer.WritePropertyName("description"u8);
				writer.WriteStringValue(Description);
			}
			if (!((JsonPatch)(ref Patch)).Contains("$.name"u8))
			{
				writer.WritePropertyName("name"u8);
				writer.WriteStringValue(Name);
			}
			if (Optional.IsDefined(Parameters) && !((JsonPatch)(ref Patch)).Contains("$.parameters"u8))
			{
				writer.WritePropertyName("parameters"u8);
				using JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(Parameters));
				JsonSerializer.Serialize(writer, jsonDocument.RootElement);
			}
			if (Optional.IsDefined(Strict) && !((JsonPatch)(ref Patch)).Contains("$.strict"u8))
			{
				writer.WritePropertyName("strict"u8);
				writer.WriteBooleanValue(Strict.Value);
			}
			((JsonPatch)(ref Patch)).WriteTo(writer);
		}

		InternalFunctionDefinition IJsonModel<InternalFunctionDefinition>.Create(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
		{
			return JsonModelCreateCore(ref reader, options);
		}

		protected virtual InternalFunctionDefinition JsonModelCreateCore(ref Utf8JsonReader reader, ModelReaderWriterOptions options)
		{
			string text = ((options.Format == "W") ? ((IPersistableModel<InternalFunctionDefinition>)this).GetFormatFromOptions(options) : options.Format);
			if (text != "J")
			{
				throw new FormatException("The model InternalFunctionDefinition does not support reading '" + text + "' format.");
			}
			using JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader);
			return DeserializeInternalFunctionDefinition(jsonDocument.RootElement, null, options);
		}

		internal static InternalFunctionDefinition DeserializeInternalFunctionDefinition(JsonElement element, BinaryData data, ModelReaderWriterOptions options)
		{
			if (element.ValueKind == JsonValueKind.Null)
			{
				return null;
			}
			string description = null;
			string name = null;
			BinaryData parameters = null;
			bool? strict = null;
			JsonPatch patch = default(JsonPatch);
			((JsonPatch)(ref patch))..ctor((data == null) ? ReadOnlyMemory<byte>.Empty : data.ToMemory());
			foreach (JsonProperty item in element.EnumerateObject())
			{
				if (item.NameEquals("description"u8))
				{
					description = item.Value.GetString();
					continue;
				}
				if (item.NameEquals("name"u8))
				{
					name = item.Value.GetString();
					continue;
				}
				if (item.NameEquals("parameters"u8))
				{
					if (item.Value.ValueKind != JsonValueKind.Null)
					{
						parameters = BinaryData.FromString(item.Value.GetRawText());
					}
					continue;
				}
				if (item.NameEquals("strict"u8))
				{
					strict = ((item.Value.ValueKind != JsonValueKind.Null) ? new bool?(item.Value.GetBoolean()) : null);
					continue;
				}
				ReadOnlySpan<byte> readOnlySpan = "$."u8;
				byte[] bytes = Encoding.UTF8.GetBytes(item.Name);
				int num = 0;
				byte[] array = new byte[readOnlySpan.Length + bytes.Length];
				readOnlySpan.CopyTo(new Span<byte>(array).Slice(num, readOnlySpan.Length));
				num += readOnlySpan.Length;
				ReadOnlySpan<byte> readOnlySpan2 = new ReadOnlySpan<byte>(bytes);
				readOnlySpan2.CopyTo(new Span<byte>(array).Slice(num, readOnlySpan2.Length));
				num += readOnlySpan2.Length;
				((JsonPatch)(ref patch)).Set(new ReadOnlySpan<byte>(array), item.Value.GetUtf8Bytes());
			}
			return new InternalFunctionDefinition(description, name, parameters, strict, in patch);
		}

		BinaryData IPersistableModel<InternalFunctionDefinition>.Write(ModelReaderWriterOptions options)
		{
			return PersistableModelWriteCore(options);
		}

		protected virtual BinaryData PersistableModelWriteCore(ModelReaderWriterOptions options)
		{
			if (((options.Format == "W") ? ((IPersistableModel<InternalFunctionDefinition>)this).GetFormatFromOptions(options) : options.Format) == "J")
			{
				return ModelReaderWriter.Write<InternalFunctionDefinition>(this, options, (ModelReaderWriterContext)(object)OpenAIContext.Default);
			}
			throw new FormatException("The model InternalFunctionDefinition does not support writing '" + options.Format + "' format.");
		}

		InternalFunctionDefinition IPersistableModel<InternalFunctionDefinition>.Create(BinaryData data, ModelReaderWriterOptions options)
		{
			return PersistableModelCreateCore(data, options);
		}

		protected virtual InternalFunctionDefinition PersistableModelCreateCore(BinaryData data, ModelReaderWriterOptions options)
		{
			if (((options.Format == "W") ? ((IPersistableModel<InternalFunctionDefinition>)this).GetFormatFromOptions(options) : options.Format) == "J")
			{
				using (JsonDocument jsonDocument = JsonDocument.Parse(BinaryData.op_Implicit(data), ModelSerializationExtensions.JsonDocumentOptions))
				{
					return DeserializeInternalFunctionDefinition(jsonDocument.RootElement, data, options);
				}
			}
			throw new FormatException("The model InternalFunctionDefinition does not support reading '" + options.Format + "' format.");
		}

		string IPersistableModel<InternalFunctionDefinition>.GetFormatFromOptions(ModelReaderWriterOptions options)
		{
			return "J";
		}
	}
	internal class TelemetryDetails
	{
		internal class RuntimeInformationWrapper
		{
			public virtual string FrameworkDescription => RuntimeInformation.FrameworkDescription;

			public virtual string OSDescription => RuntimeInformation.OSDescription;

			public virtual Architecture OSArchitecture => RuntimeInformation.OSArchitecture;

			public virtual Architecture ProcessArchitecture => RuntimeInformation.ProcessArchitecture;

			public virtual bool IsOSPlatform(OSPlatform osPlatform)
			{
				return RuntimeInformation.IsOSPlatform(osPlatform);
			}
		}

		private const int MaxApplicationIdLength = 24;

		private readonly string _userAgent;

		public Assembly Assembly { get; }

		public string? ApplicationId { get; }

		internal TelemetryDetails(Assembly assembly, string? applicationId = null)
			: this(assembly, applicationId, new RuntimeInformationWrapper())
		{
		}

		internal TelemetryDetails(Assembly assembly, string? applicationId = null, RuntimeInformationWrapper? runtimeInformation = null)
		{
			Argument.AssertNotNull(assembly, "assembly");
			if (applicationId != null && applicationId.Length > 24)
			{
				throw new ArgumentOutOfRangeException("applicationId", string.Format("{0} must be shorter than {1} characters", "applicationId", 25));
			}
			Assembly = assembly;
			ApplicationId = applicationId;
			_userAgent = GenerateUserAgentString(assembly, applicationId, runtimeInformation);
		}

		internal static string GenerateUserAgentString(Assembly clientAssembly, string? applicationId = null, RuntimeInformationWrapper? runtimeInformation = null)
		{
			string text = (clientAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>() ?? throw new InvalidOperationException("AssemblyInformationalVersionAttribute is required on client SDK assembly '" + clientAssembly.FullName + "'.")).InformationalVersion;
			string name = clientAssembly.GetName().Name;
			int num = text.LastIndexOf('+');
			if (num != -1)
			{
				text = text.Substring(0, num);
			}
			if (runtimeInformation == null)
			{
				runtimeInformation = new RuntimeInformationWrapper();
			}
			string text2 = EscapeProductInformation("(" + runtimeInformation.FrameworkDescription + "; " + runtimeInformation.OSDescription + ")");
			if (applicationId == null)
			{
				return name + "/" + text + " " + text2;
			}
			return applicationId + " " + name + "/" + text + " " + text2;
		}

		public override string ToString()
		{
			return _userAgent;
		}

		private static string EscapeProductInformation(string productInfo)
		{
			bool flag = false;
			try
			{
				flag = ProductInfoHeaderValue.TryParse(productInfo, out ProductInfoHeaderValue _);
			}
			catch (Exception)
			{
			}
			if (flag)
			{
				return productInfo;
			}
			StringBuilder stringBuilder = new StringBuilder(productInfo.Length + 2);
			stringBuilder.Append('(');
			for (int i = 1; i < productInfo.Length - 1; i++)
			{
				char c = productInfo[i];
				switch (c)
				{
				case '(':
				case ')':
					stringBuilder.Append('\\');
					break;
				case '\\':
					if (i + 1 < productInfo.Length - 1)
					{
						char c2 = productInfo[i + 1];
						if (c2 == '\\' || c2 == '(' || c2 == ')')
						{
							stringBuilder.Append(c);
							stringBuilder.Append(c2);
							i++;
							continue;
						}
						stringBuilder.Append('\\');
					}
					else
					{
						stringBuilder.Append('\\');
					}
					break;
				}
				stringBuilder.Append(c);
			}
			stringBuilder.Append(')');
			return stringBuilder.ToString();
		}
	}
	[CodeGenType("OpenAIClient")]
	[CodeGenSuppress("OpenAIClient", new Type[] { typeof(ApiKeyCredential) })]
	[CodeGenSuppress("OpenAIClient", new Type[]
	{
		typeof(Uri),
		typeof(ApiKeyCredential),
		typeof(OpenAIClientOptions)
	})]
	[CodeGenSuppress("_cachedAssistantClient", new Type[] { })]
	[CodeGenSuppress("_cachedAudioClient", new Type[] { })]
	[CodeGenSuppress("_cachedBatchClient", new Type[] { })]
	[CodeGenSuppress("_cachedChatClient", new Type[] { })]
	[CodeGenSuppress("_cachedLegacyCompletionClient", new Type[] { })]
	[CodeGenSuppress("_cachedContainerClient", new Type[] { })]
	[CodeGenSuppress("_cachedConversationClient", new Type[] { })]
	[CodeGenSuppress("_cachedEmbeddingClient", new Type[] { })]
	[CodeGenSuppress("_cachedEvaluationClient", new Type[] { })]
	[CodeGenSuppress("_cachedOpenAIFileClient", new Type[] { })]
	[CodeGenSuppress("_cachedFineTuningClient", new Type[] { })]
	[CodeGenSuppress("_cachedGraderClient", new Type[] { })]
	[CodeGenSuppress("_cachedImageClient", new Type[] { })]
	[CodeGenSuppress("_cachedOpenAIModelClient", new Type[] { })]
	[CodeGenSuppress("_cachedModerationClient", new Type[] { })]
	[CodeGenSuppress("_cachedRealtimeClient", new Type[] { })]
	[CodeGenSuppress("_cachedResponsesClient", new Type[] { })]
	[CodeGenSuppress("_cachedVectorStoreClient", new Type[] { })]
	[CodeGenSuppress("_cachedVideoClient", new Type[] { })]
	[CodeGenSuppress("_cachedInternalAssistantMessageClient", new Type[] { })]
	[CodeGenSuppress("_cachedInternalAssistantRunClient", new Type[] { })]
	[CodeGenSuppress("_cachedInternalAssistantThreadClient", new Type[] { })]
	[CodeGenSuppress("_cachedInternalUploadsClient", new Type[] { })]
	[CodeGenSuppress("GetAssistantClient", new Type[] { })]
	[CodeGenSuppress("GetAudioClient", new Type[] { })]
	[CodeGenSuppress("GetBatchClient", new Type[] { })]
	[CodeGenSuppress("GetChatClient", new Type[] { })]
	[CodeGenSuppress("GetLegacyCompletionClient", new Type[] { })]
	[CodeGenSuppress("GetContainerClient", new Type[] { })]
	[CodeGenSuppress("GetConversationClient", new Type[] { })]
	[CodeGenSuppress("GetEmbeddingClient", new Type[] { })]
	[CodeGenSuppress("GetEvaluationClient", new Type[] { })]
	[CodeGenSuppress("GetOpenAIFileClient", new Type[] { })]
	[CodeGenSuppress("GetFineTuningClient", new Type[] { })]
	[CodeGenSuppress("GetGraderClient", new Type[] { })]
	[CodeGenSuppress("GetImageClient", new Type[] { })]
	[CodeGenSuppress("GetOpenAIModelClient", new Type[] { })]
	[CodeGenSuppress("GetModerationClient", new Type[] { })]
	[CodeGenSuppress("GetRealtimeClient", new Type[] { })]
	[CodeGenSuppress("GetResponsesClient", new Type[] { })]
	[CodeGenSuppress("GetVectorStoreClient", new Type[] { })]
	[CodeGenSuppress("GetVideoClient", new Type[] { })]
	[CodeGenSuppress("GetInternalAssistantMessageClient", new Type[] { })]
	[CodeGenSuppress("GetInternalAssistantRunClient", new Type[] { })]
	[CodeGenSuppress("GetInternalAssistantThreadClient", new Type[] { })]
	[CodeGenSuppress("GetInternalUploadsClient", new Type[] { })]
	public class OpenAIClient
	{
		private static class KnownHeaderNames
		{
			public const string OpenAIOrganization = "OpenAI-Organization";

			public const string OpenAIProject = "OpenAI-Project";

			public const string UserAgent = "User-Agent";
		}

		private const string OpenAIV1Endpoint = "https://api.openai.com/v1";

		private readonly OpenAIClientOptions _options;

		private readonly Uri _endpoint;

		private readonly ApiKeyCredential _keyCredential;

		private const string AuthorizationHeader = "Authorization";

		private const string AuthorizationApiKeyPrefix = "Bearer";

		[Experimental("OPENAI001")]
		public Uri Endpoint => _endpoint;

		public ClientPipeline Pipeline { get; }

		public OpenAIClient(string apiKey)
			: this(new ApiKeyCredential(apiKey), new OpenAIClientOptions())
		{
		}//IL_0002: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown


		public OpenAIClient(ApiKeyCredential credential)
			: this(credential, new OpenAIClientOptions())
		{
		}

		public OpenAIClient(ApiKeyCredential credential, OpenAIClientOptions options)
			: this(CreateApiKeyAuthenticationPolicy(credential), options)
		{
			_keyCredential = credential;
		}

		[Experimental("OPENAI001")]
		public OpenAIClient(AuthenticationPolicy authenticationPolicy)
			: this(authenticationPolicy, new OpenAIClientOptions())
		{
		}

		[Experimental("OPENAI001")]
		public OpenAIClient(AuthenticationPolicy authenticationPolicy, OpenAIClientOptions options)
		{
			Argument.AssertNotNull<AuthenticationPolicy>(authenticationPolicy, "authenticationPolicy");
			if (options == null)
			{
				options = new OpenAIClientOptions();
			}
			Pipeline = CreatePipeline(authenticationPolicy, options);
			_endpoint = GetEndpoint(options);
			_options = options;
		}

		protected internal OpenAIClient(ClientPipeline pipeline, OpenAIClientOptions options)
		{
			Argument.AssertNotNull<ClientPipeline>(pipeline, "pipeline");
			if (options == null)
			{
				options = new OpenAIClientOptions();
			}
			Pipeline = pipeline;
			_endpoint = GetEndpoint(options);
			_options = options;
		}

		[Experimental("OPENAI001")]
		public virtual AssistantClient GetAssistantClient()
		{
			return new AssistantClient(Pipeline, _options);
		}

		public virtual AudioClient GetAudioClient(string model)
		{
			return new AudioClient(Pipeline, model, _options);
		}

		[Experimental("OPENAI001")]
		public virtual BatchClient GetBatchClient()
		{
			return new BatchClient(Pipeline, _options);
		}

		public virtual ChatClient GetChatClient(string model)
		{
			return new ChatClient(Pipeline, model, _options);
		}

		[Experimental("OPENAI001")]
		public virtual ContainerClient GetContainerClient()
		{
			return new ContainerClient(Pipeline, _options);
		}

		[Experimental("OPENAI001")]
		public virtual ConversationClient GetConversationClient()
		{
			return new ConversationClient(Pipeline, _options);
		}

		public virtual EmbeddingClient GetEmbeddingClient(string model)
		{
			return new EmbeddingClient(Pipeline, model, _options);
		}

		[Experimental("OPENAI001")]
		public virtual EvaluationClient GetEvaluationClient()
		{
			return new EvaluationClient(Pipeline, _options);
		}

		public virtual OpenAIFileClient GetOpenAIFileClient()
		{
			return new OpenAIFileClient(Pipeline, _options);
		}

		[Experimental("OPENAI001")]
		public virtual FineTuningClient GetFineTuningClient()
		{
			return new FineTuningClient(Pipeline, _options);
		}

		[Experimental("OPENAI001")]
		public virtual GraderClient GetGraderClient()
		{
			return new GraderClient(Pipeline, _options);
		}

		public virtual ImageClient GetImageClient(string model)
		{
			return new ImageClient(Pipeline, model, _options);
		}

		public virtual OpenAIModelClient GetOpenAIModelClient()
		{
			return new OpenAIModelClient(Pipeline, _options);
		}

		public virtual ModerationClient GetModerationClient(string model)
		{
			return new ModerationClient(Pipeline, model, _options);
		}

		[Experimental("OPENAI002")]
		public virtual RealtimeClient GetRealtimeClient()
		{
			return new RealtimeClient(_keyCredential, _options);
		}

		[Experimental("OPENAI001")]
		public virtual ResponsesClient GetResponsesClient(string model)
		{
			return new ResponsesClient(Pipeline, model, _options);
		}

		[Experimental("OPENAI001")]
		public virtual VectorStoreClient GetVectorStoreClient()
		{
			return new VectorStoreClient(Pipeline, _options);
		}

		[Experimental("OPENAI001")]
		public virtual VideoClient GetVideoClient()
		{
			return new VideoClient(Pipeline, _options);
		}

		internal static AuthenticationPolicy CreateApiKeyAuthenticationPolicy(ApiKeyCredential credential)
		{
			Argument.AssertNotNull<ApiKeyCredential>(credential, "credential");
			return (AuthenticationPolicy)(object)ApiKeyAuthenticationPolicy.CreateHeaderApiKeyPolicy(credential, "Authorization", "Bearer");
		}

		internal static ClientPipeline CreatePipeline(AuthenticationPolicy authenticationPolicy, OpenAIClientOptions options)
		{
			return ClientPipeline.Create((ClientPipelineOptions)(object)options, new ReadOnlySpan<PipelinePolicy>((PipelinePolicy[]?)(object)new PipelinePolicy[1] { CreateAddCustomHeadersPolicy(options) }), new ReadOnlySpan<PipelinePolicy>((PipelinePolicy[]?)(object)new PipelinePolicy[1] { (PipelinePolicy)authenticationPolicy }), default(ReadOnlySpan<PipelinePolicy>));
		}

		internal static Uri GetEndpoint(OpenAIClientOptions options = null)
		{
			return options?.Endpoint ?? new Uri("https://api.openai.com/v1");
		}

		private static PipelinePolicy CreateAddCustomHeadersPolicy(OpenAIClientOptions options = null)
		{
			TelemetryDetails telemetryDetails = new TelemetryDetails(typeof(OpenAIClientOptions).Assembly, options?.UserAgentApplicationId);
			return (PipelinePolicy)(object)new GenericActionPipelinePolicy(delegate(PipelineMessage message)
			{
				if (message != null)
				{
					PipelineRequest request = message.Request;
					bool? obj;
					if (request == null)
					{
						obj = null;
					}
					else
					{
						PipelineRequestHeaders headers = request.Headers;
						string text = default(string);
						obj = ((headers != null) ? new bool?(headers.TryGetValue("User-Agent", ref text)) : null);
					}
					if (obj == false)
					{
						message.Request.Headers.Set("User-Agent", telemetryDetails.ToString());
					}
				}
				if (!string.IsNullOrEmpty(options?.OrganizationId))
				{
					message.Request.Headers.Set("OpenAI-Organization", options.OrganizationId);
				}
				if (!string.IsNullOrEmpty(options?.ProjectId))
				{
					message.Request.Headers.Set("OpenAI-Project", options.ProjectId);
				}
			});
		}

		protected OpenAIClient()
		{
		}
	}
	[CodeGenType("OpenAIClientOptions")]
	public class OpenAIClientOptions : ClientPipelineOptions
	{
		private Uri _endpoint;

		private string _organizationId;

		private string _projectId;

		private string _userAgentApplicationId;

		public Uri Endpoint
		{
			get
			{
				return _endpoint;
			}
			set
			{
				((ClientPipelineOptions)this).AssertNotFrozen();
				_endpoint = value;
			}
		}

		public string OrganizationId
		{
			get
			{
				return _organizationId;
			}
			set
			{
				((ClientPipelineOptions)this).AssertNotFrozen();
				_organizationId = value;
			}
		}

		public string ProjectId
		{
			get
			{
				return _projectId;
			}
			set
			{
				((ClientPipelineOptions)this).AssertNotFrozen();
				_projectId = value;
			}
		}

		public string UserAgentApplicationId
		{
			get
			{
				return _userAgentApplicationId;
			}
			set
			{
				((ClientPipelineOptions)this).AssertNotFrozen();
				_userAgentApplicationId = value;
			}
		}
	}
	[Experimental("OPENAI001")]
	[ModelReaderWriterBuildable(typeof(Assistant))]
	[ModelReaderWriterBuildable(typeof(AssistantChatMessage))]
	[ModelReaderWriterBuildable(typeof(AssistantCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(AssistantCreationOptions))]
	[ModelReaderWriterBuildable(typeof(AssistantDeletionResult))]
	[ModelReaderWriterBuildable(typeof(AssistantModificationOptions))]
	[ModelReaderWriterBuildable(typeof(AssistantResponseFormat))]
	[ModelReaderWriterBuildable(typeof(AssistantThread))]
	[ModelReaderWriterBuildable(typeof(AudioTokenLogProbabilityDetails))]
	[ModelReaderWriterBuildable(typeof(AudioTranscription))]
	[ModelReaderWriterBuildable(typeof(AudioTranscriptionOptions))]
	[ModelReaderWriterBuildable(typeof(AudioTranslation))]
	[ModelReaderWriterBuildable(typeof(AudioTranslationOptions))]
	[ModelReaderWriterBuildable(typeof(AutomaticCodeInterpreterToolContainerConfiguration))]
	[ModelReaderWriterBuildable(typeof(BatchCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(BatchJob))]
	[ModelReaderWriterBuildable(typeof(ChatAudioOptions))]
	[ModelReaderWriterBuildable(typeof(ChatCompletion))]
	[ModelReaderWriterBuildable(typeof(ChatCompletionCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(ChatCompletionDeletionResult))]
	[ModelReaderWriterBuildable(typeof(ChatCompletionMessageCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(ChatCompletionMessageListDatum))]
	[ModelReaderWriterBuildable(typeof(ChatCompletionOptions))]
	[ModelReaderWriterBuildable(typeof(ChatFunction))]
	[ModelReaderWriterBuildable(typeof(ChatFunctionCall))]
	[ModelReaderWriterBuildable(typeof(ChatFunctionChoice))]
	[ModelReaderWriterBuildable(typeof(ChatInputTokenUsageDetails))]
	[ModelReaderWriterBuildable(typeof(ChatMessage))]
	[ModelReaderWriterBuildable(typeof(ChatMessageAnnotation))]
	[ModelReaderWriterBuildable(typeof(ChatMessageContentPart))]
	[ModelReaderWriterBuildable(typeof(ChatOutputAudio))]
	[ModelReaderWriterBuildable(typeof(ChatOutputAudioReference))]
	[ModelReaderWriterBuildable(typeof(ChatOutputPrediction))]
	[ModelReaderWriterBuildable(typeof(ChatOutputTokenUsageDetails))]
	[ModelReaderWriterBuildable(typeof(ChatResponseFormat))]
	[ModelReaderWriterBuildable(typeof(ChatTokenLogProbabilityDetails))]
	[ModelReaderWriterBuildable(typeof(ChatTokenTopLogProbabilityDetails))]
	[ModelReaderWriterBuildable(typeof(ChatTokenUsage))]
	[ModelReaderWriterBuildable(typeof(ChatTool))]
	[ModelReaderWriterBuildable(typeof(ChatToolCall))]
	[ModelReaderWriterBuildable(typeof(ChatToolChoice))]
	[ModelReaderWriterBuildable(typeof(ChatWebSearchOptions))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterCallImageOutput))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterCallLogsOutput))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterCallOutput))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterCallResponseItem))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterTool))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterToolContainer))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterToolContainerConfiguration))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterToolDefinition))]
	[ModelReaderWriterBuildable(typeof(CodeInterpreterToolResources))]
	[ModelReaderWriterBuildable(typeof(ComputerCallAction))]
	[ModelReaderWriterBuildable(typeof(ComputerCallOutput))]
	[ModelReaderWriterBuildable(typeof(ComputerCallOutputResponseItem))]
	[ModelReaderWriterBuildable(typeof(ComputerCallResponseItem))]
	[ModelReaderWriterBuildable(typeof(ComputerCallSafetyCheck))]
	[ModelReaderWriterBuildable(typeof(ComputerTool))]
	[ModelReaderWriterBuildable(typeof(ContainerCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(ContainerFileCitationMessageAnnotation))]
	[ModelReaderWriterBuildable(typeof(ContainerFileCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(ContainerFileResource))]
	[ModelReaderWriterBuildable(typeof(ContainerResource))]
	[ModelReaderWriterBuildable(typeof(ContainerResourceExpiresAfter))]
	[ModelReaderWriterBuildable(typeof(ConversationContentPart))]
	[ModelReaderWriterBuildable(typeof(ConversationFunctionTool))]
	[ModelReaderWriterBuildable(typeof(ConversationInputTokenUsageDetails))]
	[ModelReaderWriterBuildable(typeof(ConversationOutputTokenUsageDetails))]
	[ModelReaderWriterBuildable(typeof(ConversationRateLimitDetailsItem))]
	[ModelReaderWriterBuildable(typeof(ConversationResponseOptions))]
	[ModelReaderWriterBuildable(typeof(ConversationSessionConfiguredUpdate))]
	[ModelReaderWriterBuildable(typeof(ConversationSessionOptions))]
	[ModelReaderWriterBuildable(typeof(ConversationSessionStartedUpdate))]
	[ModelReaderWriterBuildable(typeof(ConversationStatusDetails))]
	[ModelReaderWriterBuildable(typeof(ConversationTokenUsage))]
	[ModelReaderWriterBuildable(typeof(ConversationTool))]
	[ModelReaderWriterBuildable(typeof(CreateContainerBody))]
	[ModelReaderWriterBuildable(typeof(CreateContainerBodyExpiresAfter))]
	[ModelReaderWriterBuildable(typeof(CreateContainerFileBody))]
	[ModelReaderWriterBuildable(typeof(CreateResponseOptions))]
	[ModelReaderWriterBuildable(typeof(CustomMcpToolCallApprovalPolicy))]
	[ModelReaderWriterBuildable(typeof(DeleteContainerFileResponse))]
	[ModelReaderWriterBuildable(typeof(DeleteContainerResponse))]
	[ModelReaderWriterBuildable(typeof(DeveloperChatMessage))]
	[ModelReaderWriterBuildable(typeof(EmbeddingGenerationOptions))]
	[ModelReaderWriterBuildable(typeof(EmbeddingTokenUsage))]
	[ModelReaderWriterBuildable(typeof(FileChunkingStrategy))]
	[ModelReaderWriterBuildable(typeof(FileCitationMessageAnnotation))]
	[ModelReaderWriterBuildable(typeof(FileDeletionResult))]
	[ModelReaderWriterBuildable(typeof(FileFromStoreRemovalResult))]
	[ModelReaderWriterBuildable(typeof(FilePathMessageAnnotation))]
	[ModelReaderWriterBuildable(typeof(FileSearchCallResponseItem))]
	[ModelReaderWriterBuildable(typeof(FileSearchCallResult))]
	[ModelReaderWriterBuildable(typeof(FileSearchRankingOptions))]
	[ModelReaderWriterBuildable(typeof(FileSearchTool))]
	[ModelReaderWriterBuildable(typeof(FileSearchToolDefinition))]
	[ModelReaderWriterBuildable(typeof(FileSearchToolRankingOptions))]
	[ModelReaderWriterBuildable(typeof(FileSearchToolResources))]
	[ModelReaderWriterBuildable(typeof(FineTuneReinforcementHyperparameters))]
	[ModelReaderWriterBuildable(typeof(FineTuningCheckpoint))]
	[ModelReaderWriterBuildable(typeof(FineTuningCheckpointMetrics))]
	[ModelReaderWriterBuildable(typeof(FineTuningError))]
	[ModelReaderWriterBuildable(typeof(FineTuningEvent))]
	[ModelReaderWriterBuildable(typeof(FineTuningHyperparameters))]
	[ModelReaderWriterBuildable(typeof(FineTuningIntegration))]
	[ModelReaderWriterBuildable(typeof(FineTuningIntegrationWandbWandb))]
	[ModelReaderWriterBuildable(typeof(FineTuningOptions))]
	[ModelReaderWriterBuildable(typeof(FineTuningTrainingMethod))]
	[ModelReaderWriterBuildable(typeof(FunctionCallOutputResponseItem))]
	[ModelReaderWriterBuildable(typeof(FunctionCallResponseItem))]
	[ModelReaderWriterBuildable(typeof(FunctionChatMessage))]
	[ModelReaderWriterBuildable(typeof(FunctionTool))]
	[ModelReaderWriterBuildable(typeof(FunctionToolDefinition))]
	[ModelReaderWriterBuildable(typeof(GeneratedImage))]
	[ModelReaderWriterBuildable(typeof(GeneratedImageCollection))]
	[ModelReaderWriterBuildable(typeof(GetResponseOptions))]
	[ModelReaderWriterBuildable(typeof(Grader))]
	[ModelReaderWriterBuildable(typeof(GraderLabelModel))]
	[ModelReaderWriterBuildable(typeof(GraderMulti))]
	[ModelReaderWriterBuildable(typeof(GraderPython))]
	[ModelReaderWriterBuildable(typeof(GraderScoreModel))]
	[ModelReaderWriterBuildable(typeof(GraderStringCheck))]
	[ModelReaderWriterBuildable(typeof(GraderTextSimilarity))]
	[ModelReaderWriterBuildable(typeof(HyperparameterOptions))]
	[ModelReaderWriterBuildable(typeof(HyperparametersForDPO))]
	[ModelReaderWriterBuildable(typeof(HyperparametersForSupervised))]
	[ModelReaderWriterBuildable(typeof(ImageEditOptions))]
	[ModelReaderWriterBuildable(typeof(ImageGenerationCallResponseItem))]
	[ModelReaderWriterBuildable(typeof(ImageGenerationOptions))]
	[ModelReaderWriterBuildable(typeof(ImageGenerationTool))]
	[ModelReaderWriterBuildable(typeof(ImageGenerationToolInputImageMask))]
	[ModelReaderWriterBuildable(typeof(ImageInputTokenUsageDetails))]
	[ModelReaderWriterBuildable(typeof(ImageTokenUsage))]
	[ModelReaderWriterBuildable(typeof(ImageVariationOptions))]
	[ModelReaderWriterBuildable(typeof(InputAudioClearedUpdate))]
	[ModelReaderWriterBuildable(typeof(InputAudioCommittedUpdate))]
	[ModelReaderWriterBuildable(typeof(InputAudioSpeechFinishedUpdate))]
	[ModelReaderWriterBuildable(typeof(InputAudioSpeechStartedUpdate))]
	[ModelReaderWriterBuildable(typeof(InputAudioTranscriptionDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(InputAudioTranscriptionFailedUpdate))]
	[ModelReaderWriterBuildable(typeof(InputAudioTranscriptionFinishedUpdate))]
	[ModelReaderWriterBuildable(typeof(InputNoiseReductionOptions))]
	[ModelReaderWriterBuildable(typeof(InputTranscriptionOptions))]
	[ModelReaderWriterBuildable(typeof(InternalAddUploadPartRequest))]
	[ModelReaderWriterBuildable(typeof(InternalAssistantsNamedToolChoiceFunction))]
	[ModelReaderWriterBuildable(typeof(InternalAssistantToolsFileSearchFileSearch))]
	[ModelReaderWriterBuildable(typeof(InternalAssistantToolsFileSearchTypeOnly))]
	[ModelReaderWriterBuildable(typeof(InternalAutoChunkingStrategyRequestParam))]
	[ModelReaderWriterBuildable(typeof(InternalBatchError))]
	[ModelReaderWriterBuildable(typeof(InternalBatchErrors))]
	[ModelReaderWriterBuildable(typeof(InternalBatchRequestCounts))]
	[ModelReaderWriterBuildable(typeof(InternalBatchRequestInput))]
	[ModelReaderWriterBuildable(typeof(InternalBatchRequestOutput))]
	[ModelReaderWriterBuildable(typeof(InternalBatchRequestOutputError))]
	[ModelReaderWriterBuildable(typeof(InternalBatchRequestOutputResponse))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionFunctionCallOption))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionList))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionMessageList))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionMessageToolCallChunkFunction))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionMessageToolCallFunction))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionNamedToolChoice))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionNamedToolChoiceFunction))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionRequestMessageContentPartAudio))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionRequestMessageContentPartAudioInputAudio))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionRequestMessageContentPartFile))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionRequestMessageContentPartFileFile))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionRequestMessageContentPartImage))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionRequestMessageContentPartImageImageUrl))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionRequestMessageContentPartRefusal))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionRequestMessageContentPartText))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionResponseMessage))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionResponseMessageAnnotationUrlCitation))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionResponseMessageFunctionCall))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionStreamOptions))]
	[ModelReaderWriterBuildable(typeof(InternalChatCompletionStreamResponseDelta))]
	[ModelReaderWriterBuildable(typeof(InternalChatOutputPredictionContent))]
	[ModelReaderWriterBuildable(typeof(InternalChunkingStrategyRequestParam))]
	[ModelReaderWriterBuildable(typeof(InternalChunkingStrategyResponseParam))]
	[ModelReaderWriterBuildable(typeof(InternalCodeInterpreterToolCallItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalComparisonFilter))]
	[ModelReaderWriterBuildable(typeof(InternalComparisonFilterEquals))]
	[ModelReaderWriterBuildable(typeof(InternalComparisonFilterGreaterThan))]
	[ModelReaderWriterBuildable(typeof(InternalComparisonFilterGreaterThanOrEquals))]
	[ModelReaderWriterBuildable(typeof(InternalComparisonFilterLessThan))]
	[ModelReaderWriterBuildable(typeof(InternalComparisonFilterLessThanOrEquals))]
	[ModelReaderWriterBuildable(typeof(InternalComparisonFilterNotEquals))]
	[ModelReaderWriterBuildable(typeof(InternalCompleteUploadRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCompoundFilter))]
	[ModelReaderWriterBuildable(typeof(InternalCompoundFilterAnd))]
	[ModelReaderWriterBuildable(typeof(InternalCompoundFilterOr))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionClick))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionDoubleClick))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionDrag))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionKeyPress))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionMove))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionScreenshot))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionScroll))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionTypeKeys))]
	[ModelReaderWriterBuildable(typeof(InternalComputerActionWait))]
	[ModelReaderWriterBuildable(typeof(InternalComputerToolCallOutputItemOutputComputerScreenshot))]
	[ModelReaderWriterBuildable(typeof(InternalComputerUsePreviewToolCallItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalComputerUsePreviewToolCallOutputItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalContainerFileListResource))]
	[ModelReaderWriterBuildable(typeof(InternalContainerListResource))]
	[ModelReaderWriterBuildable(typeof(InternalConversationItemCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(InternalCoordinate))]
	[ModelReaderWriterBuildable(typeof(InternalCreateAssistantRequestToolResources))]
	[ModelReaderWriterBuildable(typeof(InternalCreateAssistantRequestToolResourcesCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalCreateBatchRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCreateChatCompletionRequestWebSearchOptionsUserLocation1))]
	[ModelReaderWriterBuildable(typeof(InternalCreateChatCompletionResponseChoice))]
	[ModelReaderWriterBuildable(typeof(InternalCreateChatCompletionResponseChoiceLogprobs))]
	[ModelReaderWriterBuildable(typeof(InternalCreateChatCompletionStreamResponseChoice))]
	[ModelReaderWriterBuildable(typeof(InternalCreateChatCompletionStreamResponseChoiceLogprobs))]
	[ModelReaderWriterBuildable(typeof(InternalCreateCompletionRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCreateCompletionResponse))]
	[ModelReaderWriterBuildable(typeof(InternalCreateCompletionResponseChoice))]
	[ModelReaderWriterBuildable(typeof(InternalCreateCompletionResponseChoiceLogprobs))]
	[ModelReaderWriterBuildable(typeof(InternalCreateEvalRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCreateEvalRunRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCreateFineTuningCheckpointPermissionRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCreateFineTuningJobRequestWandbIntegrationWandb))]
	[ModelReaderWriterBuildable(typeof(InternalCreateModerationRequestInput2))]
	[ModelReaderWriterBuildable(typeof(InternalCreateModerationRequestInput3))]
	[ModelReaderWriterBuildable(typeof(InternalCreateModerationRequestInputImageUrl))]
	[ModelReaderWriterBuildable(typeof(InternalCreateModerationResponseResultCategoryAppliedInputTypes))]
	[ModelReaderWriterBuildable(typeof(InternalCreateThreadAndRunRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCreateThreadAndRunRequestToolResources))]
	[ModelReaderWriterBuildable(typeof(InternalCreateThreadAndRunRequestToolResourcesCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalCreateThreadRequestToolResources))]
	[ModelReaderWriterBuildable(typeof(InternalCreateThreadRequestToolResourcesCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalCreateThreadRequestToolResourcesFileSearchBase))]
	[ModelReaderWriterBuildable(typeof(InternalCreateTranscriptionResponseJson))]
	[ModelReaderWriterBuildable(typeof(InternalCreateTranscriptionResponseJsonLogprob))]
	[ModelReaderWriterBuildable(typeof(InternalCreateTranscriptionResponseVerboseJson))]
	[ModelReaderWriterBuildable(typeof(InternalCreateTranslationResponseJson))]
	[ModelReaderWriterBuildable(typeof(InternalCreateUploadRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCreateVectorStoreFileBatchRequest))]
	[ModelReaderWriterBuildable(typeof(InternalCreateVectorStoreFileRequest))]
	[ModelReaderWriterBuildable(typeof(InternalDeleteEvalResponse))]
	[ModelReaderWriterBuildable(typeof(InternalDeleteEvalRunResponse))]
	[ModelReaderWriterBuildable(typeof(InternalDeleteFineTuningCheckpointPermissionResponse))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetAssistantResponseFormatJsonObject))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetAssistantResponseFormatJsonSchema))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetAssistantResponseFormatJsonSchemaJsonSchema))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetAssistantResponseFormatText))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetChatResponseFormatJsonObject))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetChatResponseFormatJsonSchema))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetChatResponseFormatJsonSchemaJsonSchema))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetChatResponseFormatText))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetCombinedAutoChunkingStrategyParam))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetCombinedOtherChunkingStrategyParam))]
	[ModelReaderWriterBuildable(typeof(InternalDotNetRealtimeLogProbProperties))]
	[ModelReaderWriterBuildable(typeof(InternalEval))]
	[ModelReaderWriterBuildable(typeof(InternalEvalApiError))]
	[ModelReaderWriterBuildable(typeof(InternalEvalCompletionsRunDataSourceParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalCompletionsRunDataSourceParamsInputMessages1))]
	[ModelReaderWriterBuildable(typeof(InternalEvalCompletionsRunDataSourceParamsInputMessages2))]
	[ModelReaderWriterBuildable(typeof(InternalEvalCompletionsRunDataSourceParamsSamplingParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalCustomDataSourceConfigParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalCustomDataSourceConfigResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalDataSourceConfigParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalDataSourceConfigResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderLabelModelParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderLabelModelParamsInput))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderLabelModelResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderPythonParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderPythonResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderScoreModelParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderScoreModelResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderStringCheckParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderTextSimilarityParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalGraderTextSimilarityResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalItem))]
	[ModelReaderWriterBuildable(typeof(InternalEvalItemContent))]
	[ModelReaderWriterBuildable(typeof(InternalEvalItemContentInputText))]
	[ModelReaderWriterBuildable(typeof(InternalEvalItemContentOutputText))]
	[ModelReaderWriterBuildable(typeof(InternalEvalJsonlRunDataSourceParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalList))]
	[ModelReaderWriterBuildable(typeof(InternalEvalLogsDataSourceConfigParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalLogsDataSourceConfigResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalResponsesRunDataSourceParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalResponsesRunDataSourceParamsInputMessages1))]
	[ModelReaderWriterBuildable(typeof(InternalEvalResponsesRunDataSourceParamsInputMessages2))]
	[ModelReaderWriterBuildable(typeof(InternalEvalResponsesRunDataSourceParamsInputMessagesTemplate1))]
	[ModelReaderWriterBuildable(typeof(InternalEvalResponsesRunDataSourceParamsSamplingParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalResponsesRunDataSourceParamsSamplingParamsText))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRun))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunDataContentSource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunDataSourceParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunDataSourceResource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunFileContentDataContentSource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunFileContentDataContentSourceContent))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunFileIdDataContentSource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunList))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunOutputItem))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunOutputItemList))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunOutputItemSample))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunOutputItemSampleInput))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunOutputItemSampleOutput))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunOutputItemSampleUsage))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunPerModelUsage))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunPerTestingCriteriaResult))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunResponsesDataContentSource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunResultCounts))]
	[ModelReaderWriterBuildable(typeof(InternalEvalRunStoredCompletionsDataContentSource))]
	[ModelReaderWriterBuildable(typeof(InternalEvalStoredCompletionsDataSourceConfigParams))]
	[ModelReaderWriterBuildable(typeof(InternalEvalStoredCompletionsDataSourceConfigResource))]
	[ModelReaderWriterBuildable(typeof(InternalFileSearchToolCallItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalFileUploadOptions))]
	[ModelReaderWriterBuildable(typeof(InternalFineTuneReinforcementMethod))]
	[ModelReaderWriterBuildable(typeof(InternalFineTuningCheckpointPermission))]
	[ModelReaderWriterBuildable(typeof(InternalFineTuningIntegration))]
	[ModelReaderWriterBuildable(typeof(InternalFineTuningIntegrationWandb))]
	[ModelReaderWriterBuildable(typeof(InternalFineTuningJob))]
	[ModelReaderWriterBuildable(typeof(InternalFineTuningJobRequestMethodDpo))]
	[ModelReaderWriterBuildable(typeof(InternalFineTuningJobRequestMethodSupervised))]
	[ModelReaderWriterBuildable(typeof(InternalFineTuningJobsPageToken))]
	[ModelReaderWriterBuildable(typeof(InternalFunctionDefinition))]
	[ModelReaderWriterBuildable(typeof(InternalFunctionToolCallItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalFunctionToolCallOutputItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalImageGenToolCallItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalImplicitUserMessage))]
	[ModelReaderWriterBuildable(typeof(InternalItemContentInputAudio))]
	[ModelReaderWriterBuildable(typeof(InternalItemContentInputFile))]
	[ModelReaderWriterBuildable(typeof(InternalItemContentInputImage))]
	[ModelReaderWriterBuildable(typeof(InternalItemContentInputText))]
	[ModelReaderWriterBuildable(typeof(InternalItemContentOutputAudio))]
	[ModelReaderWriterBuildable(typeof(InternalItemContentOutputText))]
	[ModelReaderWriterBuildable(typeof(InternalItemContentRefusal))]
	[ModelReaderWriterBuildable(typeof(InternalItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalItemReferenceItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalListAssistantsResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListBatchesResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListFineTuningCheckpointPermissionResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListFineTuningJobCheckpointsResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListFineTuningJobEventsResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListMessagesResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListPaginatedFineTuningJobsResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListRunsResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListRunStepsResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListVectorStoreFilesResponse))]
	[ModelReaderWriterBuildable(typeof(InternalListVectorStoresResponse))]
	[ModelReaderWriterBuildable(typeof(InternalLocalShellExecAction))]
	[ModelReaderWriterBuildable(typeof(InternalLocalShellTool))]
	[ModelReaderWriterBuildable(typeof(InternalLocalShellToolCallItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalLocalShellToolCallItemResource))]
	[ModelReaderWriterBuildable(typeof(InternalLocalShellToolCallOutputItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalLocalShellToolCallOutputItemResource))]
	[ModelReaderWriterBuildable(typeof(InternalLogProb))]
	[ModelReaderWriterBuildable(typeof(InternalLogProbProperties))]
	[ModelReaderWriterBuildable(typeof(InternalMCPApprovalRequestItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalMCPApprovalResponseItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalMCPCallItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalMCPListToolsItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalMCPToolRequireApproval1))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentImageFileObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentImageUrlObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentImageUrlObjectImageUrl))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentItemFileObjectImageFile))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentRefusalObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentTextAnnotationsFileCitationObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentTextAnnotationsFileCitationObjectFileCitation))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentTextAnnotationsFilePathObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentTextAnnotationsFilePathObjectFilePath))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentTextObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentTextObjectAnnotation))]
	[ModelReaderWriterBuildable(typeof(InternalMessageContentTextObjectText1))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContent))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentImageFileObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentImageFileObjectImageFile))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentImageUrlObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentImageUrlObjectImageUrl))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentRefusalObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentTextAnnotationsFileCitationObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentTextAnnotationsFileCitationObjectFileCitation))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentTextAnnotationsFilePathObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentTextAnnotationsFilePathObjectFilePath))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentTextObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaContentTextObjectText))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaObject))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaObjectDelta))]
	[ModelReaderWriterBuildable(typeof(InternalMessageDeltaTextContentAnnotation))]
	[ModelReaderWriterBuildable(typeof(InternalMessageObjectAttachment))]
	[ModelReaderWriterBuildable(typeof(InternalMetadataPropertyForRequest))]
	[ModelReaderWriterBuildable(typeof(InternalModerationCategories))]
	[ModelReaderWriterBuildable(typeof(InternalModerationCategoryScores))]
	[ModelReaderWriterBuildable(typeof(InternalModifyAssistantRequestToolResources))]
	[ModelReaderWriterBuildable(typeof(InternalModifyAssistantRequestToolResourcesCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalModifyThreadRequestToolResources))]
	[ModelReaderWriterBuildable(typeof(InternalModifyThreadRequestToolResourcesCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalOtherChunkingStrategyResponseParam))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeAudioFarFieldNoiseReduction))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeAudioNearFieldNoiseReduction))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEvent))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventConversationItemCreate))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventConversationItemDelete))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventConversationItemRetrieve))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventConversationItemTruncate))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventInputAudioBufferAppend))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventInputAudioBufferClear))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventInputAudioBufferCommit))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventOutputAudioBufferClear))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventResponseCancel))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventResponseCreate))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventSessionUpdate))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeClientEventTranscriptionSessionUpdate))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeRequestAssistantMessageItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeRequestAudioContentPart))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeRequestFunctionCallItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeRequestFunctionCallOutputItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeRequestMessageItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeRequestSystemMessageItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeRequestTextContentPart))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeRequestUserMessageItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponse))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponseAudioContentPart))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponseFunctionCallItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponseFunctionCallOutputItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponseItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponseMessageItem))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponseSession))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponseStatusDetailsError))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeResponseTextContentPart))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSemanticVadTurnDetection))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventConversationCreated))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventConversationCreatedConversation))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventConversationItemInputAudioTranscriptionFailedError))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventErrorError))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventOutputAudioBufferCleared))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventOutputAudioBufferStarted))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventOutputAudioBufferStopped))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventResponseAudioDelta))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventResponseAudioTranscriptDelta))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventResponseContentPartAdded))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventResponseContentPartDone))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventResponseFunctionCallArgumentsDelta))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventResponseFunctionCallArgumentsDone))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerEventResponseTextDelta))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeServerVadTurnDetection))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateRequest))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateRequestClientSecret))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateRequestClientSecretExpiresAt))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateRequestInputAudioNoiseReduction1))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateRequestInputAudioTranscription))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateRequestTracing1))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateRequestTurnDetection))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateResponse))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateResponseClientSecret))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateResponseInputAudioTranscription))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateResponseTracing1))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeSessionCreateResponseTurnDetection))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeToolChoiceFunctionObject))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeToolChoiceFunctionObjectFunction))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeToolChoiceObject))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateRequestClientSecret))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateRequestClientSecretExpiresAt))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateRequestInputAudioNoiseReduction1))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateRequestInputAudioTranscription))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateRequestTurnDetection))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateResponse))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateResponseClientSecret))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateResponseInputAudioTranscription))]
	[ModelReaderWriterBuildable(typeof(InternalRealtimeTranscriptionSessionCreateResponseTurnDetection))]
	[ModelReaderWriterBuildable(typeof(InternalReasoningItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalRequiredFunctionToolCall))]
	[ModelReaderWriterBuildable(typeof(InternalResponseErrorResponse))]
	[ModelReaderWriterBuildable(typeof(InternalResponseFormat))]
	[ModelReaderWriterBuildable(typeof(InternalResponseFormatJsonObject))]
	[ModelReaderWriterBuildable(typeof(InternalResponseFormatJsonSchema))]
	[ModelReaderWriterBuildable(typeof(InternalResponseFormatJsonSchemaJsonSchema))]
	[ModelReaderWriterBuildable(typeof(InternalResponseFormatJsonSchemaSchema))]
	[ModelReaderWriterBuildable(typeof(InternalResponseFormatText))]
	[ModelReaderWriterBuildable(typeof(InternalResponseReasoningDeltaEvent))]
	[ModelReaderWriterBuildable(typeof(InternalResponseReasoningDoneEvent))]
	[ModelReaderWriterBuildable(typeof(InternalResponseReasoningSummaryDeltaEvent))]
	[ModelReaderWriterBuildable(typeof(InternalResponseReasoningSummaryDoneEvent))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesAssistantMessage))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesAssistantMessageItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesDeveloperMessage))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesDeveloperMessageItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesMessageItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesSystemMessage))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesSystemMessageItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesTextFormatJsonObject))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesTextFormatJsonSchema))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesTextFormatText))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesUserMessage))]
	[ModelReaderWriterBuildable(typeof(InternalResponsesUserMessageItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalRunObjectRequiredActionSubmitToolOutputs))]
	[ModelReaderWriterBuildable(typeof(InternalRunRequiredAction))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepCodeInterpreterLogOutput))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDelta))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaObjectDelta))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetails))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsMessageCreationObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsMessageCreationObjectMessageCreation))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsCodeObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsCodeObjectCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsCodeOutputImageObjectImage))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsCodeOutputLogsObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsFileSearchObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsFileSearchObjectFileSearch))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsFunctionObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsFunctionObjectFunction))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDeltaStepDetailsToolCallsObjectToolCallsObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsMessageCreationObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsMessageCreationObjectMessageCreation))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsCodeObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsCodeObjectCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsCodeOutputImageObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsCodeOutputImageObjectImage))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsFileSearchObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsFileSearchObjectFileSearch))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsFileSearchRankingOptionsObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsFunctionObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsFunctionObjectFunction))]
	[ModelReaderWriterBuildable(typeof(InternalRunStepDetailsToolCallsObject))]
	[ModelReaderWriterBuildable(typeof(InternalRunToolCallObjectFunction))]
	[ModelReaderWriterBuildable(typeof(InternalStaticChunkingStrategy))]
	[ModelReaderWriterBuildable(typeof(InternalStaticChunkingStrategyRequestParam))]
	[ModelReaderWriterBuildable(typeof(InternalStaticChunkingStrategyResponseParam))]
	[ModelReaderWriterBuildable(typeof(InternalSubmitToolOutputsRunRequest))]
	[ModelReaderWriterBuildable(typeof(InternalThreadObjectToolResources))]
	[ModelReaderWriterBuildable(typeof(InternalThreadObjectToolResourcesCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalThreadObjectToolResourcesFileSearch))]
	[ModelReaderWriterBuildable(typeof(InternalTodoFineTuneChatRequestInput))]
	[ModelReaderWriterBuildable(typeof(InternalToolChoiceObject))]
	[ModelReaderWriterBuildable(typeof(InternalToolChoiceObjectCodeInterpreter))]
	[ModelReaderWriterBuildable(typeof(InternalToolChoiceObjectComputer))]
	[ModelReaderWriterBuildable(typeof(InternalToolChoiceObjectFileSearch))]
	[ModelReaderWriterBuildable(typeof(InternalToolChoiceObjectFunction))]
	[ModelReaderWriterBuildable(typeof(InternalToolChoiceObjectImageGen))]
	[ModelReaderWriterBuildable(typeof(InternalToolChoiceObjectMCP))]
	[ModelReaderWriterBuildable(typeof(InternalToolChoiceObjectWebSearch))]
	[ModelReaderWriterBuildable(typeof(InternalToolResourcesFileSearchIdsOnly))]
	[ModelReaderWriterBuildable(typeof(InternalTopLogProb))]
	[ModelReaderWriterBuildable(typeof(InternalTranscriptTextDeltaEventLogprob))]
	[ModelReaderWriterBuildable(typeof(InternalTranscriptTextDoneEventLogprob))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownAnnotation))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownChatCompletionRequestMessageContentPart))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownChatMessage))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownChatOutputPrediction))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownChatResponseFormat))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownChunkingStrategyRequestParamProxy))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownChunkingStrategyResponseParam))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownCodeInterpreterContainerConfiguration))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownCodeInterpreterToolOutput))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownComparisonFilter))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownCompoundFilter))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownComputerAction))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownComputerToolCallOutputItemOutput))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownCreateTranscriptionResponseStreamEvent))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownDotNetAssistantResponseFormat))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownDotNetCombinedChunkingStrategyParam))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownEvalDataSourceConfigParams))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownEvalDataSourceConfigResource))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownEvalGraderParams))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownEvalGraderResource))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownEvalItemContent))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownEvalRunDataContentSource))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownEvalRunDataSourceParams))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownItemContent))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownItemResource))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownLocation))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownMessageContent))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownRealtimeAudioNoiseReduction))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownReasoningItemSummaryPart))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownResponseFormat))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownResponsesMessageItemResource))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownResponsesMessageItemResourceItemParam))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownResponseTextFormatConfiguration))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownTool))]
	[ModelReaderWriterBuildable(typeof(InternalUnknownToolChoiceObject))]
	[ModelReaderWriterBuildable(typeof(InternalUpdateChatCompletionRequest))]
	[ModelReaderWriterBuildable(typeof(InternalUpdateEvalRequest))]
	[ModelReaderWriterBuildable(typeof(InternalUpdateVectorStoreFileAttributesRequest))]
	[ModelReaderWriterBuildable(typeof(InternalUpload))]
	[ModelReaderWriterBuildable(typeof(InternalUploadPart))]
	[ModelReaderWriterBuildable(typeof(InternalVadConfig))]
	[ModelReaderWriterBuildable(typeof(InternalVectorStoreFileBatchObjectFileCounts))]
	[ModelReaderWriterBuildable(typeof(InternalVectorStoreFileContentResponse))]
	[ModelReaderWriterBuildable(typeof(InternalVectorStoreFileContentResponseDatum))]
	[ModelReaderWriterBuildable(typeof(InternalVectorStoreSearchRequest))]
	[ModelReaderWriterBuildable(typeof(InternalVectorStoreSearchRequestRankingOptions))]
	[ModelReaderWriterBuildable(typeof(InternalVectorStoreSearchResultContentObject))]
	[ModelReaderWriterBuildable(typeof(InternalVectorStoreSearchResultItem))]
	[ModelReaderWriterBuildable(typeof(InternalVectorStoreSearchResultsPage))]
	[ModelReaderWriterBuildable(typeof(InternalWebSearchLocation))]
	[ModelReaderWriterBuildable(typeof(InternalWebSearchToolCallItemParam))]
	[ModelReaderWriterBuildable(typeof(InternaVideoCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(ItemCreatedUpdate))]
	[ModelReaderWriterBuildable(typeof(ItemDeletedUpdate))]
	[ModelReaderWriterBuildable(typeof(ItemRetrievedUpdate))]
	[ModelReaderWriterBuildable(typeof(ItemTruncatedUpdate))]
	[ModelReaderWriterBuildable(typeof(McpTool))]
	[ModelReaderWriterBuildable(typeof(McpToolCallApprovalPolicy))]
	[ModelReaderWriterBuildable(typeof(McpToolCallApprovalRequestItem))]
	[ModelReaderWriterBuildable(typeof(McpToolCallApprovalResponseItem))]
	[ModelReaderWriterBuildable(typeof(McpToolCallItem))]
	[ModelReaderWriterBuildable(typeof(McpToolDefinition))]
	[ModelReaderWriterBuildable(typeof(McpToolDefinitionListItem))]
	[ModelReaderWriterBuildable(typeof(McpToolFilter))]
	[ModelReaderWriterBuildable(typeof(MessageCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(MessageContent))]
	[ModelReaderWriterBuildable(typeof(MessageCreationAttachment))]
	[ModelReaderWriterBuildable(typeof(MessageCreationOptions))]
	[ModelReaderWriterBuildable(typeof(MessageDeletionResult))]
	[ModelReaderWriterBuildable(typeof(MessageFailureDetails))]
	[ModelReaderWriterBuildable(typeof(MessageModificationOptions))]
	[ModelReaderWriterBuildable(typeof(MessageResponseItem))]
	[ModelReaderWriterBuildable(typeof(ModelDeletionResult))]
	[ModelReaderWriterBuildable(typeof(ModerationOptions))]
	[ModelReaderWriterBuildable(typeof(ModerationResult))]
	[ModelReaderWriterBuildable(typeof(ModerationResultCollection))]
	[ModelReaderWriterBuildable(typeof(OpenAIEmbedding))]
	[ModelReaderWriterBuildable(typeof(OpenAIEmbeddingCollection))]
	[ModelReaderWriterBuildable(typeof(OpenAIError))]
	[ModelReaderWriterBuildable(typeof(OpenAIErrorResponse))]
	[ModelReaderWriterBuildable(typeof(OpenAIFile))]
	[ModelReaderWriterBuildable(typeof(OpenAIFileCollection))]
	[ModelReaderWriterBuildable(typeof(OpenAIModel))]
	[ModelReaderWriterBuildable(typeof(OpenAIModelCollection))]
	[ModelReaderWriterBuildable(typeof(OutputAudioFinishedUpdate))]
	[ModelReaderWriterBuildable(typeof(OutputAudioTranscriptionFinishedUpdate))]
	[ModelReaderWriterBuildable(typeof(OutputStreamingFinishedUpdate))]
	[ModelReaderWriterBuildable(typeof(OutputStreamingStartedUpdate))]
	[ModelReaderWriterBuildable(typeof(OutputTextFinishedUpdate))]
	[ModelReaderWriterBuildable(typeof(RateLimitsUpdate))]
	[ModelReaderWriterBuildable(typeof(RealtimeErrorUpdate))]
	[ModelReaderWriterBuildable(typeof(RealtimeItem))]
	[ModelReaderWriterBuildable(typeof(RealtimeUpdate))]
	[ModelReaderWriterBuildable(typeof(ReasoningResponseItem))]
	[ModelReaderWriterBuildable(typeof(ReasoningSummaryPart))]
	[ModelReaderWriterBuildable(typeof(ReasoningSummaryTextPart))]
	[ModelReaderWriterBuildable(typeof(ReferenceResponseItem))]
	[ModelReaderWriterBuildable(typeof(ResponseContentPart))]
	[ModelReaderWriterBuildable(typeof(ResponseConversationOptions))]
	[ModelReaderWriterBuildable(typeof(ResponseDeletionResult))]
	[ModelReaderWriterBuildable(typeof(ResponseError))]
	[ModelReaderWriterBuildable(typeof(ResponseFinishedUpdate))]
	[ModelReaderWriterBuildable(typeof(ResponseIncompleteStatusDetails))]
	[ModelReaderWriterBuildable(typeof(ResponseInputTokenUsageDetails))]
	[ModelReaderWriterBuildable(typeof(ResponseItem))]
	[ModelReaderWriterBuildable(typeof(ResponseItemCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(ResponseItemCollectionPage))]
	[ModelReaderWriterBuildable(typeof(ResponseMessageAnnotation))]
	[ModelReaderWriterBuildable(typeof(ResponseOutputTokenUsageDetails))]
	[ModelReaderWriterBuildable(typeof(ResponseReasoningOptions))]
	[ModelReaderWriterBuildable(typeof(ResponseResult))]
	[ModelReaderWriterBuildable(typeof(ResponseStartedUpdate))]
	[ModelReaderWriterBuildable(typeof(ResponseTextFormat))]
	[ModelReaderWriterBuildable(typeof(ResponseTextOptions))]
	[ModelReaderWriterBuildable(typeof(ResponseTokenUsage))]
	[ModelReaderWriterBuildable(typeof(ResponseTool))]
	[ModelReaderWriterBuildable(typeof(RunCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(RunCreationOptions))]
	[ModelReaderWriterBuildable(typeof(RunError))]
	[ModelReaderWriterBuildable(typeof(RunGraderRequest))]
	[ModelReaderWriterBuildable(typeof(RunGraderResponse))]
	[ModelReaderWriterBuildable(typeof(RunGraderResponseMetadata))]
	[ModelReaderWriterBuildable(typeof(RunGraderResponseMetadataErrors))]
	[ModelReaderWriterBuildable(typeof(RunIncompleteDetails))]
	[ModelReaderWriterBuildable(typeof(RunModificationOptions))]
	[ModelReaderWriterBuildable(typeof(RunStep))]
	[ModelReaderWriterBuildable(typeof(RunStepCodeInterpreterOutput))]
	[ModelReaderWriterBuildable(typeof(RunStepCollectionOptions))]
	[ModelReaderWriterBuildable(typeof(RunStepDetails))]
	[ModelReaderWriterBuildable(typeof(RunStepError))]
	[ModelReaderWriterBuildable(typeof(RunStepFileSearchResult))]
	[ModelReaderWriterBuildable(typeof(RunStepFileSearchResultContent))]
	[ModelReaderWriterBuildable(typeof(RunStepTokenUsage))]
	[ModelReaderWriterBuildable(typeof(RunStepToolCall))]
	[ModelReaderWriterBuildable(typeof(RunStepUpdateCodeInterpreterOutput))]
	[ModelReaderWriterBuildable(typeof(RunTokenUsage))]
	[ModelReaderWriterBuildable(typeof(RunTruncationStrategy))]
	[ModelReaderWriterBuildable(typeof(SpeechGenerationOptions))]
	[ModelReaderWriterBuildable(typeof(StaticFileChunkingStrategy))]
	[ModelReaderWriterBuildable(typeof(StreamingAudioTranscriptionTextDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingAudioTranscriptionTextDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingAudioTranscriptionUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingChatCompletionUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingChatFunctionCallUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingChatOutputAudioUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingChatToolCallUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseCodeInterpreterCallCodeDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseCodeInterpreterCallCodeDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseCodeInterpreterCallCompletedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseCodeInterpreterCallInProgressUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseCodeInterpreterCallInterpretingUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseCompletedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseContentPartAddedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseContentPartDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseCreatedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseErrorUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseFailedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseFileSearchCallCompletedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseFileSearchCallInProgressUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseFileSearchCallSearchingUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseFunctionCallArgumentsDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseFunctionCallArgumentsDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseImageGenerationCallCompletedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseImageGenerationCallGeneratingUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseImageGenerationCallInProgressUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseImageGenerationCallPartialImageUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseIncompleteUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseInProgressUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseMcpCallArgumentsDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseMcpCallArgumentsDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseMcpCallCompletedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseMcpCallFailedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseMcpCallInProgressUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseMcpListToolsCompletedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseMcpListToolsFailedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseMcpListToolsInProgressUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseOutputItemAddedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseOutputItemDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseOutputTextDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseOutputTextDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseQueuedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseReasoningSummaryPartAddedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseReasoningSummaryPartDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseReasoningSummaryTextDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseReasoningSummaryTextDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseReasoningTextDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseReasoningTextDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseRefusalDeltaUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseRefusalDoneUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseTextAnnotationAddedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseWebSearchCallCompletedUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseWebSearchCallInProgressUpdate))]
	[ModelReaderWriterBuildable(typeof(StreamingResponseWebSearchCallSearchingUpdate))]
	[ModelReaderWriterBuildable(typeof(SystemChatMessage))]
	[ModelReaderWriterBuildable(typeof(ThreadCreationOptions))]
	[ModelReaderWriterBuildable(typeof(ThreadDeletionResult))]
	[ModelReaderWriterBuildable(typeof(ThreadMessage))]
	[ModelReaderWriterBuildable(typeof(ThreadModificationOptions))]
	[ModelReaderWriterBuildable(typeof(ThreadRun))]
	[ModelReaderWriterBuildable(typeof(ToolChatMessage))]
	[ModelReaderWriterBuildable(typeof(ToolConstraint))]
	[ModelReaderWriterBuildable(typeof(ToolDefinition))]
	[ModelReaderWriterBuildable(typeof(ToolOutput))]
	[ModelReaderWriterBuildable(typeof(ToolResources))]
	[ModelReaderWriterBuildable(typeof(TranscribedSegment))]
	[ModelReaderWriterBuildable(typeof(TranscribedWord))]
	[ModelReaderWriterBuildable(typeof(TranscriptionSessionConfiguredUpdate))]
	[ModelReaderWriterBuildable(typeof(TranscriptionSessionOptions))]
	[ModelReaderWriterBuildable(typeof(TurnDetectionOptions))]
	[ModelReaderWriterBuildable(typeof(UnknownAssistantToolDefinition))]
	[ModelReaderWriterBuildable(typeof(UnknownCreateFineTuningJobRequestIntegration))]
	[ModelReaderWriterBuildable(typeof(UnknownFineTuningIntegration))]
	[ModelReaderWriterBuildable(typeof(UnknownGrader))]
	[ModelReaderWriterBuildable(typeof(UnknownMessageContentTextObjectAnnotation))]
	[ModelReaderWriterBuildable(typeof(UnknownMessageDeltaContent))]
	[ModelReaderWriterBuildable(typeof(UnknownMessageDeltaTextContentAnnotation))]
	[ModelReaderWriterBuildable(typeof(UnknownRealtimeClientEvent))]
	[ModelReaderWriterBuildable(typeof(UnknownRealtimeContentPart))]
	[ModelReaderWriterBuildable(typeof(UnknownRealtimeRequestItem))]
	[ModelReaderWriterBuildable(typeof(UnknownRealtimeRequestMessageItem))]
	[ModelReaderWriterBuildable(typeof(UnknownRealtimeResponseItem))]
	[ModelReaderWriterBuildable(typeof(UnknownRealtimeServerEvent))]
	[ModelReaderWriterBuildable(typeof(UnknownRealtimeTool))]
	[ModelReaderWriterBuildable(typeof(UnknownRealtimeToolChoiceObject))]
	[ModelReaderWriterBui

BepInEx/core/System.Buffers.dll

Decompiled 2 weeks ago
using System.Buffers;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Buffers")]
[assembly: AssemblyDescription("System.Buffers")]
[assembly: AssemblyDefaultAlias("System.Buffers")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("4.0.99.0")]
[assembly: AssemblyFileVersion("4.0.99.0")]
[assembly: AssemblyVersion("4.0.99.0")]
[assembly: TypeForwardedTo(typeof(ArrayPool<>))]

BepInEx/core/System.ClientModel.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Text;
using System.ClientModel.Internal;
using System.ClientModel.Primitives;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Logging;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.ClientModel.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")]
[assembly: InternalsVisibleTo("System.ClientModel.Tests.Internal, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")]
[assembly: InternalsVisibleTo("System.ClientModel.Tests.Internal.Perf, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d15ddcb29688295338af4b7686603fe614abd555e09efba8fb88ee09e1f7b1ccaeed2e8f823fa9eef3fdd60217fc012ea67d2479751a0b8c087a4185541b851bd8b16f8d91b840e51b1cb0ba6fe647997e57429265e85ef62d565db50a69ae1647d54d7bd855e4db3d8a91510e5bcbd0edfbbecaa20a7bd9ae74593daa7b11b4")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Contains building blocks for clients that call cloud services.")]
[assembly: AssemblyFileVersion("1.800.125.56003")]
[assembly: AssemblyInformationalVersion("1.8.1+8009447c9a15f1a8256bf98960fa67217961719d")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyTitle("System.ClientModel")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/Azure/azure-sdk-for-net")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("1.8.1.0")]
[module: RefSafetyRules(11)]
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
	{
	}
	[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;
		}
	}
}
[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
[EditorBrowsable(EditorBrowsableState.Never)]
internal static class __LoggerMessageGenerator
{
	public static string Enumerate(IEnumerable? enumerable)
	{
		if (enumerable == null)
		{
			return "(null)";
		}
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.Append('[');
		bool flag = true;
		foreach (object item in enumerable)
		{
			if (!flag)
			{
				stringBuilder.Append(", ");
			}
			if (item == null)
			{
				stringBuilder.Append("(null)");
			}
			else if (item is IFormattable formattable)
			{
				stringBuilder.Append(formattable.ToString(null, CultureInfo.InvariantCulture));
			}
			else
			{
				stringBuilder.Append(item);
			}
			flag = false;
		}
		stringBuilder.Append(']');
		return stringBuilder.ToString();
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	internal sealed class ExperimentalAttribute : Attribute
	{
		public string DiagnosticId { get; }

		public string? UrlFormat { get; set; }

		public ExperimentalAttribute(string diagnosticId)
		{
			DiagnosticId = diagnosticId;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string? Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string? Scope { get; set; }

		public string? Target { get; set; }

		public string? MessageId { get; set; }

		public string? Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class DynamicDependencyAttribute : Attribute
	{
		public string? MemberSignature { get; }

		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public Type? Type { get; }

		public string? TypeName { get; }

		public string? AssemblyName { get; }

		public string? Condition { get; set; }

		public DynamicDependencyAttribute(string memberSignature)
		{
			MemberSignature = memberSignature;
		}

		public DynamicDependencyAttribute(string memberSignature, Type type)
		{
			MemberSignature = memberSignature;
			Type = type;
		}

		public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName)
		{
			MemberSignature = memberSignature;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type)
		{
			MemberTypes = memberTypes;
			Type = type;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName)
		{
			MemberTypes = memberTypes;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000,
		All = -1
	}
}
namespace System.ClientModel
{
	public abstract class AuthenticationTokenProvider
	{
		public abstract GetTokenOptions? CreateTokenOptions(IReadOnlyDictionary<string, object> properties);

		public abstract AuthenticationToken GetToken(GetTokenOptions options, CancellationToken cancellationToken);

		public abstract ValueTask<AuthenticationToken> GetTokenAsync(GetTokenOptions options, CancellationToken cancellationToken);
	}
	public class ApiKeyCredential
	{
		private string _key;

		public ApiKeyCredential(string key)
		{
			Update(key);
		}

		public void Deconstruct(out string key)
		{
			key = Volatile.Read(ref _key);
		}

		public void Update(string key)
		{
			Argument.AssertNotNullOrEmpty(key, "key");
			Volatile.Write(ref _key, key);
		}
	}
	public abstract class AsyncCollectionResult<T> : AsyncCollectionResult, IAsyncEnumerable<T>
	{
		protected internal AsyncCollectionResult()
		{
		}

		public async IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken = default(CancellationToken))
		{
			await foreach (ClientResult item in GetRawPagesAsync().ConfigureAwait(continueOnCapturedContext: false).WithCancellation(cancellationToken))
			{
				await foreach (T item2 in GetValuesFromPageAsync(item).ConfigureAwait(continueOnCapturedContext: false).WithCancellation(cancellationToken))
				{
					yield return item2;
				}
			}
		}

		protected abstract IAsyncEnumerable<T> GetValuesFromPageAsync(ClientResult page);
	}
	public class ClientResult
	{
		private readonly PipelineResponse _response;

		protected ClientResult(PipelineResponse response)
		{
			Argument.AssertNotNull(response, "response");
			_response = response;
		}

		public PipelineResponse GetRawResponse()
		{
			return _response;
		}

		public static ClientResult FromResponse(PipelineResponse response)
		{
			Argument.AssertNotNull(response, "response");
			return new ClientResult(response);
		}

		public static ClientResult<T> FromValue<T>(T value, PipelineResponse response)
		{
			Argument.AssertNotNull(response, "response");
			if (value == null)
			{
				string message = "ClientResult<T> contract guarantees that ClientResult<T>.Value is non-null. If you need to return a ClientResult where the Value is null, please use ClientResult.FromOptionalValue instead.";
				throw new ArgumentNullException("value", message);
			}
			return new ClientResult<T>(value, response);
		}

		public static ClientResult<T?> FromOptionalValue<T>(T? value, PipelineResponse response)
		{
			Argument.AssertNotNull(response, "response");
			return new ClientResult<T>(value, response);
		}
	}
	public class ClientResultException : Exception
	{
		private const string DefaultMessage = "Service request failed.";

		private readonly PipelineResponse? _response;

		private int _status;

		public int Status
		{
			get
			{
				return _status;
			}
			protected set
			{
				_status = value;
			}
		}

		public static async Task<ClientResultException> CreateAsync(PipelineResponse response, Exception? innerException = null)
		{
			Argument.AssertNotNull(response, "response");
			return new ClientResultException(await CreateMessageAsync(response).ConfigureAwait(continueOnCapturedContext: false), response, innerException);
		}

		public ClientResultException(PipelineResponse response, Exception? innerException = null)
			: base(CreateMessage(response), innerException)
		{
			Argument.AssertNotNull(response, "response");
			_response = response;
			_status = response.Status;
		}

		public ClientResultException(string message, PipelineResponse? response = null, Exception? innerException = null)
			: base(message, innerException)
		{
			Argument.AssertNotNull(message, "message");
			_response = response;
			_status = response?.Status ?? 0;
		}

		public PipelineResponse? GetRawResponse()
		{
			return _response;
		}

		private static string CreateMessage(PipelineResponse response)
		{
			return CreateMessageSyncOrAsync(response, async: false).EnsureCompleted();
		}

		private static async ValueTask<string> CreateMessageAsync(PipelineResponse response)
		{
			return await CreateMessageSyncOrAsync(response, async: true).ConfigureAwait(continueOnCapturedContext: false);
		}

		private static async ValueTask<string> CreateMessageSyncOrAsync(PipelineResponse response, bool async)
		{
			Argument.AssertNotNull(response, "response");
			if (async)
			{
				await response.BufferContentAsync().ConfigureAwait(continueOnCapturedContext: false);
			}
			else
			{
				response.BufferContent();
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine("Service request failed.").Append("Status: ").Append(response.Status.ToString(CultureInfo.InvariantCulture));
			if (!string.IsNullOrEmpty(response.ReasonPhrase))
			{
				stringBuilder.Append(" (").Append(response.ReasonPhrase).AppendLine(")");
			}
			else
			{
				stringBuilder.AppendLine();
			}
			return stringBuilder.ToString();
		}
	}
	public class ClientResult<T> : ClientResult
	{
		public virtual T Value { get; }

		protected internal ClientResult(T value, PipelineResponse response)
			: base(response)
		{
			Value = value;
		}

		public static implicit operator T(ClientResult<T> result)
		{
			if (result == null)
			{
				throw new ArgumentNullException("result", $"The implicit cast from ClientResult<{typeof(T)}> to {typeof(T)} failed because the ClientResult<{typeof(T)}> was null.");
			}
			return result.Value;
		}
	}
	public abstract class CollectionResult<T> : CollectionResult, IEnumerable<T>, IEnumerable
	{
		[CompilerGenerated]
		private sealed class <GetEnumerator>d__1 : IEnumerator<T>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private T <>2__current;

			public CollectionResult<T> <>4__this;

			private IEnumerator<ClientResult> <>7__wrap1;

			private IEnumerator<T> <>7__wrap2;

			T IEnumerator<T>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

			[DebuggerHidden]
			public <GetEnumerator>d__1(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				int num = <>1__state;
				if ((uint)(num - -4) <= 1u || num == 1)
				{
					try
					{
						if (num == -4 || num == 1)
						{
							try
							{
							}
							finally
							{
								<>m__Finally2();
							}
						}
					}
					finally
					{
						<>m__Finally1();
					}
				}
				<>7__wrap1 = null;
				<>7__wrap2 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				try
				{
					int num = <>1__state;
					CollectionResult<T> collectionResult = <>4__this;
					if (num != 0)
					{
						if (num != 1)
						{
							return false;
						}
						<>1__state = -4;
						goto IL_008e;
					}
					<>1__state = -1;
					<>7__wrap1 = collectionResult.GetRawPages().GetEnumerator();
					<>1__state = -3;
					goto IL_00a8;
					IL_008e:
					if (<>7__wrap2.MoveNext())
					{
						T current = <>7__wrap2.Current;
						<>2__current = current;
						<>1__state = 1;
						return true;
					}
					<>m__Finally2();
					<>7__wrap2 = null;
					goto IL_00a8;
					IL_00a8:
					if (<>7__wrap1.MoveNext())
					{
						ClientResult current2 = <>7__wrap1.Current;
						<>7__wrap2 = collectionResult.GetValuesFromPage(current2).GetEnumerator();
						<>1__state = -4;
						goto IL_008e;
					}
					<>m__Finally1();
					<>7__wrap1 = null;
					return false;
				}
				catch
				{
					//try-fault
					((IDisposable)this).Dispose();
					throw;
				}
			}

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

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

			private void <>m__Finally2()
			{
				<>1__state = -3;
				if (<>7__wrap2 != null)
				{
					<>7__wrap2.Dispose();
				}
			}

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		protected internal CollectionResult()
		{
		}

		[IteratorStateMachine(typeof(CollectionResult<>.<GetEnumerator>d__1))]
		public IEnumerator<T> GetEnumerator()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetEnumerator>d__1(0)
			{
				<>4__this = this
			};
		}

		protected abstract IEnumerable<T> GetValuesFromPage(ClientResult page);

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	public class ContinuationToken
	{
		private readonly BinaryData? _bytes;

		protected ContinuationToken()
		{
		}

		protected ContinuationToken(BinaryData bytes)
		{
			Argument.AssertNotNull<BinaryData>(bytes, "bytes");
			_bytes = bytes;
		}

		public static ContinuationToken FromBytes(BinaryData bytes)
		{
			return new ContinuationToken(bytes);
		}

		public virtual BinaryData ToBytes()
		{
			return _bytes ?? throw new InvalidOperationException("Unable to write token as bytes.");
		}
	}
	public abstract class BinaryContent : IDisposable
	{
		private sealed class BinaryDataBinaryContent : BinaryContent
		{
			private readonly ReadOnlyMemory<byte> _bytes;

			public BinaryDataBinaryContent(ReadOnlyMemory<byte> bytes, string? mediaType = null)
			{
				_bytes = bytes;
				base.MediaType = mediaType;
			}

			public override bool TryComputeLength(out long length)
			{
				length = _bytes.Length;
				return true;
			}

			public override void WriteTo(Stream stream, CancellationToken cancellation)
			{
				Argument.AssertNotNull(stream, "stream");
				byte[] array = _bytes.ToArray();
				stream.Write(array, 0, array.Length);
			}

			public override async Task WriteToAsync(Stream stream, CancellationToken cancellation)
			{
				Argument.AssertNotNull(stream, "stream");
				await StreamExtensions.WriteAsync(stream, _bytes, cancellation).ConfigureAwait(continueOnCapturedContext: false);
			}

			public override void Dispose()
			{
			}
		}

		private sealed class ModelBinaryContent<T> : BinaryContent where T : IPersistableModel<T>
		{
			private readonly T _model;

			private readonly ModelReaderWriterOptions _options;

			private UnsafeBufferSequence.Reader? _sequenceReader;

			private BinaryData? _data;

			private byte[]? _bytes;

			private UnsafeBufferSequence.Reader SequenceReader
			{
				get
				{
					if (!((object)_model is IJsonModel<T> model))
					{
						throw new InvalidOperationException("Cannot use Writer with non-IJsonModel model type.");
					}
					if (_sequenceReader == null)
					{
						_sequenceReader = new ModelWriter<T>(model, _options).ExtractReader();
					}
					return _sequenceReader;
				}
			}

			private BinaryData Data
			{
				get
				{
					if (ModelReaderWriter.ShouldWriteAsJson(_model, _options))
					{
						throw new InvalidOperationException("Should use ModelWriter instead of _model.Write with IJsonModel.");
					}
					if (_data == null)
					{
						_data = _model.Write(_options);
					}
					return _data;
				}
			}

			private byte[] Bytes => _bytes ?? (_bytes = Data.ToArray());

			public ModelBinaryContent(T model, ModelReaderWriterOptions options)
			{
				_model = model;
				_options = options;
				if (options.Format == "J" || (options.Format == "W" && model.GetFormatFromOptions(options) == "J"))
				{
					base.MediaType = "application/json";
				}
			}

			public override bool TryComputeLength(out long length)
			{
				length = (ModelReaderWriter.ShouldWriteAsJson(_model, _options) ? SequenceReader.Length : Data.ToMemory().Length);
				return true;
			}

			public override void WriteTo(Stream stream, CancellationToken cancellation)
			{
				Argument.AssertNotNull(stream, "stream");
				if (ModelReaderWriter.ShouldWriteAsJson(_model, _options))
				{
					SequenceReader.CopyTo(stream, cancellation);
				}
				else
				{
					stream.Write(Bytes, 0, Bytes.Length);
				}
			}

			public override async Task WriteToAsync(Stream stream, CancellationToken cancellation)
			{
				Argument.AssertNotNull(stream, "stream");
				if (ModelReaderWriter.ShouldWriteAsJson(_model, _options))
				{
					await SequenceReader.CopyToAsync(stream, cancellation).ConfigureAwait(continueOnCapturedContext: false);
				}
				else
				{
					await StreamExtensions.WriteAsync(stream, Data.ToMemory(), cancellation).ConfigureAwait(continueOnCapturedContext: false);
				}
			}

			public override void Dispose()
			{
				UnsafeBufferSequence.Reader sequenceReader = _sequenceReader;
				if (sequenceReader != null)
				{
					_sequenceReader = null;
					sequenceReader.Dispose();
				}
			}
		}

		private sealed class StreamBinaryContent : BinaryContent
		{
			private readonly Stream _stream;

			private readonly long _origin;

			public StreamBinaryContent(Stream stream)
			{
				if (!stream.CanSeek)
				{
					throw new ArgumentException("Stream must be seekable.", "stream");
				}
				_stream = stream;
				_origin = stream.Position;
			}

			public override bool TryComputeLength(out long length)
			{
				length = _stream.Length - _origin;
				return true;
			}

			public override void WriteTo(Stream stream, CancellationToken cancellationToken)
			{
				Argument.AssertNotNull(stream, "stream");
				_stream.Seek(_origin, SeekOrigin.Begin);
				_stream.CopyTo(stream, cancellationToken);
				_stream.Flush();
			}

			public override async Task WriteToAsync(Stream stream, CancellationToken cancellationToken)
			{
				Argument.AssertNotNull(stream, "stream");
				_stream.Seek(_origin, SeekOrigin.Begin);
				await StreamExtensions.CopyToAsync(_stream, stream, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				await _stream.FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public override void Dispose()
			{
				_stream.Dispose();
			}
		}

		private static readonly ModelReaderWriterOptions ModelWriteWireOptions = new ModelReaderWriterOptions("W");

		private const string JsonSerializerRequiresDynamicCode = "JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.";

		private const string JsonSerializerRequiresUnreferencedCode = "JSON serialization and deserialization might require types that cannot be statically analyzed.";

		public string? MediaType { get; protected set; }

		public static BinaryContent Create(BinaryData value)
		{
			Argument.AssertNotNull<BinaryData>(value, "value");
			return new BinaryDataBinaryContent(value.ToMemory());
		}

		public static BinaryContent Create<T>(T model, ModelReaderWriterOptions? options = null) where T : IPersistableModel<T>
		{
			Argument.AssertNotNull(model, "model");
			return new ModelBinaryContent<T>(model, options ?? ModelWriteWireOptions);
		}

		public static BinaryContent Create(Stream stream)
		{
			Argument.AssertNotNull(stream, "stream");
			return new StreamBinaryContent(stream);
		}

		[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.")]
		[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
		public static BinaryContent CreateJson<T>(T jsonSerializable, JsonSerializerOptions? options = null)
		{
			Argument.AssertNotNull(jsonSerializable, "jsonSerializable");
			return new BinaryDataBinaryContent(BinaryData.FromObjectAsJson<T>(jsonSerializable, options).ToMemory(), "application/json");
		}

		public static BinaryContent CreateJson<T>(T jsonSerializable, JsonTypeInfo<T> jsonTypeInfo)
		{
			Argument.AssertNotNull(jsonSerializable, "jsonSerializable");
			Argument.AssertNotNull(jsonTypeInfo, "jsonTypeInfo");
			return new BinaryDataBinaryContent(BinaryData.FromObjectAsJson<T>(jsonSerializable, jsonTypeInfo).ToMemory(), "application/json");
		}

		public static BinaryContent CreateJson(string jsonString, bool validate = false)
		{
			Argument.AssertNotNull(jsonString, "jsonString");
			if (validate)
			{
				ValidateJsonString(jsonString);
			}
			return new BinaryDataBinaryContent(BinaryData.FromString(jsonString).ToMemory(), "application/json");
		}

		private static void ValidateJsonString(string jsonString)
		{
			try
			{
				Utf8JsonReader utf8JsonReader = new Utf8JsonReader(Encoding.UTF8.GetBytes(jsonString));
				while (utf8JsonReader.Read())
				{
				}
			}
			catch (JsonException ex)
			{
				throw new ArgumentException("The provided string is not valid JSON: " + ex.Message, "jsonString", ex);
			}
		}

		public abstract bool TryComputeLength(out long length);

		public abstract Task WriteToAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken));

		public abstract void WriteTo(Stream stream, CancellationToken cancellationToken = default(CancellationToken));

		public abstract void Dispose();
	}
}
namespace System.ClientModel.Internal
{
	internal class Argument
	{
		public static void AssertNotNull<T>(T value, string name)
		{
			if (value == null)
			{
				throw new ArgumentNullException(name);
			}
		}

		public static void AssertNotNullOrEmpty(string value, string name)
		{
			if (value == null)
			{
				throw new ArgumentNullException(name);
			}
			if (value.Length == 0)
			{
				throw new ArgumentException("Value cannot be an empty string.", name);
			}
		}

		public static void AssertInRange<T>(T value, T minimum, T maximum, string name) where T : notnull, IComparable<T>
		{
			if (minimum.CompareTo(value) > 0)
			{
				throw new ArgumentOutOfRangeException(name, "Value is less than the minimum allowed.");
			}
			if (maximum.CompareTo(value) < 0)
			{
				throw new ArgumentOutOfRangeException(name, "Value is greater than the maximum allowed.");
			}
		}
	}
	internal struct ArrayBackedPropertyBag<TKey, TValue> where TKey : struct, IEquatable<TKey>
	{
		private (TKey Key, TValue? Value) _first;

		private (TKey Key, TValue? Value) _second;

		private (TKey Key, TValue? Value)[]? _rest;

		private int _count;

		private readonly object _lock;

		public int Count => _count;

		public bool IsEmpty => _count == 0;

		public ArrayBackedPropertyBag()
		{
			_first = default((TKey, TValue));
			_second = default((TKey, TValue));
			_rest = null;
			_count = 0;
			_lock = new object();
		}

		public void GetAt(int index, out TKey key, out TValue? value)
		{
			(key, value) = index switch
			{
				0 => _first, 
				1 => _second, 
				_ => GetRest()[index - 2], 
			};
		}

		public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue? value)
		{
			int index = GetIndex(key);
			if (index < 0)
			{
				value = default(TValue);
				return false;
			}
			value = GetAt(index);
			return true;
		}

		public bool TryAdd(TKey key, TValue value, out TValue? existingValue)
		{
			int index = GetIndex(key);
			if (index >= 0)
			{
				existingValue = GetAt(index);
				return false;
			}
			AddInternal(key, value);
			existingValue = default(TValue);
			return true;
		}

		public void Set(TKey key, TValue? value)
		{
			int index = GetIndex(key);
			if (index < 0)
			{
				AddInternal(key, value);
			}
			else
			{
				SetAt(index, (key, value));
			}
		}

		public bool TryRemove(TKey key)
		{
			switch (_count)
			{
			case 0:
				return false;
			case 1:
				if (IsFirst(key))
				{
					_first = default((TKey, TValue));
					_count--;
					return true;
				}
				return false;
			case 2:
				if (IsFirst(key))
				{
					_first = _second;
					_second = default((TKey, TValue));
					_count--;
					return true;
				}
				if (IsSecond(key))
				{
					_second = default((TKey, TValue));
					_count--;
					return true;
				}
				return false;
			default:
			{
				(TKey, TValue)[] rest = GetRest();
				if (IsFirst(key))
				{
					_first = _second;
					_second = rest[0];
					_count--;
					Array.Copy(rest, 1, rest, 0, _count - 2);
					rest[_count - 2] = default((TKey, TValue));
					return true;
				}
				if (IsSecond(key))
				{
					_second = rest[0];
					_count--;
					Array.Copy(rest, 1, rest, 0, _count - 2);
					rest[_count - 2] = default((TKey, TValue));
					return true;
				}
				for (int i = 0; i < _count - 2; i++)
				{
					if (rest[i].Item1.Equals(key))
					{
						_count--;
						Array.Copy(rest, i + 1, rest, i, _count - 2 - i);
						rest[_count - 2] = default((TKey, TValue));
						return true;
					}
				}
				return false;
			}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private bool IsFirst(TKey key)
		{
			return _first.Key.Equals(key);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private bool IsSecond(TKey key)
		{
			return _second.Key.Equals(key);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AddInternal(TKey key, TValue? value)
		{
			switch (_count)
			{
			case 0:
				_first = (key, value);
				_count = 1;
				return;
			case 1:
				if (IsFirst(key))
				{
					_first = (_first.Key, value);
					return;
				}
				_second = (key, value);
				_count = 2;
				return;
			}
			if (_rest == null)
			{
				_rest = ArrayPool<(TKey, TValue)>.Shared.Rent(8);
				_rest[_count++ - 2] = (key, value);
				return;
			}
			if (_rest.Length <= _count)
			{
				(TKey, TValue)[] array = ArrayPool<(TKey, TValue)>.Shared.Rent(_rest.Length << 1);
				_rest.CopyTo(array, 0);
				(TKey, TValue)[] rest = _rest;
				_rest = array;
				ArrayPool<(TKey, TValue)>.Shared.Return(rest, clearArray: true);
			}
			_rest[_count++ - 2] = (key, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void SetAt(int index, (TKey Key, TValue? Value) value)
		{
			switch (index)
			{
			case 0:
				_first = value;
				break;
			case 1:
				_second = value;
				break;
			default:
				GetRest()[index - 2] = value;
				break;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private TValue? GetAt(int index)
		{
			return index switch
			{
				0 => _first.Value, 
				1 => _second.Value, 
				_ => GetRest()[index - 2].Value, 
			};
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private int GetIndex(TKey key)
		{
			if (_count == 0)
			{
				return -1;
			}
			if (_count > 0 && _first.Key.Equals(key))
			{
				return 0;
			}
			if (_count > 1 && _second.Key.Equals(key))
			{
				return 1;
			}
			if (_count <= 2)
			{
				return -1;
			}
			(TKey, TValue)[] rest = GetRest();
			int num = _count - 2;
			for (int i = 0; i < num; i++)
			{
				if (rest[i].Item1.Equals(key))
				{
					return i + 2;
				}
			}
			return -1;
		}

		public void Dispose()
		{
			_count = 0;
			_first = default((TKey, TValue));
			_second = default((TKey, TValue));
			lock (_lock)
			{
				if (_rest != null)
				{
					(TKey, TValue)[] rest = _rest;
					_rest = null;
					ArrayPool<(TKey, TValue)>.Shared.Return(rest, clearArray: true);
				}
			}
		}

		private (TKey Key, TValue? Value)[] GetRest()
		{
			return _rest ?? throw new InvalidOperationException(string.Format("{0} field is null while {1} == {2}", "_rest", "_count", _count));
		}

		[Conditional("DEBUG")]
		private void CheckDisposed()
		{
		}
	}
	internal struct BitVector640
	{
		private ulong _bits0;

		private ulong _bits1;

		private ulong _bits2;

		private ulong _bits3;

		private ulong _bits4;

		private ulong _bits5;

		private ulong _bits6;

		private ulong _bits7;

		private ulong _bits8;

		private ulong _bits9;

		public bool this[int i]
		{
			readonly get
			{
				int index = i >> 6;
				int num = i & 0x3F;
				ulong num2 = (ulong)(1L << num);
				return (Get(index) & num2) == num2;
			}
			set
			{
				int index = i >> 6;
				int num = i & 0x3F;
				ulong mask = (ulong)(1L << num);
				Set(index, mask, value);
			}
		}

		private readonly ulong Get(int index)
		{
			return index switch
			{
				0 => _bits0, 
				1 => _bits1, 
				2 => _bits2, 
				3 => _bits3, 
				4 => _bits4, 
				5 => _bits5, 
				6 => _bits6, 
				7 => _bits7, 
				8 => _bits8, 
				9 => _bits9, 
				_ => throw new InvalidOperationException(), 
			};
		}

		private void Set(int index, ulong mask, bool value)
		{
			if (value)
			{
				switch (index)
				{
				case 0:
					_bits0 |= mask;
					break;
				case 1:
					_bits1 |= mask;
					break;
				case 2:
					_bits2 |= mask;
					break;
				case 3:
					_bits3 |= mask;
					break;
				case 4:
					_bits4 |= mask;
					break;
				case 5:
					_bits5 |= mask;
					break;
				case 6:
					_bits6 |= mask;
					break;
				case 7:
					_bits7 |= mask;
					break;
				case 8:
					_bits8 |= mask;
					break;
				case 9:
					_bits9 |= mask;
					break;
				default:
					throw new InvalidOperationException();
				}
			}
			else
			{
				switch (index)
				{
				case 0:
					_bits0 &= ~mask;
					break;
				case 1:
					_bits1 &= ~mask;
					break;
				case 2:
					_bits2 &= ~mask;
					break;
				case 3:
					_bits3 &= ~mask;
					break;
				case 4:
					_bits4 &= ~mask;
					break;
				case 5:
					_bits5 &= ~mask;
					break;
				case 6:
					_bits6 &= ~mask;
					break;
				case 7:
					_bits7 &= ~mask;
					break;
				case 8:
					_bits8 &= ~mask;
					break;
				case 9:
					_bits9 &= ~mask;
					break;
				default:
					throw new InvalidOperationException();
				}
			}
		}
	}
	internal static class CancellationHelper
	{
		private static readonly string s_cancellationMessage = new OperationCanceledException().Message;

		internal static bool ShouldWrapInOperationCanceledException(Exception exception, CancellationToken cancellationToken)
		{
			if (!(exception is OperationCanceledException))
			{
				return cancellationToken.IsCancellationRequested;
			}
			return false;
		}

		internal static Exception CreateOperationCanceledException(Exception? innerException, CancellationToken cancellationToken, string? message = null)
		{
			return new TaskCanceledException(message ?? s_cancellationMessage, innerException);
		}

		private static void ThrowOperationCanceledException(Exception? innerException, CancellationToken cancellationToken)
		{
			throw CreateOperationCanceledException(innerException, cancellationToken);
		}

		internal static void ThrowIfCancellationRequested(CancellationToken cancellationToken, Exception? innerException = null)
		{
			if (cancellationToken.IsCancellationRequested)
			{
				ThrowOperationCanceledException(innerException, cancellationToken);
			}
		}

		internal static void ThrowIfCancellationRequestedOrTimeout(CancellationToken messageToken, CancellationToken timeoutToken, Exception? innerException, TimeSpan timeout)
		{
			ThrowIfCancellationRequested(messageToken, innerException);
			if (timeoutToken.IsCancellationRequested)
			{
				throw CreateOperationCanceledException(innerException, timeoutToken, $"The operation was cancelled because it exceeded the configured timeout of {timeout:g}. " + "The default timeout can be adjusted by passing a custom ClientPipelineOptions.NetworkTimeout value to the client's constructor. See https://aka.ms/net/scm/configure/networktimeout for more information.");
			}
		}
	}
	internal class ChangeTrackingStringList : IList<string>, ICollection<string>, IEnumerable<string>, IEnumerable
	{
		private IList<string> _list;

		private bool _frozen;

		private bool _tracking = true;

		public bool HasChanged { get; private set; }

		public string this[int index]
		{
			get
			{
				return _list[index];
			}
			set
			{
				AssertNotFrozen();
				_list[index] = value;
				HasChanged |= _tracking;
			}
		}

		public int Count => _list.Count;

		public bool IsReadOnly => _list.IsReadOnly;

		public ChangeTrackingStringList()
		{
			_list = new List<string>();
		}

		public ChangeTrackingStringList(IEnumerable<string> collection)
		{
			_list = new List<string>(collection);
		}

		public void Freeze()
		{
			_frozen = true;
		}

		public void AssertNotFrozen()
		{
			if (_frozen)
			{
				throw new InvalidOperationException("Cannot change any client pipeline options after the client pipeline has been created.");
			}
		}

		public void Add(string item)
		{
			AssertNotFrozen();
			_list.Add(item);
			HasChanged |= _tracking;
		}

		public void Clear()
		{
			AssertNotFrozen();
			int count = _list.Count;
			_list.Clear();
			HasChanged |= _tracking && count != 0;
		}

		public bool Contains(string item)
		{
			return _list.Contains(item);
		}

		public void CopyTo(string[] array, int arrayIndex)
		{
			_list.CopyTo(array, arrayIndex);
		}

		public IEnumerator<string> GetEnumerator()
		{
			return _list.GetEnumerator();
		}

		public int IndexOf(string item)
		{
			return _list.IndexOf(item);
		}

		public void Insert(int index, string item)
		{
			AssertNotFrozen();
			_list.Insert(index, item);
			HasChanged |= _tracking;
		}

		public bool Remove(string item)
		{
			AssertNotFrozen();
			bool flag = _list.Remove(item);
			HasChanged |= _tracking && flag;
			return flag;
		}

		public void RemoveAt(int index)
		{
			AssertNotFrozen();
			_list.RemoveAt(index);
			HasChanged |= _tracking;
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	internal class ContentTypeUtilities
	{
		public static bool TryGetTextEncoding(string contentType, out Encoding? encoding)
		{
			if (contentType == null)
			{
				encoding = null;
				return false;
			}
			int num = contentType.IndexOf("; charset=", StringComparison.OrdinalIgnoreCase);
			if (num != -1 && contentType.AsSpan().Slice(num + "; charset=".Length).StartsWith("utf-8".AsSpan(), StringComparison.OrdinalIgnoreCase))
			{
				encoding = Encoding.UTF8;
				return true;
			}
			if (contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("json", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("xml", StringComparison.OrdinalIgnoreCase) || contentType.EndsWith("-urlencoded", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) || contentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
			{
				encoding = Encoding.UTF8;
				return true;
			}
			encoding = null;
			return false;
		}
	}
	[EventSource(Name = "System.ClientModel")]
	internal sealed class ClientModelEventSource : EventSource
	{
		public static ClientModelEventSource Log = new ClientModelEventSource("System.ClientModel");

		private ClientModelEventSource(string eventSourceName, string[]? traits = null)
			: base(eventSourceName, EventSourceSettings.Default, traits)
		{
		}

		[NonEvent]
		public void Request(string requestId, PipelineRequest request, string? clientAssembly, PipelineMessageSanitizer sanitizer)
		{
			if (IsEnabled(EventLevel.Informational, EventKeywords.None))
			{
				Request(requestId, request.Method, sanitizer.SanitizeUrl(request.Uri.AbsoluteUri), FormatHeaders(request.Headers, sanitizer), clientAssembly);
			}
		}

		[Event(1, Level = EventLevel.Informational, Message = "Request [{0}] {1} {2}\r\n{3}client assembly: {4}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")]
		private void Request(string? requestId, string method, string uri, string headers, string? clientAssembly)
		{
			WriteEvent(1, requestId, method, uri, headers, clientAssembly);
		}

		[NonEvent]
		public void RequestContent(string requestId, byte[] content, Encoding? textEncoding)
		{
			if (IsEnabled(EventLevel.Verbose, EventKeywords.None))
			{
				if (textEncoding != null)
				{
					RequestContentText(requestId, textEncoding.GetString(content));
				}
				else
				{
					RequestContent(requestId, content);
				}
			}
		}

		[Event(2, Level = EventLevel.Verbose, Message = "Request [{0}] content: {1}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")]
		private void RequestContent(string? requestId, byte[] content)
		{
			WriteEvent(2, requestId, content);
		}

		[Event(17, Level = EventLevel.Verbose, Message = "Request [{0}] content: {1}")]
		private void RequestContentText(string? requestId, string content)
		{
			WriteEvent(17, requestId, content);
		}

		[NonEvent]
		public void Response(string requestId, PipelineResponse response, double seconds, PipelineMessageSanitizer sanitizer)
		{
			if (IsEnabled(EventLevel.Informational, EventKeywords.None))
			{
				Response(requestId, response.Status, response.ReasonPhrase, FormatHeaders(response.Headers, sanitizer), seconds);
			}
		}

		[Event(5, Level = EventLevel.Informational, Message = "Response [{0}] {1} {2} ({4:00.0}s)\r\n{3}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")]
		private void Response(string? requestId, int status, string reasonPhrase, string headers, double seconds)
		{
			WriteEvent(5, requestId, status, reasonPhrase, headers, seconds);
		}

		[NonEvent]
		public void ResponseContent(string requestId, byte[] content, Encoding? textEncoding)
		{
			if (IsEnabled(EventLevel.Verbose, EventKeywords.None))
			{
				if (textEncoding != null)
				{
					ResponseContentText(requestId, textEncoding.GetString(content));
				}
				else
				{
					ResponseContent(requestId, content);
				}
			}
		}

		[Event(6, Level = EventLevel.Verbose, Message = "Response [{0}] content: {1}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")]
		private void ResponseContent(string? requestId, byte[] content)
		{
			WriteEvent(6, requestId, content);
		}

		[Event(13, Level = EventLevel.Verbose, Message = "Response [{0}] content: {1}")]
		private void ResponseContentText(string? requestId, string content)
		{
			WriteEvent(13, requestId, content);
		}

		[NonEvent]
		public void ResponseContentBlock(string requestId, int blockNumber, byte[] content, Encoding? textEncoding)
		{
			if (IsEnabled(EventLevel.Verbose, EventKeywords.None))
			{
				if (textEncoding != null)
				{
					ResponseContentTextBlock(requestId, blockNumber, textEncoding.GetString(content));
				}
				else
				{
					ResponseContentBlock(requestId, blockNumber, content);
				}
			}
		}

		[Event(11, Level = EventLevel.Verbose, Message = "Response [{0}] content block {1}: {2}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")]
		private void ResponseContentBlock(string? requestId, int blockNumber, byte[] content)
		{
			WriteEvent(11, requestId, blockNumber, content);
		}

		[Event(15, Level = EventLevel.Verbose, Message = "Response [{0}] content block {1}: {2}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")]
		private void ResponseContentTextBlock(string? requestId, int blockNumber, string content)
		{
			WriteEvent(15, requestId, blockNumber, content);
		}

		[NonEvent]
		public void ErrorResponse(string requestId, PipelineResponse response, double elapsed, PipelineMessageSanitizer sanitizer)
		{
			if (IsEnabled(EventLevel.Warning, EventKeywords.None))
			{
				ErrorResponse(requestId, response.Status, response.ReasonPhrase, FormatHeaders(response.Headers, sanitizer), elapsed);
			}
		}

		[Event(8, Level = EventLevel.Warning, Message = "Error response [{0}] {1} {2} ({4:00.0}s)\r\n{3}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")]
		private void ErrorResponse(string? requestId, int status, string reasonPhrase, string headers, double seconds)
		{
			WriteEvent(8, requestId, status, reasonPhrase, headers, seconds);
		}

		[NonEvent]
		public void ErrorResponseContent(string requestId, byte[] content, Encoding? textEncoding)
		{
			if (IsEnabled(EventLevel.Informational, EventKeywords.None))
			{
				if (textEncoding != null)
				{
					ErrorResponseContentText(requestId, textEncoding.GetString(content));
				}
				else
				{
					ErrorResponseContent(requestId, content);
				}
			}
		}

		[Event(9, Level = EventLevel.Informational, Message = "Error response [{0}] content: {1}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")]
		private void ErrorResponseContent(string? requestId, byte[] content)
		{
			WriteEvent(9, requestId, content);
		}

		[Event(14, Level = EventLevel.Informational, Message = "Error response [{0}] content: {1}")]
		private void ErrorResponseContentText(string? requestId, string content)
		{
			WriteEvent(14, requestId, content);
		}

		[NonEvent]
		public void ErrorResponseContentBlock(string requestId, int blockNumber, byte[] content, Encoding? textEncoding)
		{
			if (IsEnabled(EventLevel.Informational, EventKeywords.None))
			{
				if (textEncoding != null)
				{
					ErrorResponseContentTextBlock(requestId, blockNumber, textEncoding.GetString(content));
				}
				else
				{
					ErrorResponseContentBlock(requestId, blockNumber, content);
				}
			}
		}

		[Event(12, Level = EventLevel.Informational, Message = "Error response [{0}] content block {1}: {2}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with an array with primitive type elements.")]
		private void ErrorResponseContentBlock(string? requestId, int blockNumber, byte[] content)
		{
			WriteEvent(12, requestId, blockNumber, content);
		}

		[Event(16, Level = EventLevel.Informational, Message = "Error response [{0}] content block {1}: {2}")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")]
		private void ErrorResponseContentTextBlock(string? requestId, int blockNumber, string content)
		{
			WriteEvent(16, requestId, blockNumber, content);
		}

		[Event(10, Level = EventLevel.Informational, Message = "Request [{0}] attempt number {1} took {2:00.0}s")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")]
		public void RequestRetrying(string? requestId, int retryNumber, double seconds)
		{
			if (IsEnabled(EventLevel.Informational, EventKeywords.None))
			{
				WriteEvent(10, requestId, retryNumber, seconds);
			}
		}

		[Event(7, Level = EventLevel.Warning, Message = "Response [{0}] took {1:00.0}s")]
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026", Justification = "WriteEvent is used with primitive types.")]
		public void ResponseDelay(string? requestId, double seconds)
		{
			if (IsEnabled(EventLevel.Warning, EventKeywords.None))
			{
				WriteEvent(7, requestId, seconds);
			}
		}

		[Event(18, Level = EventLevel.Informational, Message = "Request [{0}] exception {1}")]
		public void ExceptionResponse(string? requestId, string exception)
		{
			if (IsEnabled(EventLevel.Informational, EventKeywords.None))
			{
				WriteEvent(18, requestId, exception);
			}
		}

		[NonEvent]
		private string FormatHeaders(IEnumerable<KeyValuePair<string, string>> headers, PipelineMessageSanitizer sanitizer)
		{
			StringBuilder stringBuilder = new StringBuilder();
			foreach (KeyValuePair<string, string> header in headers)
			{
				stringBuilder.Append(header.Key);
				stringBuilder.Append(':');
				stringBuilder.Append(sanitizer.SanitizeHeader(header.Key, header.Value));
				stringBuilder.Append(Environment.NewLine);
			}
			return stringBuilder.ToString();
		}
	}
	internal class LoggingEventIds
	{
		public const int RequestEvent = 1;

		public const int RequestContentEvent = 2;

		public const int ResponseEvent = 5;

		public const int ResponseContentEvent = 6;

		public const int ResponseDelayEvent = 7;

		public const int ErrorResponseEvent = 8;

		public const int ErrorResponseContentEvent = 9;

		public const int RequestRetryingEvent = 10;

		public const int ResponseContentBlockEvent = 11;

		public const int ErrorResponseContentBlockEvent = 12;

		public const int ResponseContentTextEvent = 13;

		public const int ErrorResponseContentTextEvent = 14;

		public const int ResponseContentTextBlockEvent = 15;

		public const int ErrorResponseContentTextBlockEvent = 16;

		public const int RequestContentTextEvent = 17;

		public const int ExceptionResponseEvent = 18;
	}
	internal class PipelineMessageHeadersLogValue : IReadOnlyList<KeyValuePair<string, string>>, IEnumerable<KeyValuePair<string, string>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, string>>
	{
		private readonly PipelineRequestHeaders? _requestHeaders;

		private readonly PipelineResponseHeaders? _responseHeaders;

		private readonly PipelineMessageSanitizer _sanitizer;

		private List<KeyValuePair<string, string>>? _values;

		private string? _formatted;

		private List<KeyValuePair<string, string>> Values
		{
			get
			{
				if (_values == null)
				{
					List<KeyValuePair<string, string>> list = new List<KeyValuePair<string, string>>();
					if (_requestHeaders != null)
					{
						foreach (KeyValuePair<string, string> requestHeader in _requestHeaders)
						{
							list.Add(new KeyValuePair<string, string>(requestHeader.Key, _sanitizer.SanitizeHeader(requestHeader.Key, requestHeader.Value)));
						}
					}
					else if (_responseHeaders != null)
					{
						foreach (KeyValuePair<string, string> responseHeader in _responseHeaders)
						{
							list.Add(new KeyValuePair<string, string>(responseHeader.Key, _sanitizer.SanitizeHeader(responseHeader.Key, responseHeader.Value)));
						}
					}
					_values = list;
				}
				return _values;
			}
		}

		public KeyValuePair<string, string> this[int index]
		{
			get
			{
				if (index < 0 || index >= Count)
				{
					throw new IndexOutOfRangeException("index");
				}
				return Values[index];
			}
		}

		public int Count => Values.Count;

		public PipelineMessageHeadersLogValue(PipelineRequestHeaders headers, PipelineMessageSanitizer sanitizer)
		{
			_sanitizer = sanitizer;
			_requestHeaders = headers;
		}

		public PipelineMessageHeadersLogValue(PipelineResponseHeaders headers, PipelineMessageSanitizer sanitizer)
		{
			_sanitizer = sanitizer;
			_responseHeaders = headers;
		}

		public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
		{
			return Values.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return Values.GetEnumerator();
		}

		public override string ToString()
		{
			if (_formatted == null)
			{
				StringBuilder stringBuilder = new StringBuilder();
				foreach (KeyValuePair<string, string> value in Values)
				{
					stringBuilder.Append(value.Key);
					stringBuilder.Append(':');
					stringBuilder.Append(_sanitizer.SanitizeHeader(value.Key, value.Value));
					stringBuilder.Append(Environment.NewLine);
				}
				_formatted = stringBuilder.ToString();
			}
			return _formatted;
		}
	}
	internal class PipelineMessageLogger
	{
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		private readonly struct __ResponseStruct : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__12 : IEnumerator<KeyValuePair<string, object?>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object?> <>2__current;

				public __ResponseStruct <>4__this;

				private int <i>5__2;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__12(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<i>5__2 = 0;
						break;
					case 1:
						<>1__state = -1;
						<i>5__2++;
						break;
					}
					if (<i>5__2 < 6)
					{
						<>2__current = <>4__this[<i>5__2];
						<>1__state = 1;
						return true;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			private readonly string _requestId;

			private readonly int _status;

			private readonly string _reasonPhrase;

			private readonly PipelineMessageHeadersLogValue _headers;

			private readonly double _seconds;

			public static readonly Func<__ResponseStruct, Exception?, string> Format = (__ResponseStruct state, Exception? ex) => state.ToString();

			public int Count => 6;

			public KeyValuePair<string, object?> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>("requestId", _requestId), 
				1 => new KeyValuePair<string, object>("status", _status), 
				2 => new KeyValuePair<string, object>("reasonPhrase", _reasonPhrase), 
				3 => new KeyValuePair<string, object>("headers", _headers), 
				4 => new KeyValuePair<string, object>("seconds", _seconds), 
				5 => new KeyValuePair<string, object>("{OriginalFormat}", "Response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{headers}"), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public __ResponseStruct(string requestId, int status, string reasonPhrase, PipelineMessageHeadersLogValue headers, double seconds)
			{
				_requestId = requestId;
				_status = status;
				_reasonPhrase = reasonPhrase;
				_headers = headers;
				_seconds = seconds;
			}

			public override string ToString()
			{
				string requestId = _requestId;
				int status = _status;
				string reasonPhrase = _reasonPhrase;
				double seconds = _seconds;
				string text = __LoggerMessageGenerator.Enumerate(_headers);
				return $"Response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{text}";
			}

			[IteratorStateMachine(typeof(<GetEnumerator>d__12))]
			public IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__12(0)
				{
					<>4__this = this
				};
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		private readonly struct __ErrorResponseStruct : IReadOnlyList<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable, IReadOnlyCollection<KeyValuePair<string, object?>>
		{
			[CompilerGenerated]
			private sealed class <GetEnumerator>d__12 : IEnumerator<KeyValuePair<string, object?>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, object?> <>2__current;

				public __ErrorResponseStruct <>4__this;

				private int <i>5__2;

				KeyValuePair<string, object> IEnumerator<KeyValuePair<string, object>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

				[DebuggerHidden]
				public <GetEnumerator>d__12(int <>1__state)
				{
					this.<>1__state = <>1__state;
				}

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					switch (<>1__state)
					{
					default:
						return false;
					case 0:
						<>1__state = -1;
						<i>5__2 = 0;
						break;
					case 1:
						<>1__state = -1;
						<i>5__2++;
						break;
					}
					if (<i>5__2 < 6)
					{
						<>2__current = <>4__this[<i>5__2];
						<>1__state = 1;
						return true;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}
			}

			private readonly string _requestId;

			private readonly int _status;

			private readonly string _reasonPhrase;

			private readonly PipelineMessageHeadersLogValue _headers;

			private readonly double _seconds;

			public static readonly Func<__ErrorResponseStruct, Exception?, string> Format = (__ErrorResponseStruct state, Exception? ex) => state.ToString();

			public int Count => 6;

			public KeyValuePair<string, object?> this[int index] => index switch
			{
				0 => new KeyValuePair<string, object>("requestId", _requestId), 
				1 => new KeyValuePair<string, object>("status", _status), 
				2 => new KeyValuePair<string, object>("reasonPhrase", _reasonPhrase), 
				3 => new KeyValuePair<string, object>("headers", _headers), 
				4 => new KeyValuePair<string, object>("seconds", _seconds), 
				5 => new KeyValuePair<string, object>("{OriginalFormat}", "Error response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{headers}"), 
				_ => throw new IndexOutOfRangeException("index"), 
			};

			public __ErrorResponseStruct(string requestId, int status, string reasonPhrase, PipelineMessageHeadersLogValue headers, double seconds)
			{
				_requestId = requestId;
				_status = status;
				_reasonPhrase = reasonPhrase;
				_headers = headers;
				_seconds = seconds;
			}

			public override string ToString()
			{
				string requestId = _requestId;
				int status = _status;
				string reasonPhrase = _reasonPhrase;
				double seconds = _seconds;
				string text = __LoggerMessageGenerator.Enumerate(_headers);
				return $"Error response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{text}";
			}

			[IteratorStateMachine(typeof(<GetEnumerator>d__12))]
			public IEnumerator<KeyValuePair<string, object?>> GetEnumerator()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <GetEnumerator>d__12(0)
				{
					<>4__this = this
				};
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		private readonly ILogger<MessageLoggingPolicy>? _logger;

		private readonly PipelineMessageSanitizer _sanitizer;

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, string, string, PipelineMessageHeadersLogValue, string?, Exception?> __RequestCallback = LoggerMessage.Define<string, string, string, PipelineMessageHeadersLogValue, string>(LogLevel.Information, new EventId(1, "Request"), "Request [{requestId}] {method} {uri}\r\n{headers}client assembly: {clientAssembly}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, byte[], Exception?> __RequestContentCallback = LoggerMessage.Define<string, byte[]>(LogLevel.Debug, new EventId(2, "RequestContent"), "Request [{requestId}] content: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, string, Exception?> __RequestContentTextCallback = LoggerMessage.Define<string, string>(LogLevel.Debug, new EventId(17, "RequestContentText"), "Request [{requestId}] content: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, byte[], Exception?> __ResponseContentCallback = LoggerMessage.Define<string, byte[]>(LogLevel.Debug, new EventId(6, "ResponseContent"), "Response [{requestId}] content: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, string, Exception?> __ResponseContentTextCallback = LoggerMessage.Define<string, string>(LogLevel.Debug, new EventId(13, "ResponseContentText"), "Response [{requestId}] content: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, int, byte[], Exception?> __ResponseContentBlockCallback = LoggerMessage.Define<string, int, byte[]>(LogLevel.Debug, new EventId(11, "ResponseContentBlock"), "Response [{requestId}] content block {blockNumber}: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, int, string, Exception?> __ResponseContentTextBlockCallback = LoggerMessage.Define<string, int, string>(LogLevel.Debug, new EventId(15, "ResponseContentTextBlock"), "Response [{requestId}] content block {blockNumber}: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, byte[], Exception?> __ErrorResponseContentCallback = LoggerMessage.Define<string, byte[]>(LogLevel.Information, new EventId(9, "ErrorResponseContent"), "Error response [{requestId}] content: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, string, Exception?> __ErrorResponseContentTextCallback = LoggerMessage.Define<string, string>(LogLevel.Information, new EventId(14, "ErrorResponseContentText"), "Error response [{requestId}] content: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, int, byte[], Exception?> __ErrorResponseContentBlockCallback = LoggerMessage.Define<string, int, byte[]>(LogLevel.Information, new EventId(12, "ErrorResponseContentBlock"), "Error response [{requestId}] content block {blockNumber}: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, int, string, Exception?> __ErrorResponseContentTextBlockCallback = LoggerMessage.Define<string, int, string>(LogLevel.Information, new EventId(16, "ErrorResponseContentTextBlock"), "Error response [{requestId}] content block {blockNumber}: {content}", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		public PipelineMessageLogger(PipelineMessageSanitizer sanitizer, ILoggerFactory? loggerFactory)
		{
			_sanitizer = sanitizer;
			_logger = loggerFactory?.CreateLogger<MessageLoggingPolicy>() ?? null;
		}

		public bool IsEnabled(LogLevel logLevel, EventLevel eventLevel)
		{
			if (_logger == null)
			{
				return ClientModelEventSource.Log.IsEnabled(eventLevel, EventKeywords.None);
			}
			return _logger.IsEnabled(logLevel);
		}

		public void LogRequest(string requestId, PipelineRequest request, string? clientAssembly)
		{
			if (_logger != null)
			{
				if (_logger.IsEnabled(LogLevel.Information))
				{
					Request(_logger, requestId, request.Method, _sanitizer.SanitizeUrl(request.Uri.AbsoluteUri), new PipelineMessageHeadersLogValue(request.Headers, _sanitizer), clientAssembly);
				}
			}
			else
			{
				ClientModelEventSource.Log.Request(requestId, request, clientAssembly, _sanitizer);
			}
		}

		[LoggerMessage(1, LogLevel.Information, "Request [{requestId}] {method} {uri}\r\n{headers}client assembly: {clientAssembly}", SkipEnabledCheck = true, EventName = "Request")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void Request(ILogger logger, string requestId, string method, string uri, PipelineMessageHeadersLogValue headers, string? clientAssembly)
		{
			__RequestCallback(logger, requestId, method, uri, headers, clientAssembly, null);
		}

		public void LogRequestContent(string requestId, byte[] content, Encoding? textEncoding)
		{
			if (_logger != null)
			{
				if (_logger.IsEnabled(LogLevel.Debug))
				{
					if (textEncoding != null)
					{
						RequestContentText(_logger, requestId, textEncoding.GetString(content));
					}
					else
					{
						RequestContent(_logger, requestId, content);
					}
				}
			}
			else
			{
				ClientModelEventSource.Log.RequestContent(requestId, content, textEncoding);
			}
		}

		[LoggerMessage(2, LogLevel.Debug, "Request [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "RequestContent")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void RequestContent(ILogger logger, string requestId, byte[] content)
		{
			__RequestContentCallback(logger, requestId, content, null);
		}

		[LoggerMessage(17, LogLevel.Debug, "Request [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "RequestContentText")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void RequestContentText(ILogger logger, string requestId, string content)
		{
			__RequestContentTextCallback(logger, requestId, content, null);
		}

		public void LogResponse(string requestId, PipelineResponse response, double seconds)
		{
			if (_logger != null)
			{
				if (_logger.IsEnabled(LogLevel.Information))
				{
					Response(_logger, requestId, response.Status, response.ReasonPhrase, new PipelineMessageHeadersLogValue(response.Headers, _sanitizer), seconds);
				}
			}
			else
			{
				ClientModelEventSource.Log.Response(requestId, response, seconds, _sanitizer);
			}
		}

		[LoggerMessage(5, LogLevel.Information, "Response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{headers}", SkipEnabledCheck = true, EventName = "Response")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void Response(ILogger logger, string requestId, int status, string reasonPhrase, PipelineMessageHeadersLogValue headers, double seconds)
		{
			logger.Log(LogLevel.Information, new EventId(5, "Response"), new __ResponseStruct(requestId, status, reasonPhrase, headers, seconds), null, __ResponseStruct.Format);
		}

		public void LogResponseContent(string requestId, byte[] content, Encoding? textEncoding)
		{
			if (_logger != null)
			{
				if (_logger.IsEnabled(LogLevel.Debug))
				{
					if (textEncoding != null)
					{
						ResponseContentText(_logger, requestId, textEncoding.GetString(content));
					}
					else
					{
						ResponseContent(_logger, requestId, content);
					}
				}
			}
			else
			{
				ClientModelEventSource.Log.ResponseContent(requestId, content, textEncoding);
			}
		}

		[LoggerMessage(6, LogLevel.Debug, "Response [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "ResponseContent")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ResponseContent(ILogger logger, string requestId, byte[] content)
		{
			__ResponseContentCallback(logger, requestId, content, null);
		}

		[LoggerMessage(13, LogLevel.Debug, "Response [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "ResponseContentText")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ResponseContentText(ILogger logger, string requestId, string content)
		{
			__ResponseContentTextCallback(logger, requestId, content, null);
		}

		public void LogResponseContentBlock(string requestId, int blockNumber, byte[] content, Encoding? textEncoding)
		{
			if (_logger != null)
			{
				if (_logger.IsEnabled(LogLevel.Debug))
				{
					if (textEncoding != null)
					{
						ResponseContentTextBlock(_logger, requestId, blockNumber, textEncoding.GetString(content));
					}
					else
					{
						ResponseContentBlock(_logger, requestId, blockNumber, content);
					}
				}
			}
			else
			{
				ClientModelEventSource.Log.ResponseContentBlock(requestId, blockNumber, content, textEncoding);
			}
		}

		[LoggerMessage(11, LogLevel.Debug, "Response [{requestId}] content block {blockNumber}: {content}", SkipEnabledCheck = true, EventName = "ResponseContentBlock")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ResponseContentBlock(ILogger logger, string requestId, int blockNumber, byte[] content)
		{
			__ResponseContentBlockCallback(logger, requestId, blockNumber, content, null);
		}

		[LoggerMessage(15, LogLevel.Debug, "Response [{requestId}] content block {blockNumber}: {content}", SkipEnabledCheck = true, EventName = "ResponseContentTextBlock")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ResponseContentTextBlock(ILogger logger, string requestId, int blockNumber, string content)
		{
			__ResponseContentTextBlockCallback(logger, requestId, blockNumber, content, null);
		}

		public void LogErrorResponse(string requestId, PipelineResponse response, double seconds)
		{
			if (_logger != null)
			{
				if (_logger.IsEnabled(LogLevel.Warning))
				{
					ErrorResponse(_logger, requestId, response.Status, response.ReasonPhrase, new PipelineMessageHeadersLogValue(response.Headers, _sanitizer), seconds);
				}
			}
			else
			{
				ClientModelEventSource.Log.ErrorResponse(requestId, response, seconds, _sanitizer);
			}
		}

		[LoggerMessage(8, LogLevel.Warning, "Error response [{requestId}] {status} {reasonPhrase} ({seconds:00.0}s)\r\n{headers}", SkipEnabledCheck = true, EventName = "ErrorResponse")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ErrorResponse(ILogger logger, string requestId, int status, string reasonPhrase, PipelineMessageHeadersLogValue headers, double seconds)
		{
			logger.Log(LogLevel.Warning, new EventId(8, "ErrorResponse"), new __ErrorResponseStruct(requestId, status, reasonPhrase, headers, seconds), null, __ErrorResponseStruct.Format);
		}

		public void LogErrorResponseContent(string requestId, byte[] content, Encoding? textEncoding)
		{
			if (_logger != null)
			{
				if (_logger.IsEnabled(LogLevel.Information))
				{
					if (textEncoding != null)
					{
						ErrorResponseContentText(_logger, requestId, textEncoding.GetString(content));
					}
					else
					{
						ErrorResponseContent(_logger, requestId, content);
					}
				}
			}
			else
			{
				ClientModelEventSource.Log.ErrorResponseContent(requestId, content, textEncoding);
			}
		}

		[LoggerMessage(9, LogLevel.Information, "Error response [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "ErrorResponseContent")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ErrorResponseContent(ILogger logger, string requestId, byte[] content)
		{
			__ErrorResponseContentCallback(logger, requestId, content, null);
		}

		[LoggerMessage(14, LogLevel.Information, "Error response [{requestId}] content: {content}", SkipEnabledCheck = true, EventName = "ErrorResponseContentText")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ErrorResponseContentText(ILogger logger, string requestId, string content)
		{
			__ErrorResponseContentTextCallback(logger, requestId, content, null);
		}

		public void LogErrorResponseContentBlock(string requestId, int blockNumber, byte[] content, Encoding? textEncoding)
		{
			if (_logger != null)
			{
				if (_logger.IsEnabled(LogLevel.Information))
				{
					if (textEncoding != null)
					{
						ErrorResponseContentTextBlock(_logger, requestId, blockNumber, textEncoding.GetString(content));
					}
					else
					{
						ErrorResponseContentBlock(_logger, requestId, blockNumber, content);
					}
				}
			}
			else
			{
				ClientModelEventSource.Log.ErrorResponseContentBlock(requestId, blockNumber, content, textEncoding);
			}
		}

		[LoggerMessage(12, LogLevel.Information, "Error response [{requestId}] content block {blockNumber}: {content}", SkipEnabledCheck = true, EventName = "ErrorResponseContentBlock")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ErrorResponseContentBlock(ILogger logger, string requestId, int blockNumber, byte[] content)
		{
			__ErrorResponseContentBlockCallback(logger, requestId, blockNumber, content, null);
		}

		[LoggerMessage(16, LogLevel.Information, "Error response [{requestId}] content block {blockNumber}: {content}", SkipEnabledCheck = true, EventName = "ErrorResponseContentTextBlock")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ErrorResponseContentTextBlock(ILogger logger, string requestId, int blockNumber, string content)
		{
			__ErrorResponseContentTextBlockCallback(logger, requestId, blockNumber, content, null);
		}
	}
	internal class PipelineMessageSanitizer
	{
		private const string LogAllValue = "*";

		private readonly bool _logAllHeaders;

		private readonly bool _logFullQueries;

		private readonly string _redactedPlaceholder;

		[ThreadStatic]
		private static StringBuilder? s_cachedStringBuilder;

		private const int MaxCachedStringBuilderCapacity = 1024;

		internal readonly HashSet<string> _allowedQueryParameters;

		internal readonly HashSet<string> _allowedHeaders;

		public PipelineMessageSanitizer(HashSet<string> allowedQueryParameters, HashSet<string> allowedHeaders, string redactedPlaceholder = "REDACTED")
		{
			_logAllHeaders = allowedHeaders.Contains("*");
			_logFullQueries = allowedQueryParameters.Contains("*");
			_allowedQueryParameters = allowedQueryParameters;
			_redactedPlaceholder = redactedPlaceholder;
			_allowedHeaders = allowedHeaders;
		}

		public string SanitizeHeader(string name, string value)
		{
			if (_logAllHeaders || _allowedHeaders.Contains(name))
			{
				return value;
			}
			return _redactedPlaceholder;
		}

		public bool ShouldSanitizeHeaderValue(string name)
		{
			if (_logAllHeaders || _allowedHeaders.Contains(name))
			{
				return false;
			}
			return true;
		}

		public string SanitizeUrl(string url)
		{
			if (_logFullQueries)
			{
				return url;
			}
			int num = url.IndexOf('?');
			if (num == -1)
			{
				return url;
			}
			StringBuilder stringBuilder = null;
			int num2 = num + 1;
			ReadOnlySpan<char> span2 = url.AsSpan(num + 1);
			while (span2.Length > 0)
			{
				int num3 = span2.IndexOf('&');
				int num4 = span2.IndexOf('=');
				bool flag = false;
				if ((num3 == -1 && num4 == -1) || (num3 != -1 && (num4 == -1 || num4 > num3)))
				{
					num4 = num3;
					flag = true;
				}
				if (num4 == -1)
				{
					num4 = span2.Length;
				}
				num3 = ((num3 != -1) ? (num3 + 1) : span2.Length);
				ReadOnlySpan<char> span3 = span2.Slice(0, num4);
				bool flag2 = false;
				foreach (string allowedQueryParameter in _allowedQueryParameters)
				{
					if (MemoryExtensions.Equals(span3, allowedQueryParameter.AsSpan(), StringComparison.OrdinalIgnoreCase))
					{
						flag2 = true;
						break;
					}
				}
				int num5 = num3;
				int length = num4;
				if (flag2 || flag)
				{
					if (stringBuilder == null)
					{
						num2 += num5;
					}
					else
					{
						AppendReadOnlySpan(stringBuilder, span2.Slice(0, num5));
					}
				}
				else
				{
					if (stringBuilder == null)
					{
						stringBuilder = RentStringBuilder(url.Length).Append(url, 0, num2);
					}
					AppendReadOnlySpan(stringBuilder, span2.Slice(0, length)).Append('=').Append(_redactedPlaceholder);
					if (span2[num3 - 1] == '&')
					{
						stringBuilder.Append('&');
					}
				}
				span2 = span2.Slice(num5);
			}
			if (stringBuilder != null)
			{
				return ToStringAndReturnStringBuilder(stringBuilder);
			}
			return url;
			static StringBuilder AppendReadOnlySpan(StringBuilder builder, ReadOnlySpan<char> span)
			{
				ReadOnlySpan<char> readOnlySpan = span;
				for (int i = 0; i < readOnlySpan.Length; i++)
				{
					char value = readOnlySpan[i];
					builder.Append(value);
				}
				return builder;
			}
		}

		private static StringBuilder RentStringBuilder(int capacity)
		{
			if (capacity <= 1024)
			{
				StringBuilder stringBuilder = s_cachedStringBuilder;
				if (stringBuilder != null && stringBuilder.Capacity >= capacity)
				{
					s_cachedStringBuilder = null;
					return stringBuilder;
				}
			}
			return new StringBuilder(capacity);
		}

		private static string ToStringAndReturnStringBuilder(StringBuilder builder)
		{
			string result = builder.ToString();
			if (builder.Capacity <= 1024)
			{
				s_cachedStringBuilder = builder.Clear();
			}
			return result;
		}
	}
	internal class PipelineRetryLogger
	{
		private readonly ILogger<ClientRetryPolicy>? _logger;

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string?, int, double, Exception?> __RequestRetryingCallback = LoggerMessage.Define<string, int, double>(LogLevel.Information, new EventId(10, "RequestRetrying"), "Request [{requestId}] attempt number {retryNumber} took {seconds:00.0}s", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		public PipelineRetryLogger(ILoggerFactory? loggerFactory)
		{
			_logger = loggerFactory?.CreateLogger<ClientRetryPolicy>() ?? null;
		}

		public void LogRequestRetrying(string? requestId, int retryNumber, double seconds)
		{
			if (_logger != null)
			{
				RequestRetrying(_logger, requestId, retryNumber, seconds);
			}
			else
			{
				ClientModelEventSource.Log.RequestRetrying(requestId, retryNumber, seconds);
			}
		}

		[LoggerMessage(10, LogLevel.Information, "Request [{requestId}] attempt number {retryNumber} took {seconds:00.0}s", EventName = "RequestRetrying")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void RequestRetrying(ILogger logger, string? requestId, int retryNumber, double seconds)
		{
			if (logger.IsEnabled(LogLevel.Information))
			{
				__RequestRetryingCallback(logger, requestId, retryNumber, seconds, null);
			}
		}
	}
	internal class PipelineTransportLogger
	{
		private readonly ILogger<PipelineTransport>? _logger;

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, double, Exception?> __ResponseDelayCallback = LoggerMessage.Define<string, double>(LogLevel.Warning, new EventId(7, "ResponseDelay"), "Response [{requestId}] took {seconds:00.0}s", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static readonly Action<ILogger, string, Exception?> __ExceptionResponseCallback = LoggerMessage.Define<string>(LogLevel.Information, new EventId(18, "ExceptionResponse"), "Request [{requestId}] exception occurred.", new LogDefineOptions
		{
			SkipEnabledCheck = true
		});

		public PipelineTransportLogger(ILoggerFactory? loggerFactory)
		{
			_logger = loggerFactory?.CreateLogger<PipelineTransport>() ?? null;
		}

		public void LogResponseDelay(string requestId, double seconds)
		{
			if (_logger != null)
			{
				ResponseDelay(_logger, requestId, seconds);
			}
			else
			{
				ClientModelEventSource.Log.ResponseDelay(requestId, seconds);
			}
		}

		[LoggerMessage(7, LogLevel.Warning, "Response [{requestId}] took {seconds:00.0}s", EventName = "ResponseDelay")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ResponseDelay(ILogger logger, string requestId, double seconds)
		{
			if (logger.IsEnabled(LogLevel.Warning))
			{
				__ResponseDelayCallback(logger, requestId, seconds, null);
			}
		}

		public void LogExceptionResponse(string requestId, Exception exception)
		{
			if (_logger != null)
			{
				ExceptionResponse(_logger, requestId, exception);
			}
			else if (ClientModelEventSource.Log.IsEnabled(EventLevel.Informational, EventKeywords.None))
			{
				ClientModelEventSource.Log.ExceptionResponse(requestId, exception.ToString());
			}
		}

		[LoggerMessage(18, LogLevel.Information, "Request [{requestId}] exception occurred.", EventName = "ExceptionResponse")]
		[GeneratedCode("Microsoft.Extensions.Logging.Generators", "8.0.12.6609")]
		private static void ExceptionResponse(ILogger logger, string requestId, Exception exception)
		{
			if (logger.IsEnabled(LogLevel.Information))
			{
				__ExceptionResponseCallback(logger, requestId, exception);
			}
		}
	}
	internal sealed class PollingInterval
	{
		private static readonly TimeSpan DefaultDelay = TimeSpan.FromSeconds(1.0);

		private readonly TimeSpan _interval;

		public PollingInterval(TimeSpan? interval = null)
		{
			_interval = interval ?? DefaultDelay;
		}

		public async Task WaitAsync(PipelineResponse response, CancellationToken cancellationToken)
		{
			await Task.Delay(GetDelay(response), cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public void Wait(PipelineResponse response, CancellationToken cancellationToken)
		{
			TimeSpan delay = GetDelay(response);
			if (!cancellationToken.CanBeCanceled)
			{
				Thread.Sleep(delay);
			}
			else if (cancellationToken.WaitHandle.WaitOne(delay))
			{
				cancellationToken.ThrowIfCancellationRequested();
			}
		}

		private TimeSpan GetDelay(PipelineResponse response)
		{
			if (!PipelineResponseHeaders.TryGetRetryAfter(response, out var value) || !(value > _interval))
			{
				return _interval;
			}
			return value;
		}
	}
	internal class ReadTimeoutStream : Stream
	{
		private readonly Stream _stream;

		private TimeSpan _readTimeout;

		private CancellationTokenSource _cancellationTokenSource;

		public override bool CanRead => _stream.CanRead;

		public override bool CanSeek => _stream.CanSeek;

		public override bool CanWrite => false;

		public override long Length => _stream.Length;

		public override long Position
		{
			get
			{
				return _stream.Position;
			}
			set
			{
				_stream.Position = value;
			}
		}

		public override int ReadTimeout
		{
			get
			{
				return (int)_readTimeout.TotalMilliseconds;
			}
			set
			{
				_readTimeout = TimeSpan.FromMilliseconds(value);
				UpdateReadTimeout();
			}
		}

		public ReadTimeoutStream(Stream stream, TimeSpan readTimeout)
		{
			_stream = stream;
			_readTimeout = readTimeout;
			UpdateReadTimeout();
			InitializeTokenSource();
		}

		public override void Close()
		{
			_stream.Close();
		}

		public override void Flush()
		{
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			bool dispose;
			CancellationTokenSource cancellationTokenSource = StartTimeout(default(CancellationToken), out dispose);
			try
			{
				return _stream.Read(buffer, offset, count);
			}
			catch (IOException innerException)
			{
				CancellationHelper.ThrowIfCancellationRequestedOrTimeout(default(CancellationToken), cancellationTokenSource.Token, innerException, _readTimeout);
				throw;
			}
			catch (ObjectDisposedException innerException2)
			{
				CancellationHelper.ThrowIfCancellationRequestedOrTimeout(default(CancellationToken), cancellationTokenSource.Token, innerException2, _readTimeout);
				throw;
			}
			catch (OperationCanceledException innerException3)
			{
				CancellationHelper.ThrowIfCancellationRequestedOrTimeout(default(CancellationToken), cancellationTokenSource.Token, innerException3, _readTimeout);
				throw;
			}
			finally
			{
				StopTimeout(cancellationTokenSource, dispose);
			}
		}

		public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			bool dispose;
			CancellationTokenSource source = StartTimeout(cancellationToken, out dispose);
			try
			{
				return await _stream.ReadAsync(buffer, offset, count, source.Token).ConfigureAwait(continueOnCapturedContext: false);
			}
			catch (IOException innerException)
			{
				CancellationHelper.ThrowIfCancellationRequestedOrTimeout(cancellationToken, source.Token, innerException, _readTimeout);
				throw;
			}
			catch (ObjectDisposedException innerException2)
			{
				CancellationHelper.ThrowIfCancellationRequestedOrTimeout(cancellationToken, source.Token, innerException2, _readTimeout);
				throw;
			}
			catch (OperationCanceledException innerException3)
			{
				CancellationHelper.ThrowIfCancellationRequestedOrTimeout(cancellationToken, source.Token, innerException3, _readTimeout);
				throw;
			}
			finally
			{
				StopTimeout(source, dispose);
			}
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			return _stream.Seek(offset, origin);
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		private CancellationTokenSource StartTimeout(CancellationToken additionalToken, out bool dispose)
		{
			if (_cancellationTokenSource.IsCancellationRequested)
			{
				InitializeTokenSource();
			}
			CancellationTokenSource result;
			if (additionalToken.CanBeCanceled)
			{
				result = CancellationTokenSource.CreateLinkedTokenSource(additionalToken, _cancellationTokenSource.Token);
				dispose = true;
			}
			else
			{
				result = _cancellationTokenSource;
				dispose = false;
			}
			_cancellationTokenSource.CancelAfter(_readTimeout);
			return result;
		}

		private void InitializeTokenSource()
		{
			_cancellationTokenSource = new CancellationTokenSource();
			_cancellationTokenSource.Token.Register(delegate(object state)
			{
				((ReadTimeoutStream)state).DisposeStream();
			}, this);
		}

		private void StopTimeout(CancellationTokenSource source, bool dispose)
		{
			_cancellationTokenSource.CancelAfter(Timeout.InfiniteTimeSpan);
			if (dispose)
			{
				source.Dispose();
			}
		}

		private void UpdateReadTimeout()
		{
			try
			{
				if (_stream.CanTimeout)
				{
					_stream.ReadTimeout = (int)_readTimeout.TotalMilliseconds;
				}
			}
			catch
			{
			}
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			_stream.Dispose();
			_cancellationTokenSource.Dispose();
		}

		private void DisposeStream()
		{
			_stream.Dispose();
		}
	}
	internal class RuntimeInformationWrapper
	{
		public virtual string FrameworkDescription => RuntimeInformation.FrameworkDescription;

		public virtual string OSDescription => RuntimeInformation.OSDescription;

		public virtual Architecture OSArchitecture => RuntimeInformation.OSArchitecture;

		public virtual Architecture ProcessArchitecture => RuntimeInformation.ProcessArchitecture;

		public virtual bool IsOSPlatform(OSPlatform osPlatform)
		{
			return RuntimeInformation.IsOSPlatform(osPlatform);
		}
	}
	internal static class ServicePointHelpers
	{
		private const int RuntimeDefaultConnectionLimit = 2;

		private const int IncreasedConnectionLimit = 50;

		private const int IncreasedConnectionLeaseTimeout = 300000;

		private static TimeSpan DefaultConnectionLeaseTimeoutTimeSpan = Timeout.InfiniteTimeSpan;

		private static TimeSpan IncreasedConnectionLeaseTimeoutTimeSpan = TimeSpan.FromMilliseconds(300000.0);

		public static void SetLimits(HttpMessageHandler messageHandler)
		{
			if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("BROWSER")))
			{
				return;
			}
			try
			{
				if (messageHandler is HttpClientHandler httpClientHandler && httpClientHandler.MaxConnectionsPerServer == 2)
				{
					httpClientHandler.MaxConnectionsPerServer = 50;
				}
			}
			catch (NotSupportedException)
			{
			}
			catch (NotImplementedException)
			{
			}
		}
	}
	internal static class TaskExtensions
	{
		public readonly struct Enumerable<T> : IEnumerable<T>, IEnumerable
		{
			private readonly IAsyncEnumerable<T> _asyncEnumerable;

			public Enumerable(IAsyncEnumerable<T> asyncEnumerable)
			{
				_asyncEnumerable = asyncEnumerable;
			}

			public Enumerator<T> GetEnumerator()
			{
				return new Enumerator<T>(_asyncEnumerable.GetAsyncEnumerator());
			}

			IEnumerator<T> IEnumerable<T>.GetEnumerator()
			{
				return new Enumerator<T>(_asyncEnumerable.GetAsyncEnumerator());
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		public readonly struct Enumerator<T> : IEnumerator<T>, IEnumerator, IDisposable
		{
			private readonly IAsyncEnumerator<T> _asyncEnumerator;

			public T Current => _asyncEnumerator.Current;

			object? IEnumerator.Current => Current;

			public Enumerator(IAsyncEnumerator<T> asyncEnumerator)
			{
				_asyncEnumerator = asyncEnumerator;
			}

			public bool MoveNext()
			{
				return _asyncEnumerator.MoveNextAsync().EnsureCompleted();
			}

			public void Reset()
			{
				throw new NotSupportedException($"{GetType()} is a synchronous wrapper for {_asyncEnumerator.GetType()} async enumerator, which can't be reset, so IEnumerable.Reset() calls aren't supported.");
			}

			public void Dispose()
			{
				_asyncEnumerator.DisposeAsync().EnsureCompleted();
			}
		}

		public readonly struct WithCancellationTaskAwaitable
		{
			private readonly CancellationToken _cancellationToken;

			private readonly ConfiguredTaskAwaitable _awaitable;

			public WithCancellationTaskAwaitable(Task task, CancellationToken cancellationToken)
			{
				_awaitable = task.ConfigureAwait(continueOnCapturedContext: false);
				_cancellationToken = cancellationToken;
			}

			public WithCancellationTaskAwaiter GetAwaiter()
			{
				ConfiguredTaskAwaitable awaitable = _awaitable;
				return new WithCancellationTaskAwaiter(awaitable.GetAwaiter(), _cancellationToken);
			}
		}

		public readonly struct WithCancellationTaskAwaitable<T>
		{
			private readonly CancellationToken _cancellationToken;

			private readonly ConfiguredTaskAwaitable<T> _awaitable;

			public WithCancellationTaskAwaitable(Task<T> task, CancellationToken cancellationToken)
			{
				_awaitable = task.ConfigureAwait(continueOnCapturedContext: false);
				_cancellationToken = cancellationToken;
			}

			public WithCancellationTaskAwaiter<T> GetAwaiter()
			{
				ConfiguredTaskAwaitable<T> awaitable = _awaitable;
				return new WithCancellationTaskAwaiter<T>(awaitable.GetAwaiter(), _cancellationToken);
			}
		}

		public readonly struct WithCancellationValueTaskAwaitable<T>
		{
			private readonly CancellationToken _cancellationToken;

			private readonly ConfiguredValueTaskAwaitable<T> _awaitable;

			public WithCancellationValueTaskAwaitable(ValueTask<T> task, CancellationToken cancellationToken)
			{
				_awaitable = task.ConfigureAwait(continueOnCapturedContext: false);
				_cancellationToken = cancellationToken;
			}

			public WithCancellationValueTaskAwaiter<T> GetAwaiter()
			{
				return new WithCancellationValueTaskAwaiter<T>(_awaitable.GetAwaiter(), _cancellationToken);
			}
		}

		public readonly struct WithCancellationTaskAwaiter : ICriticalNotifyCompletion, INotifyCompletion
		{
			private readonly CancellationToken _cancellationToken;

			private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter _taskAwaiter;

			public bool IsCompleted
			{
				get
				{
					ConfiguredTaskAwaitable.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter;
					if (!taskAwaiter.IsCompleted)
					{
						CancellationToken cancellationToken = _cancellationToken;
						return cancellationToken.IsCancellationRequested;
					}
					return true;
				}
			}

			public WithCancellationTaskAwaiter(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter, CancellationToken cancellationToken)
			{
				_taskAwaiter = awaiter;
				_cancellationToken = cancellationToken;
			}

			public void OnCompleted(Action continuation)
			{
				ConfiguredTaskAwaitable.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter;
				taskAwaiter.OnCompleted(WrapContinuation(in continuation));
			}

			public void UnsafeOnCompleted(Action continuation)
			{
				ConfiguredTaskAwaitable.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter;
				taskAwaiter.UnsafeOnCompleted(WrapContinuation(in continuation));
			}

			public void GetResult()
			{
				ConfiguredTaskAwaitable.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter;
				if (!taskAwaiter.IsCompleted)
				{
					CancellationToken cancellationToken = _cancellationToken;
					cancellationToken.ThrowIfCancellationRequested();
				}
				taskAwaiter = _taskAwaiter;
				taskAwaiter.GetResult();
			}

			private Action WrapContinuation(in Action originalContinuation)
			{
				CancellationToken cancellationToken = _cancellationToken;
				if (!cancellationToken.CanBeCanceled)
				{
					return originalContinuation;
				}
				return new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation;
			}
		}

		public readonly struct WithCancellationTaskAwaiter<T> : ICriticalNotifyCompletion, INotifyCompletion
		{
			private readonly CancellationToken _cancellationToken;

			private readonly ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter _taskAwaiter;

			public bool IsCompleted
			{
				get
				{
					ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter;
					if (!taskAwaiter.IsCompleted)
					{
						CancellationToken cancellationToken = _cancellationToken;
						return cancellationToken.IsCancellationRequested;
					}
					return true;
				}
			}

			public WithCancellationTaskAwaiter(ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter awaiter, CancellationToken cancellationToken)
			{
				_taskAwaiter = awaiter;
				_cancellationToken = cancellationToken;
			}

			public void OnCompleted(Action continuation)
			{
				ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter;
				taskAwaiter.OnCompleted(WrapContinuation(in continuation));
			}

			public void UnsafeOnCompleted(Action continuation)
			{
				ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter;
				taskAwaiter.UnsafeOnCompleted(WrapContinuation(in continuation));
			}

			public T GetResult()
			{
				ConfiguredTaskAwaitable<T>.ConfiguredTaskAwaiter taskAwaiter = _taskAwaiter;
				if (!taskAwaiter.IsCompleted)
				{
					CancellationToken cancellationToken = _cancellationToken;
					cancellationToken.ThrowIfCancellationRequested();
				}
				taskAwaiter = _taskAwaiter;
				return taskAwaiter.GetResult();
			}

			private Action WrapContinuation(in Action originalContinuation)
			{
				CancellationToken cancellationToken = _cancellationToken;
				if (!cancellationToken.CanBeCanceled)
				{
					return originalContinuation;
				}
				return new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation;
			}
		}

		public readonly struct WithCancellationValueTaskAwaiter<T> : ICriticalNotifyCompletion, INotifyCompletion
		{
			private readonly CancellationToken _cancellationToken;

			private readonly ConfiguredValueTaskAwaitable<T>.ConfiguredValueTaskAwaiter _taskAwaiter;

			public bool IsCompleted
			{
				get
				{
					if (!_taskAwaiter.IsCompleted)
					{
						CancellationToken cancellationToken = _cancellationToken;
						return cancellationToken.IsCancellationRequested;
					}
					return true;
				}
			}

			public WithCancellationValueTaskAwaiter(ConfiguredValueTaskAwaitable<T>.ConfiguredValueTaskAwaiter awaiter, CancellationToken cancellationToken)
			{
				_taskAwaiter = awaiter;
				_cancellationToken = cancellationToken;
			}

			public void OnCompleted(Action continuation)
			{
				_taskAwaiter.OnCompleted(WrapContinuation(in continuation));
			}

			public void UnsafeOnCompleted(Action continuation)
			{
				_taskAwaiter.UnsafeOnCompleted(WrapContinuation(in continuation));
			}

			public T GetResult()
			{
				if (!_taskAwaiter.IsCompleted)
				{
					CancellationToken cancellationToken = _cancellationToken;
					cancellationToken.ThrowIfCancellationRequested();
				}
				return _taskAwaiter.GetResult();
			}

			private Action WrapContinuation(in Action originalContinuation)
			{
				CancellationToken cancellationToken = _cancellationToken;
				if (!cancellationToken.CanBeCanceled)
				{
					return originalContinuation;
				}
				return new WithCancellationContinuationWrapper(originalContinuation, _cancellationToken).Continuation;
			}
		}

		private class WithCancellationContinuationWrapper
		{
			private Action? _originalContinuation;

			private readonly CancellationTokenRegistration _registration;

			public Action Continuation { get; }

			public WithCancellationContinuationWrapper(Action originalContinuation, CancellationToken cancellationToken)
			{
				Action callback = ContinuationImplementation;
				_originalContinuation = originalContinuation;
				_registration = cancellationToken.Register(callback);
				Continuation = callback;
			}

			private void ContinuationImplementation()
			{
				Action action = Interlocked.Exchange(ref _originalContinuation, null);
				if (action != null)
				{
					CancellationTokenRegistration registration = _registration;
					registration.Dispose();
					action();
				}
			}
		}

		public static WithCancellationTaskAwaitable AwaitWithCancellation(this Task task, CancellationToken cancellationToken)
		{
			return new WithCancellationTaskAwaitable(task, cancellationToken);
		}

		public static WithCancellationTaskAwaitable<T> AwaitWithCancellation<T>(this Task<T> task, CancellationToken cancellationToken)
		{
			return new WithCancellationTaskAwaitable<T>(task, cancellationToken);
		}

		public static WithCancellationValueTaskAwaitable<T> AwaitWithCancellation<T>(this ValueTask<T> task, CancellationToken cancellationToken)
		{
			return new WithCancellationValueTaskAwaitable<T>(task, cancellationToken);
		}

		public static T EnsureCompleted<T>(this Task<T> task)
		{
			return task.GetAwaiter().GetResult();
		}

		public static void EnsureCompleted(this Task task)
		{
			task.GetAwaiter().GetResult();
		}

		public static T EnsureCompleted<T>(this ValueTask<T> task)
		{
			return task.GetAwaiter().GetResult();
		}

		public static vo

BepInEx/core/System.Collections.Immutable.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using FxResources.System.Collections.Immutable;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.Collections.Immutable.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Collections.Immutable")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("This package provides collections that are thread safe and guaranteed to never change their contents, also known as immutable collections. Like strings, any methods that perform modifications will not change the existing instance but instead return a new instance. For efficiency reasons, the implementation uses a sharing mechanism to ensure that newly created instances share as much data as possible with the previous instance while ensuring that operations have a predictable time complexity.\r\n\r\nThe System.Collections.Immutable library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Collections.Immutable")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(true)]
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 ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.System.Collections.Immutable
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey");

		internal static string ArrayInitializedStateNotEqual => GetResourceString("ArrayInitializedStateNotEqual");

		internal static string ArrayLengthsNotEqual => GetResourceString("ArrayLengthsNotEqual");

		internal static string CannotFindOldValue => GetResourceString("CannotFindOldValue");

		internal static string CapacityMustBeGreaterThanOrEqualToCount => GetResourceString("CapacityMustBeGreaterThanOrEqualToCount");

		internal static string CapacityMustEqualCountOnMove => GetResourceString("CapacityMustEqualCountOnMove");

		internal static string CollectionModifiedDuringEnumeration => GetResourceString("CollectionModifiedDuringEnumeration");

		internal static string DuplicateKey => GetResourceString("DuplicateKey");

		internal static string InvalidEmptyOperation => GetResourceString("InvalidEmptyOperation");

		internal static string InvalidOperationOnDefaultArray => GetResourceString("InvalidOperationOnDefaultArray");

		internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow");

		internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported");

		internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound");

		internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall");

		internal static string Argument_IncompatibleArrayType => GetResourceString("Argument_IncompatibleArrayType");

		internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum");

		internal static string InvalidOperation_IncompatibleComparer => GetResourceString("InvalidOperation_IncompatibleComparer");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Linq
{
	public static class ImmutableArrayExtensions
	{
		public static IEnumerable<TResult> Select<T, TResult>(this ImmutableArray<T> immutableArray, Func<T, TResult> selector)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			return immutableArray.array.Select(selector);
		}

		public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>(this ImmutableArray<TSource> immutableArray, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			if (collectionSelector == null || resultSelector == null)
			{
				return Enumerable.SelectMany(immutableArray, collectionSelector, resultSelector);
			}
			if (immutableArray.Length != 0)
			{
				return immutableArray.SelectManyIterator(collectionSelector, resultSelector);
			}
			return Enumerable.Empty<TResult>();
		}

		public static IEnumerable<T> Where<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			return immutableArray.array.Where(predicate);
		}

		public static bool Any<T>(this ImmutableArray<T> immutableArray)
		{
			return immutableArray.Length > 0;
		}

		public static bool Any<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			Requires.NotNull(predicate, "predicate");
			T[] array = immutableArray.array;
			foreach (T arg in array)
			{
				if (predicate(arg))
				{
					return true;
				}
			}
			return false;
		}

		public static bool All<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			Requires.NotNull(predicate, "predicate");
			T[] array = immutableArray.array;
			foreach (T arg in array)
			{
				if (!predicate(arg))
				{
					return false;
				}
			}
			return true;
		}

		public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, IEqualityComparer<TBase>? comparer = null) where TDerived : TBase
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			items.ThrowNullRefIfNotInitialized();
			if (immutableArray.array == items.array)
			{
				return true;
			}
			if (immutableArray.Length != items.Length)
			{
				return false;
			}
			if (comparer == null)
			{
				comparer = EqualityComparer<TBase>.Default;
			}
			for (int i = 0; i < immutableArray.Length; i++)
			{
				if (!comparer.Equals(immutableArray.array[i], (TBase)(object)items.array[i]))
				{
					return false;
				}
			}
			return true;
		}

		public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, IEnumerable<TDerived> items, IEqualityComparer<TBase>? comparer = null) where TDerived : TBase
		{
			Requires.NotNull(items, "items");
			if (comparer == null)
			{
				comparer = EqualityComparer<TBase>.Default;
			}
			int num = 0;
			int length = immutableArray.Length;
			foreach (TDerived item in items)
			{
				if (num == length)
				{
					return false;
				}
				if (!comparer.Equals(immutableArray[num], (TBase)(object)item))
				{
					return false;
				}
				num++;
			}
			return num == length;
		}

		public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, Func<TBase, TBase, bool> predicate) where TDerived : TBase
		{
			Requires.NotNull(predicate, "predicate");
			immutableArray.ThrowNullRefIfNotInitialized();
			items.ThrowNullRefIfNotInitialized();
			if (immutableArray.array == items.array)
			{
				return true;
			}
			if (immutableArray.Length != items.Length)
			{
				return false;
			}
			int i = 0;
			for (int length = immutableArray.Length; i < length; i++)
			{
				if (!predicate(immutableArray[i], (TBase)(object)items[i]))
				{
					return false;
				}
			}
			return true;
		}

		public static T? Aggregate<T>(this ImmutableArray<T> immutableArray, Func<T, T, T> func)
		{
			Requires.NotNull(func, "func");
			if (immutableArray.Length == 0)
			{
				return default(T);
			}
			T val = immutableArray[0];
			int i = 1;
			for (int length = immutableArray.Length; i < length; i++)
			{
				val = func(val, immutableArray[i]);
			}
			return val;
		}

		public static TAccumulate Aggregate<TAccumulate, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func)
		{
			Requires.NotNull(func, "func");
			TAccumulate val = seed;
			T[] array = immutableArray.array;
			foreach (T arg in array)
			{
				val = func(val, arg);
			}
			return val;
		}

		public static TResult Aggregate<TAccumulate, TResult, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func, Func<TAccumulate, TResult> resultSelector)
		{
			Requires.NotNull(resultSelector, "resultSelector");
			return resultSelector(immutableArray.Aggregate(seed, func));
		}

		public static T ElementAt<T>(this ImmutableArray<T> immutableArray, int index)
		{
			return immutableArray[index];
		}

		public static T? ElementAtOrDefault<T>(this ImmutableArray<T> immutableArray, int index)
		{
			if (index < 0 || index >= immutableArray.Length)
			{
				return default(T);
			}
			return immutableArray[index];
		}

		public static T First<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			Requires.NotNull(predicate, "predicate");
			T[] array = immutableArray.array;
			foreach (T val in array)
			{
				if (predicate(val))
				{
					return val;
				}
			}
			return Enumerable.Empty<T>().First();
		}

		public static T First<T>(this ImmutableArray<T> immutableArray)
		{
			if (immutableArray.Length <= 0)
			{
				return immutableArray.array.First();
			}
			return immutableArray[0];
		}

		public static T? FirstOrDefault<T>(this ImmutableArray<T> immutableArray)
		{
			if (immutableArray.array.Length == 0)
			{
				return default(T);
			}
			return immutableArray.array[0];
		}

		public static T? FirstOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			Requires.NotNull(predicate, "predicate");
			T[] array = immutableArray.array;
			foreach (T val in array)
			{
				if (predicate(val))
				{
					return val;
				}
			}
			return default(T);
		}

		public static T Last<T>(this ImmutableArray<T> immutableArray)
		{
			if (immutableArray.Length <= 0)
			{
				return immutableArray.array.Last();
			}
			return immutableArray[immutableArray.Length - 1];
		}

		public static T Last<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			Requires.NotNull(predicate, "predicate");
			for (int num = immutableArray.Length - 1; num >= 0; num--)
			{
				if (predicate(immutableArray[num]))
				{
					return immutableArray[num];
				}
			}
			return Enumerable.Empty<T>().Last();
		}

		public static T? LastOrDefault<T>(this ImmutableArray<T> immutableArray)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			return immutableArray.array.LastOrDefault();
		}

		public static T? LastOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			Requires.NotNull(predicate, "predicate");
			for (int num = immutableArray.Length - 1; num >= 0; num--)
			{
				if (predicate(immutableArray[num]))
				{
					return immutableArray[num];
				}
			}
			return default(T);
		}

		public static T Single<T>(this ImmutableArray<T> immutableArray)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			return immutableArray.array.Single();
		}

		public static T Single<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			Requires.NotNull(predicate, "predicate");
			bool flag = true;
			T result = default(T);
			T[] array = immutableArray.array;
			foreach (T val in array)
			{
				if (predicate(val))
				{
					if (!flag)
					{
						ImmutableArray.TwoElementArray.Single();
					}
					flag = false;
					result = val;
				}
			}
			if (flag)
			{
				Enumerable.Empty<T>().Single();
			}
			return result;
		}

		public static T? SingleOrDefault<T>(this ImmutableArray<T> immutableArray)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			return immutableArray.array.SingleOrDefault();
		}

		public static T? SingleOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate)
		{
			Requires.NotNull(predicate, "predicate");
			bool flag = true;
			T result = default(T);
			T[] array = immutableArray.array;
			foreach (T val in array)
			{
				if (predicate(val))
				{
					if (!flag)
					{
						ImmutableArray.TwoElementArray.Single();
					}
					flag = false;
					result = val;
				}
			}
			return result;
		}

		public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector) where TKey : notnull
		{
			return immutableArray.ToDictionary(keySelector, EqualityComparer<TKey>.Default);
		}

		public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector) where TKey : notnull
		{
			return immutableArray.ToDictionary(keySelector, elementSelector, EqualityComparer<TKey>.Default);
		}

		public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, IEqualityComparer<TKey>? comparer) where TKey : notnull
		{
			Requires.NotNull(keySelector, "keySelector");
			Dictionary<TKey, T> dictionary = new Dictionary<TKey, T>(immutableArray.Length, comparer);
			ImmutableArray<T>.Enumerator enumerator = immutableArray.GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				dictionary.Add(keySelector(current), current);
			}
			return dictionary;
		}

		public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector, IEqualityComparer<TKey>? comparer) where TKey : notnull
		{
			Requires.NotNull(keySelector, "keySelector");
			Requires.NotNull(elementSelector, "elementSelector");
			Dictionary<TKey, TElement> dictionary = new Dictionary<TKey, TElement>(immutableArray.Length, comparer);
			T[] array = immutableArray.array;
			foreach (T arg in array)
			{
				dictionary.Add(keySelector(arg), elementSelector(arg));
			}
			return dictionary;
		}

		public static T[] ToArray<T>(this ImmutableArray<T> immutableArray)
		{
			immutableArray.ThrowNullRefIfNotInitialized();
			if (immutableArray.array.Length == 0)
			{
				return ImmutableArray<T>.Empty.array;
			}
			return (T[])immutableArray.array.Clone();
		}

		public static T First<T>(this ImmutableArray<T>.Builder builder)
		{
			Requires.NotNull(builder, "builder");
			if (!builder.Any())
			{
				throw new InvalidOperationException();
			}
			return builder[0];
		}

		public static T? FirstOrDefault<T>(this ImmutableArray<T>.Builder builder)
		{
			Requires.NotNull(builder, "builder");
			if (!builder.Any())
			{
				return default(T);
			}
			return builder[0];
		}

		public static T Last<T>(this ImmutableArray<T>.Builder builder)
		{
			Requires.NotNull(builder, "builder");
			if (!builder.Any())
			{
				throw new InvalidOperationException();
			}
			return builder[builder.Count - 1];
		}

		public static T? LastOrDefault<T>(this ImmutableArray<T>.Builder builder)
		{
			Requires.NotNull(builder, "builder");
			if (!builder.Any())
			{
				return default(T);
			}
			return builder[builder.Count - 1];
		}

		public static bool Any<T>(this ImmutableArray<T>.Builder builder)
		{
			Requires.NotNull(builder, "builder");
			return builder.Count > 0;
		}

		private static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>(this ImmutableArray<TSource> immutableArray, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector)
		{
			TSource[] array = immutableArray.array;
			foreach (TSource item in array)
			{
				foreach (TCollection item2 in collectionSelector(item))
				{
					yield return resultSelector(item, item2);
				}
			}
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
}
namespace System.Runtime.InteropServices
{
	public static class ImmutableCollectionsMarshal
	{
		public static ImmutableArray<T> AsImmutableArray<T>(T[]? array)
		{
			return new ImmutableArray<T>(array);
		}

		public static T[]? AsArray<T>(ImmutableArray<T> array)
		{
			return array.array;
		}
	}
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string? EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type? StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)]
	internal sealed class CollectionBuilderAttribute : Attribute
	{
		public Type BuilderType { get; }

		public string MethodName { get; }

		public CollectionBuilderAttribute(Type builderType, string methodName)
		{
			BuilderType = builderType;
			MethodName = methodName;
		}
	}
}
namespace System.Numerics
{
	internal static class BitOperations
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint RotateLeft(uint value, int offset)
		{
			return (value << offset) | (value >> 32 - offset);
		}
	}
}
namespace System.Collections
{
	internal static class ThrowHelper
	{
		public static void ThrowIfNull(object arg, [CallerArgumentExpression("arg")] string? paramName = null)
		{
			if (arg == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		public static void ThrowIfDestinationTooSmall()
		{
			throw new ArgumentException(System.SR.CapacityMustBeGreaterThanOrEqualToCount, "destination");
		}

		[DoesNotReturn]
		public static void ThrowArgumentNullException(string? paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		[DoesNotReturn]
		public static void ThrowKeyNotFoundException()
		{
			throw new KeyNotFoundException();
		}

		[DoesNotReturn]
		public static void ThrowKeyNotFoundException<TKey>(TKey key)
		{
			throw new KeyNotFoundException(System.SR.Format(System.SR.Arg_KeyNotFoundWithKey, key));
		}

		[DoesNotReturn]
		public static void ThrowInvalidOperationException()
		{
			throw new InvalidOperationException();
		}

		[DoesNotReturn]
		internal static void ThrowIncompatibleComparer()
		{
			throw new InvalidOperationException(System.SR.InvalidOperation_IncompatibleComparer);
		}
	}
	internal static class HashHelpers
	{
		public const uint HashCollisionThreshold = 100u;

		public const int MaxPrimeArrayLength = 2147483587;

		public const int HashPrime = 101;

		internal static ReadOnlySpan<int> Primes
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6;
				if (obj == null)
				{
					obj = new int[72]
					{
						3, 7, 11, 17, 23, 29, 37, 47, 59, 71,
						89, 107, 131, 163, 197, 239, 293, 353, 431, 521,
						631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371,
						4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023,
						25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363,
						156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403,
						968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559,
						5999471, 7199369
					};
					global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6 = (int[])obj;
				}
				return new ReadOnlySpan<int>((int[]?)obj);
			}
		}

		public static bool IsPrime(int candidate)
		{
			if (((uint)candidate & (true ? 1u : 0u)) != 0)
			{
				int num = (int)Math.Sqrt(candidate);
				for (int i = 3; i <= num; i += 2)
				{
					if (candidate % i == 0)
					{
						return false;
					}
				}
				return true;
			}
			return candidate == 2;
		}

		public static int GetPrime(int min)
		{
			if (min < 0)
			{
				throw new ArgumentException(System.SR.Arg_HTCapacityOverflow);
			}
			ReadOnlySpan<int> primes = Primes;
			for (int i = 0; i < primes.Length; i++)
			{
				int num = primes[i];
				if (num >= min)
				{
					return num;
				}
			}
			for (int j = min | 1; j < int.MaxValue; j += 2)
			{
				if (IsPrime(j) && (j - 1) % 101 != 0)
				{
					return j;
				}
			}
			return min;
		}

		public static int ExpandPrime(int oldSize)
		{
			int num = 2 * oldSize;
			if ((uint)num > 2147483587u && 2147483587 > oldSize)
			{
				return 2147483587;
			}
			return GetPrime(num);
		}

		public static ulong GetFastModMultiplier(uint divisor)
		{
			return ulong.MaxValue / (ulong)divisor + 1;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static uint FastMod(uint value, uint divisor, ulong multiplier)
		{
			return (uint)(((multiplier * value >> 32) + 1) * divisor >> 32);
		}
	}
}
namespace System.Collections.Immutable
{
	internal static class AllocFreeConcurrentStack<T>
	{
		private const int MaxSize = 35;

		private static readonly Type s_typeOfT = typeof(T);

		private static Stack<RefAsValueType<T>> ThreadLocalStack
		{
			get
			{
				Dictionary<Type, object> dictionary = AllocFreeConcurrentStack.t_stacks ?? (AllocFreeConcurrentStack.t_stacks = new Dictionary<Type, object>());
				if (!dictionary.TryGetValue(s_typeOfT, out var value))
				{
					value = new Stack<RefAsValueType<T>>(35);
					dictionary.Add(s_typeOfT, value);
				}
				return (Stack<RefAsValueType<T>>)value;
			}
		}

		public static void TryAdd(T item)
		{
			Stack<RefAsValueType<T>> threadLocalStack = ThreadLocalStack;
			if (threadLocalStack.Count < 35)
			{
				threadLocalStack.Push(new RefAsValueType<T>(item));
			}
		}

		public static bool TryTake([MaybeNullWhen(false)] out T item)
		{
			Stack<RefAsValueType<T>> threadLocalStack = ThreadLocalStack;
			if (threadLocalStack != null && threadLocalStack.Count > 0)
			{
				item = threadLocalStack.Pop().Value;
				return true;
			}
			item = default(T);
			return false;
		}
	}
	internal static class AllocFreeConcurrentStack
	{
		[ThreadStatic]
		internal static Dictionary<Type, object>? t_stacks;
	}
	internal sealed class DictionaryEnumerator<TKey, TValue> : IDictionaryEnumerator, IEnumerator where TKey : notnull
	{
		private readonly IEnumerator<KeyValuePair<TKey, TValue>> _inner;

		public DictionaryEntry Entry => new DictionaryEntry(_inner.Current.Key, _inner.Current.Value);

		public object Key => _inner.Current.Key;

		public object? Value => _inner.Current.Value;

		public object Current => Entry;

		internal DictionaryEnumerator(IEnumerator<KeyValuePair<TKey, TValue>> inner)
		{
			Requires.NotNull(inner, "inner");
			_inner = inner;
		}

		public bool MoveNext()
		{
			return _inner.MoveNext();
		}

		public void Reset()
		{
			_inner.Reset();
		}
	}
	internal struct DisposableEnumeratorAdapter<T, TEnumerator> : IDisposable where TEnumerator : struct, IEnumerator<T>
	{
		private readonly IEnumerator<T> _enumeratorObject;

		private TEnumerator _enumeratorStruct;

		public T Current
		{
			get
			{
				if (_enumeratorObject == null)
				{
					return _enumeratorStruct.Current;
				}
				return _enumeratorObject.Current;
			}
		}

		internal DisposableEnumeratorAdapter(TEnumerator enumerator)
		{
			_enumeratorStruct = enumerator;
			_enumeratorObject = null;
		}

		internal DisposableEnumeratorAdapter(IEnumerator<T> enumerator)
		{
			_enumeratorStruct = default(TEnumerator);
			_enumeratorObject = enumerator;
		}

		public bool MoveNext()
		{
			if (_enumeratorObject == null)
			{
				return _enumeratorStruct.MoveNext();
			}
			return _enumeratorObject.MoveNext();
		}

		public void Dispose()
		{
			if (_enumeratorObject != null)
			{
				_enumeratorObject.Dispose();
			}
			else
			{
				_enumeratorStruct.Dispose();
			}
		}

		public DisposableEnumeratorAdapter<T, TEnumerator> GetEnumerator()
		{
			return this;
		}
	}
	internal interface IBinaryTree
	{
		int Height { get; }

		bool IsEmpty { get; }

		int Count { get; }

		IBinaryTree? Left { get; }

		IBinaryTree? Right { get; }
	}
	internal interface IBinaryTree<out T> : IBinaryTree
	{
		T Value { get; }

		new IBinaryTree<T>? Left { get; }

		new IBinaryTree<T>? Right { get; }
	}
	internal interface IImmutableArray
	{
		Array? Array { get; }
	}
	public interface IImmutableDictionary<TKey, TValue> : IReadOnlyDictionary<TKey, TValue>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, IReadOnlyCollection<KeyValuePair<TKey, TValue>>
	{
		IImmutableDictionary<TKey, TValue> Clear();

		IImmutableDictionary<TKey, TValue> Add(TKey key, TValue value);

		IImmutableDictionary<TKey, TValue> AddRange(IEnumerable<KeyValuePair<TKey, TValue>> pairs);

		IImmutableDictionary<TKey, TValue> SetItem(TKey key, TValue value);

		IImmutableDictionary<TKey, TValue> SetItems(IEnumerable<KeyValuePair<TKey, TValue>> items);

		IImmutableDictionary<TKey, TValue> RemoveRange(IEnumerable<TKey> keys);

		IImmutableDictionary<TKey, TValue> Remove(TKey key);

		bool Contains(KeyValuePair<TKey, TValue> pair);

		bool TryGetKey(TKey equalKey, out TKey actualKey);
	}
	internal interface IImmutableDictionaryInternal<TKey, TValue>
	{
		bool ContainsValue(TValue value);
	}
	[CollectionBuilder(typeof(ImmutableList), "Create")]
	public interface IImmutableList<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T>
	{
		IImmutableList<T> Clear();

		int IndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer);

		int LastIndexOf(T item, int index, int count, IEqualityComparer<T>? equalityComparer);

		IImmutableList<T> Add(T value);

		IImmutableList<T> AddRange(IEnumerable<T> items);

		IImmutableList<T> Insert(int index, T element);

		IImmutableList<T> InsertRange(int index, IEnumerable<T> items);

		IImmutableList<T> Remove(T value, IEqualityComparer<T>? equalityComparer);

		IImmutableList<T> RemoveAll(Predicate<T> match);

		IImmutableList<T> RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer);

		IImmutableList<T> RemoveRange(int index, int count);

		IImmutableList<T> RemoveAt(int index);

		IImmutableList<T> SetItem(int index, T value);

		IImmutableList<T> Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer);
	}
	internal interface IImmutableListQueries<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T>
	{
		ImmutableList<TOutput> ConvertAll<TOutput>(Func<T, TOutput> converter);

		void ForEach(Action<T> action);

		ImmutableList<T> GetRange(int index, int count);

		void CopyTo(T[] array);

		void CopyTo(T[] array, int arrayIndex);

		void CopyTo(int index, T[] array, int arrayIndex, int count);

		bool Exists(Predicate<T> match);

		T? Find(Predicate<T> match);

		ImmutableList<T> FindAll(Predicate<T> match);

		int FindIndex(Predicate<T> match);

		int FindIndex(int startIndex, Predicate<T> match);

		int FindIndex(int startIndex, int count, Predicate<T> match);

		T? FindLast(Predicate<T> match);

		int FindLastIndex(Predicate<T> match);

		int FindLastIndex(int startIndex, Predicate<T> match);

		int FindLastIndex(int startIndex, int count, Predicate<T> match);

		bool TrueForAll(Predicate<T> match);

		int BinarySearch(T item);

		int BinarySearch(T item, IComparer<T>? comparer);

		int BinarySearch(int index, int count, T item, IComparer<T>? comparer);
	}
	[CollectionBuilder(typeof(ImmutableQueue), "Create")]
	public interface IImmutableQueue<T> : IEnumerable<T>, IEnumerable
	{
		bool IsEmpty { get; }

		IImmutableQueue<T> Clear();

		T Peek();

		IImmutableQueue<T> Enqueue(T value);

		IImmutableQueue<T> Dequeue();
	}
	[CollectionBuilder(typeof(ImmutableHashSet), "Create")]
	public interface IImmutableSet<T> : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
	{
		IImmutableSet<T> Clear();

		bool Contains(T value);

		IImmutableSet<T> Add(T value);

		IImmutableSet<T> Remove(T value);

		bool TryGetValue(T equalValue, out T actualValue);

		IImmutableSet<T> Intersect(IEnumerable<T> other);

		IImmutableSet<T> Except(IEnumerable<T> other);

		IImmutableSet<T> SymmetricExcept(IEnumerable<T> other);

		IImmutableSet<T> Union(IEnumerable<T> other);

		bool SetEquals(IEnumerable<T> other);

		bool IsProperSubsetOf(IEnumerable<T> other);

		bool IsProperSupersetOf(IEnumerable<T> other);

		bool IsSubsetOf(IEnumerable<T> other);

		bool IsSupersetOf(IEnumerable<T> other);

		bool Overlaps(IEnumerable<T> other);
	}
	[CollectionBuilder(typeof(ImmutableStack), "Create")]
	public interface IImmutableStack<T> : IEnumerable<T>, IEnumerable
	{
		bool IsEmpty { get; }

		IImmutableStack<T> Clear();

		IImmutableStack<T> Push(T value);

		IImmutableStack<T> Pop();

		T Peek();
	}
	[CollectionBuilder(typeof(ImmutableHashSet), "Create")]
	[DebuggerDisplay("Count = {Count}")]
	[DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))]
	public sealed class ImmutableHashSet<T> : IImmutableSet<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, IHashKeyCollection<T>, ICollection<T>, ISet<T>, ICollection, IStrongEnumerable<T, ImmutableHashSet<T>.Enumerator>
	{
		private sealed class HashBucketByValueEqualityComparer : IEqualityComparer<HashBucket>
		{
			private static readonly IEqualityComparer<HashBucket> s_defaultInstance = new HashBucketByValueEqualityComparer(EqualityComparer<T>.Default);

			private readonly IEqualityComparer<T> _valueComparer;

			internal static IEqualityComparer<HashBucket> DefaultInstance => s_defaultInstance;

			internal HashBucketByValueEqualityComparer(IEqualityComparer<T> valueComparer)
			{
				Requires.NotNull(valueComparer, "valueComparer");
				_valueComparer = valueComparer;
			}

			public bool Equals(HashBucket x, HashBucket y)
			{
				return x.EqualsByValue(y, _valueComparer);
			}

			public int GetHashCode(HashBucket obj)
			{
				throw new NotSupportedException();
			}
		}

		private sealed class HashBucketByRefEqualityComparer : IEqualityComparer<HashBucket>
		{
			private static readonly IEqualityComparer<HashBucket> s_defaultInstance = new HashBucketByRefEqualityComparer();

			internal static IEqualityComparer<HashBucket> DefaultInstance => s_defaultInstance;

			private HashBucketByRefEqualityComparer()
			{
			}

			public bool Equals(HashBucket x, HashBucket y)
			{
				return x.EqualsByRef(y);
			}

			public int GetHashCode(HashBucket obj)
			{
				throw new NotSupportedException();
			}
		}

		[DebuggerDisplay("Count = {Count}")]
		public sealed class Builder : IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable, ISet<T>, ICollection<T>
		{
			private SortedInt32KeyNode<HashBucket> _root = SortedInt32KeyNode<HashBucket>.EmptyNode;

			private IEqualityComparer<T> _equalityComparer;

			private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer;

			private int _count;

			private ImmutableHashSet<T> _immutable;

			private int _version;

			public int Count => _count;

			bool ICollection<T>.IsReadOnly => false;

			public IEqualityComparer<T> KeyComparer
			{
				get
				{
					return _equalityComparer;
				}
				set
				{
					Requires.NotNull(value, "value");
					if (value != _equalityComparer)
					{
						MutationResult mutationResult = ImmutableHashSet<T>.Union((IEnumerable<T>)this, new MutationInput(SortedInt32KeyNode<HashBucket>.EmptyNode, value, _hashBucketEqualityComparer, 0));
						_immutable = null;
						_equalityComparer = value;
						Root = mutationResult.Root;
						_count = mutationResult.Count;
					}
				}
			}

			internal int Version => _version;

			private MutationInput Origin => new MutationInput(Root, _equalityComparer, _hashBucketEqualityComparer, _count);

			private SortedInt32KeyNode<HashBucket> Root
			{
				get
				{
					return _root;
				}
				set
				{
					_version++;
					if (_root != value)
					{
						_root = value;
						_immutable = null;
					}
				}
			}

			internal Builder(ImmutableHashSet<T> set)
			{
				Requires.NotNull(set, "set");
				_root = set._root;
				_count = set._count;
				_equalityComparer = set._equalityComparer;
				_hashBucketEqualityComparer = set._hashBucketEqualityComparer;
				_immutable = set;
			}

			public Enumerator GetEnumerator()
			{
				return new Enumerator(_root, this);
			}

			public ImmutableHashSet<T> ToImmutable()
			{
				return _immutable ?? (_immutable = ImmutableHashSet<T>.Wrap(_root, _equalityComparer, _count));
			}

			public bool TryGetValue(T equalValue, out T actualValue)
			{
				int key = ((equalValue != null) ? _equalityComparer.GetHashCode(equalValue) : 0);
				if (_root.TryGetValue(key, out var value))
				{
					return value.TryExchange(equalValue, _equalityComparer, out actualValue);
				}
				actualValue = equalValue;
				return false;
			}

			public bool Add(T item)
			{
				MutationResult result = ImmutableHashSet<T>.Add(item, Origin);
				Apply(result);
				return result.Count != 0;
			}

			public bool Remove(T item)
			{
				MutationResult result = ImmutableHashSet<T>.Remove(item, Origin);
				Apply(result);
				return result.Count != 0;
			}

			public bool Contains(T item)
			{
				return ImmutableHashSet<T>.Contains(item, Origin);
			}

			public void Clear()
			{
				_count = 0;
				Root = SortedInt32KeyNode<HashBucket>.EmptyNode;
			}

			public void ExceptWith(IEnumerable<T> other)
			{
				MutationResult result = ImmutableHashSet<T>.Except(other, _equalityComparer, _hashBucketEqualityComparer, _root);
				Apply(result);
			}

			public void IntersectWith(IEnumerable<T> other)
			{
				MutationResult result = ImmutableHashSet<T>.Intersect(other, Origin);
				Apply(result);
			}

			public bool IsProperSubsetOf(IEnumerable<T> other)
			{
				return ImmutableHashSet<T>.IsProperSubsetOf(other, Origin);
			}

			public bool IsProperSupersetOf(IEnumerable<T> other)
			{
				return ImmutableHashSet<T>.IsProperSupersetOf(other, Origin);
			}

			public bool IsSubsetOf(IEnumerable<T> other)
			{
				return ImmutableHashSet<T>.IsSubsetOf(other, Origin);
			}

			public bool IsSupersetOf(IEnumerable<T> other)
			{
				return ImmutableHashSet<T>.IsSupersetOf(other, Origin);
			}

			public bool Overlaps(IEnumerable<T> other)
			{
				return ImmutableHashSet<T>.Overlaps(other, Origin);
			}

			public bool SetEquals(IEnumerable<T> other)
			{
				if (this == other)
				{
					return true;
				}
				return ImmutableHashSet<T>.SetEquals(other, Origin);
			}

			public void SymmetricExceptWith(IEnumerable<T> other)
			{
				MutationResult result = ImmutableHashSet<T>.SymmetricExcept(other, Origin);
				Apply(result);
			}

			public void UnionWith(IEnumerable<T> other)
			{
				MutationResult result = ImmutableHashSet<T>.Union(other, Origin);
				Apply(result);
			}

			void ICollection<T>.Add(T item)
			{
				Add(item);
			}

			void ICollection<T>.CopyTo(T[] array, int arrayIndex)
			{
				Requires.NotNull(array, "array");
				Requires.Range(arrayIndex >= 0, "arrayIndex");
				Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex");
				using Enumerator enumerator = GetEnumerator();
				while (enumerator.MoveNext())
				{
					T current = enumerator.Current;
					array[arrayIndex++] = current;
				}
			}

			IEnumerator<T> IEnumerable<T>.GetEnumerator()
			{
				return GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}

			private void Apply(MutationResult result)
			{
				Root = result.Root;
				if (result.CountType == CountType.Adjustment)
				{
					_count += result.Count;
				}
				else
				{
					_count = result.Count;
				}
			}
		}

		public struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable, IStrongEnumerator<T>
		{
			private readonly Builder _builder;

			private SortedInt32KeyNode<HashBucket>.Enumerator _mapEnumerator;

			private HashBucket.Enumerator _bucketEnumerator;

			private int _enumeratingBuilderVersion;

			public T Current
			{
				get
				{
					_mapEnumerator.ThrowIfDisposed();
					return _bucketEnumerator.Current;
				}
			}

			object? IEnumerator.Current => Current;

			internal Enumerator(SortedInt32KeyNode<HashBucket> root, Builder? builder = null)
			{
				_builder = builder;
				_mapEnumerator = new SortedInt32KeyNode<HashBucket>.Enumerator(root);
				_bucketEnumerator = default(HashBucket.Enumerator);
				_enumeratingBuilderVersion = builder?.Version ?? (-1);
			}

			public bool MoveNext()
			{
				ThrowIfChanged();
				if (_bucketEnumerator.MoveNext())
				{
					return true;
				}
				if (_mapEnumerator.MoveNext())
				{
					_bucketEnumerator = new HashBucket.Enumerator(_mapEnumerator.Current.Value);
					return _bucketEnumerator.MoveNext();
				}
				return false;
			}

			public void Reset()
			{
				_enumeratingBuilderVersion = ((_builder != null) ? _builder.Version : (-1));
				_mapEnumerator.Reset();
				_bucketEnumerator.Dispose();
				_bucketEnumerator = default(HashBucket.Enumerator);
			}

			public void Dispose()
			{
				_mapEnumerator.Dispose();
				_bucketEnumerator.Dispose();
			}

			private void ThrowIfChanged()
			{
				if (_builder != null && _builder.Version != _enumeratingBuilderVersion)
				{
					throw new InvalidOperationException(System.SR.CollectionModifiedDuringEnumeration);
				}
			}
		}

		internal enum OperationResult
		{
			SizeChanged,
			NoChangeRequired
		}

		internal readonly struct HashBucket
		{
			internal struct Enumerator : IEnumerator<T>, IEnumerator, IDisposable
			{
				private enum Position
				{
					BeforeFirst,
					First,
					Additional,
					End
				}

				private readonly HashBucket _bucket;

				private bool _disposed;

				private Position _currentPosition;

				private ImmutableList<T>.Enumerator _additionalEnumerator;

				object? IEnumerator.Current => Current;

				public T Current
				{
					get
					{
						ThrowIfDisposed();
						return _currentPosition switch
						{
							Position.First => _bucket._firstValue, 
							Position.Additional => _additionalEnumerator.Current, 
							_ => throw new InvalidOperationException(), 
						};
					}
				}

				internal Enumerator(HashBucket bucket)
				{
					_disposed = false;
					_bucket = bucket;
					_currentPosition = Position.BeforeFirst;
					_additionalEnumerator = default(ImmutableList<T>.Enumerator);
				}

				public bool MoveNext()
				{
					ThrowIfDisposed();
					if (_bucket.IsEmpty)
					{
						_currentPosition = Position.End;
						return false;
					}
					switch (_currentPosition)
					{
					case Position.BeforeFirst:
						_currentPosition = Position.First;
						return true;
					case Position.First:
						if (_bucket._additionalElements.IsEmpty)
						{
							_currentPosition = Position.End;
							return false;
						}
						_currentPosition = Position.Additional;
						_additionalEnumerator = new ImmutableList<T>.Enumerator(_bucket._additionalElements);
						return _additionalEnumerator.MoveNext();
					case Position.Additional:
						return _additionalEnumerator.MoveNext();
					case Position.End:
						return false;
					default:
						throw new InvalidOperationException();
					}
				}

				public void Reset()
				{
					ThrowIfDisposed();
					_additionalEnumerator.Dispose();
					_currentPosition = Position.BeforeFirst;
				}

				public void Dispose()
				{
					_disposed = true;
					_additionalEnumerator.Dispose();
				}

				private void ThrowIfDisposed()
				{
					if (_disposed)
					{
						Requires.FailObjectDisposed(this);
					}
				}
			}

			private readonly T _firstValue;

			private readonly ImmutableList<T>.Node _additionalElements;

			internal bool IsEmpty => _additionalElements == null;

			private HashBucket(T firstElement, ImmutableList<T>.Node additionalElements = null)
			{
				_firstValue = firstElement;
				_additionalElements = additionalElements ?? ImmutableList<T>.Node.EmptyNode;
			}

			public Enumerator GetEnumerator()
			{
				return new Enumerator(this);
			}

			public override bool Equals(object? obj)
			{
				throw new NotSupportedException();
			}

			public override int GetHashCode()
			{
				throw new NotSupportedException();
			}

			internal bool EqualsByRef(HashBucket other)
			{
				if ((object)_firstValue == (object)other._firstValue)
				{
					return _additionalElements == other._additionalElements;
				}
				return false;
			}

			internal bool EqualsByValue(HashBucket other, IEqualityComparer<T> valueComparer)
			{
				if (valueComparer.Equals(_firstValue, other._firstValue))
				{
					return _additionalElements == other._additionalElements;
				}
				return false;
			}

			internal HashBucket Add(T value, IEqualityComparer<T> valueComparer, out OperationResult result)
			{
				if (IsEmpty)
				{
					result = OperationResult.SizeChanged;
					return new HashBucket(value);
				}
				if (valueComparer.Equals(value, _firstValue) || _additionalElements.IndexOf(value, valueComparer) >= 0)
				{
					result = OperationResult.NoChangeRequired;
					return this;
				}
				result = OperationResult.SizeChanged;
				return new HashBucket(_firstValue, _additionalElements.Add(value));
			}

			internal bool Contains(T value, IEqualityComparer<T> valueComparer)
			{
				if (IsEmpty)
				{
					return false;
				}
				if (!valueComparer.Equals(value, _firstValue))
				{
					return _additionalElements.IndexOf(value, valueComparer) >= 0;
				}
				return true;
			}

			internal bool TryExchange(T value, IEqualityComparer<T> valueComparer, out T existingValue)
			{
				if (!IsEmpty)
				{
					if (valueComparer.Equals(value, _firstValue))
					{
						existingValue = _firstValue;
						return true;
					}
					int num = _additionalElements.IndexOf(value, valueComparer);
					if (num >= 0)
					{
						existingValue = _additionalElements.ItemRef(num);
						return true;
					}
				}
				existingValue = value;
				return false;
			}

			internal HashBucket Remove(T value, IEqualityComparer<T> equalityComparer, out OperationResult result)
			{
				if (IsEmpty)
				{
					result = OperationResult.NoChangeRequired;
					return this;
				}
				if (equalityComparer.Equals(_firstValue, value))
				{
					if (_additionalElements.IsEmpty)
					{
						result = OperationResult.SizeChanged;
						return default(HashBucket);
					}
					int count = _additionalElements.Left.Count;
					result = OperationResult.SizeChanged;
					return new HashBucket(_additionalElements.Key, _additionalElements.RemoveAt(count));
				}
				int num = _additionalElements.IndexOf(value, equalityComparer);
				if (num < 0)
				{
					result = OperationResult.NoChangeRequired;
					return this;
				}
				result = OperationResult.SizeChanged;
				return new HashBucket(_firstValue, _additionalElements.RemoveAt(num));
			}

			internal void Freeze()
			{
				_additionalElements?.Freeze();
			}
		}

		private readonly struct MutationInput
		{
			private readonly SortedInt32KeyNode<HashBucket> _root;

			private readonly IEqualityComparer<T> _equalityComparer;

			private readonly int _count;

			private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer;

			internal SortedInt32KeyNode<HashBucket> Root => _root;

			internal IEqualityComparer<T> EqualityComparer => _equalityComparer;

			internal int Count => _count;

			internal IEqualityComparer<HashBucket> HashBucketEqualityComparer => _hashBucketEqualityComparer;

			internal MutationInput(ImmutableHashSet<T> set)
			{
				Requires.NotNull(set, "set");
				_root = set._root;
				_equalityComparer = set._equalityComparer;
				_count = set._count;
				_hashBucketEqualityComparer = set._hashBucketEqualityComparer;
			}

			internal MutationInput(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, IEqualityComparer<HashBucket> hashBucketEqualityComparer, int count)
			{
				Requires.NotNull(root, "root");
				Requires.NotNull(equalityComparer, "equalityComparer");
				Requires.Range(count >= 0, "count");
				Requires.NotNull(hashBucketEqualityComparer, "hashBucketEqualityComparer");
				_root = root;
				_equalityComparer = equalityComparer;
				_count = count;
				_hashBucketEqualityComparer = hashBucketEqualityComparer;
			}
		}

		private enum CountType
		{
			Adjustment,
			FinalValue
		}

		private readonly struct MutationResult
		{
			private readonly SortedInt32KeyNode<HashBucket> _root;

			private readonly int _count;

			private readonly CountType _countType;

			internal SortedInt32KeyNode<HashBucket> Root => _root;

			internal int Count => _count;

			internal CountType CountType => _countType;

			internal MutationResult(SortedInt32KeyNode<HashBucket> root, int count, CountType countType = CountType.Adjustment)
			{
				Requires.NotNull(root, "root");
				_root = root;
				_count = count;
				_countType = countType;
			}

			internal ImmutableHashSet<T> Finalize(ImmutableHashSet<T> priorSet)
			{
				Requires.NotNull(priorSet, "priorSet");
				int num = Count;
				if (CountType == CountType.Adjustment)
				{
					num += priorSet._count;
				}
				return priorSet.Wrap(Root, num);
			}
		}

		private readonly struct NodeEnumerable : IEnumerable<T>, IEnumerable
		{
			private readonly SortedInt32KeyNode<HashBucket> _root;

			internal NodeEnumerable(SortedInt32KeyNode<HashBucket> root)
			{
				Requires.NotNull(root, "root");
				_root = root;
			}

			public Enumerator GetEnumerator()
			{
				return new Enumerator(_root);
			}

			[ExcludeFromCodeCoverage]
			IEnumerator<T> IEnumerable<T>.GetEnumerator()
			{
				return GetEnumerator();
			}

			[ExcludeFromCodeCoverage]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		public static readonly ImmutableHashSet<T> Empty = new ImmutableHashSet<T>(SortedInt32KeyNode<HashBucket>.EmptyNode, EqualityComparer<T>.Default, 0);

		private static readonly Action<KeyValuePair<int, HashBucket>> s_FreezeBucketAction = delegate(KeyValuePair<int, HashBucket> kv)
		{
			kv.Value.Freeze();
		};

		private readonly IEqualityComparer<T> _equalityComparer;

		private readonly int _count;

		private readonly SortedInt32KeyNode<HashBucket> _root;

		private readonly IEqualityComparer<HashBucket> _hashBucketEqualityComparer;

		public int Count => _count;

		public bool IsEmpty => Count == 0;

		public IEqualityComparer<T> KeyComparer => _equalityComparer;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		object ICollection.SyncRoot => this;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		bool ICollection.IsSynchronized => true;

		internal IBinaryTree Root => _root;

		private MutationInput Origin => new MutationInput(this);

		bool ICollection<T>.IsReadOnly => true;

		internal ImmutableHashSet(IEqualityComparer<T> equalityComparer)
			: this(SortedInt32KeyNode<HashBucket>.EmptyNode, equalityComparer, 0)
		{
		}

		private ImmutableHashSet(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count)
		{
			Requires.NotNull(root, "root");
			Requires.NotNull(equalityComparer, "equalityComparer");
			root.Freeze(s_FreezeBucketAction);
			_root = root;
			_count = count;
			_equalityComparer = equalityComparer;
			_hashBucketEqualityComparer = GetHashBucketEqualityComparer(equalityComparer);
		}

		public ImmutableHashSet<T> Clear()
		{
			if (!IsEmpty)
			{
				return Empty.WithComparer(_equalityComparer);
			}
			return this;
		}

		IImmutableSet<T> IImmutableSet<T>.Clear()
		{
			return Clear();
		}

		public Builder ToBuilder()
		{
			return new Builder(this);
		}

		public ImmutableHashSet<T> Add(T item)
		{
			return Add(item, Origin).Finalize(this);
		}

		public ImmutableHashSet<T> Remove(T item)
		{
			return Remove(item, Origin).Finalize(this);
		}

		public bool TryGetValue(T equalValue, out T actualValue)
		{
			int key = ((equalValue != null) ? _equalityComparer.GetHashCode(equalValue) : 0);
			if (_root.TryGetValue(key, out var value))
			{
				return value.TryExchange(equalValue, _equalityComparer, out actualValue);
			}
			actualValue = equalValue;
			return false;
		}

		public ImmutableHashSet<T> Union(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return Union(other, avoidWithComparer: false);
		}

		internal ImmutableHashSet<T> Union(ReadOnlySpan<T> other)
		{
			return Union(other, Origin).Finalize(this);
		}

		public ImmutableHashSet<T> Intersect(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return Intersect(other, Origin).Finalize(this);
		}

		public ImmutableHashSet<T> Except(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return Except(other, _equalityComparer, _hashBucketEqualityComparer, _root).Finalize(this);
		}

		public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return SymmetricExcept(other, Origin).Finalize(this);
		}

		public bool SetEquals(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			if (this == other)
			{
				return true;
			}
			return SetEquals(other, Origin);
		}

		public bool IsProperSubsetOf(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return IsProperSubsetOf(other, Origin);
		}

		public bool IsProperSupersetOf(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return IsProperSupersetOf(other, Origin);
		}

		public bool IsSubsetOf(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return IsSubsetOf(other, Origin);
		}

		public bool IsSupersetOf(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return IsSupersetOf(other, Origin);
		}

		public bool Overlaps(IEnumerable<T> other)
		{
			Requires.NotNull(other, "other");
			return Overlaps(other, Origin);
		}

		IImmutableSet<T> IImmutableSet<T>.Add(T item)
		{
			return Add(item);
		}

		IImmutableSet<T> IImmutableSet<T>.Remove(T item)
		{
			return Remove(item);
		}

		IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other)
		{
			return Union(other);
		}

		IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other)
		{
			return Intersect(other);
		}

		IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other)
		{
			return Except(other);
		}

		IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other)
		{
			return SymmetricExcept(other);
		}

		public bool Contains(T item)
		{
			return Contains(item, Origin);
		}

		public ImmutableHashSet<T> WithComparer(IEqualityComparer<T>? equalityComparer)
		{
			if (equalityComparer == null)
			{
				equalityComparer = EqualityComparer<T>.Default;
			}
			if (equalityComparer == _equalityComparer)
			{
				return this;
			}
			return new ImmutableHashSet<T>(equalityComparer).Union(this, avoidWithComparer: true);
		}

		bool ISet<T>.Add(T item)
		{
			throw new NotSupportedException();
		}

		void ISet<T>.ExceptWith(IEnumerable<T> other)
		{
			throw new NotSupportedException();
		}

		void ISet<T>.IntersectWith(IEnumerable<T> other)
		{
			throw new NotSupportedException();
		}

		void ISet<T>.SymmetricExceptWith(IEnumerable<T> other)
		{
			throw new NotSupportedException();
		}

		void ISet<T>.UnionWith(IEnumerable<T> other)
		{
			throw new NotSupportedException();
		}

		void ICollection<T>.CopyTo(T[] array, int arrayIndex)
		{
			Requires.NotNull(array, "array");
			Requires.Range(arrayIndex >= 0, "arrayIndex");
			Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex");
			using Enumerator enumerator = GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				array[arrayIndex++] = current;
			}
		}

		void ICollection<T>.Add(T item)
		{
			throw new NotSupportedException();
		}

		void ICollection<T>.Clear()
		{
			throw new NotSupportedException();
		}

		bool ICollection<T>.Remove(T item)
		{
			throw new NotSupportedException();
		}

		void ICollection.CopyTo(Array array, int arrayIndex)
		{
			Requires.NotNull(array, "array");
			Requires.Range(arrayIndex >= 0, "arrayIndex");
			Requires.Range(array.Length >= arrayIndex + Count, "arrayIndex");
			using Enumerator enumerator = GetEnumerator();
			while (enumerator.MoveNext())
			{
				T current = enumerator.Current;
				array.SetValue(current, arrayIndex++);
			}
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(_root);
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			if (!IsEmpty)
			{
				return GetEnumerator();
			}
			return Enumerable.Empty<T>().GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		private static bool IsSupersetOf(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
			{
				if (!Contains(item, origin))
				{
					return false;
				}
			}
			return true;
		}

		private static MutationResult Add(T item, MutationInput origin)
		{
			int num = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0);
			OperationResult result;
			HashBucket newBucket = origin.Root.GetValueOrDefault(num).Add(item, origin.EqualityComparer, out result);
			if (result == OperationResult.NoChangeRequired)
			{
				return new MutationResult(origin.Root, 0);
			}
			return new MutationResult(UpdateRoot(origin.Root, num, origin.HashBucketEqualityComparer, newBucket), 1);
		}

		private static MutationResult Remove(T item, MutationInput origin)
		{
			OperationResult result = OperationResult.NoChangeRequired;
			int num = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0);
			SortedInt32KeyNode<HashBucket> root = origin.Root;
			if (origin.Root.TryGetValue(num, out var value))
			{
				HashBucket newBucket = value.Remove(item, origin.EqualityComparer, out result);
				if (result == OperationResult.NoChangeRequired)
				{
					return new MutationResult(origin.Root, 0);
				}
				root = UpdateRoot(origin.Root, num, origin.HashBucketEqualityComparer, newBucket);
			}
			return new MutationResult(root, (result == OperationResult.SizeChanged) ? (-1) : 0);
		}

		private static bool Contains(T item, MutationInput origin)
		{
			int key = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0);
			if (origin.Root.TryGetValue(key, out var value))
			{
				return value.Contains(item, origin.EqualityComparer);
			}
			return false;
		}

		private static MutationResult Union(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			int num = 0;
			SortedInt32KeyNode<HashBucket> sortedInt32KeyNode = origin.Root;
			foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
			{
				int num2 = ((item != null) ? origin.EqualityComparer.GetHashCode(item) : 0);
				OperationResult result;
				HashBucket newBucket = sortedInt32KeyNode.GetValueOrDefault(num2).Add(item, origin.EqualityComparer, out result);
				if (result == OperationResult.SizeChanged)
				{
					sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, origin.HashBucketEqualityComparer, newBucket);
					num++;
				}
			}
			return new MutationResult(sortedInt32KeyNode, num);
		}

		private static MutationResult Union(ReadOnlySpan<T> other, MutationInput origin)
		{
			int num = 0;
			SortedInt32KeyNode<HashBucket> sortedInt32KeyNode = origin.Root;
			ReadOnlySpan<T> readOnlySpan = other;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				T val = readOnlySpan[i];
				int num2 = ((val != null) ? origin.EqualityComparer.GetHashCode(val) : 0);
				OperationResult result;
				HashBucket newBucket = sortedInt32KeyNode.GetValueOrDefault(num2).Add(val, origin.EqualityComparer, out result);
				if (result == OperationResult.SizeChanged)
				{
					sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, origin.HashBucketEqualityComparer, newBucket);
					num++;
				}
			}
			return new MutationResult(sortedInt32KeyNode, num);
		}

		private static bool Overlaps(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			if (origin.Root.IsEmpty)
			{
				return false;
			}
			foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
			{
				if (Contains(item, origin))
				{
					return true;
				}
			}
			return false;
		}

		private static bool SetEquals(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer);
			if (origin.Count != hashSet.Count)
			{
				return false;
			}
			foreach (T item in hashSet)
			{
				if (!Contains(item, origin))
				{
					return false;
				}
			}
			return true;
		}

		private static SortedInt32KeyNode<HashBucket> UpdateRoot(SortedInt32KeyNode<HashBucket> root, int hashCode, IEqualityComparer<HashBucket> hashBucketEqualityComparer, HashBucket newBucket)
		{
			bool mutated;
			if (newBucket.IsEmpty)
			{
				return root.Remove(hashCode, out mutated);
			}
			bool mutated2;
			return root.SetItem(hashCode, newBucket, hashBucketEqualityComparer, out mutated, out mutated2);
		}

		private static MutationResult Intersect(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			SortedInt32KeyNode<HashBucket> root = SortedInt32KeyNode<HashBucket>.EmptyNode;
			int num = 0;
			foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
			{
				if (Contains(item, origin))
				{
					MutationResult mutationResult = Add(item, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num));
					root = mutationResult.Root;
					num += mutationResult.Count;
				}
			}
			return new MutationResult(root, num, CountType.FinalValue);
		}

		private static MutationResult Except(IEnumerable<T> other, IEqualityComparer<T> equalityComparer, IEqualityComparer<HashBucket> hashBucketEqualityComparer, SortedInt32KeyNode<HashBucket> root)
		{
			Requires.NotNull(other, "other");
			Requires.NotNull(equalityComparer, "equalityComparer");
			Requires.NotNull(root, "root");
			int num = 0;
			SortedInt32KeyNode<HashBucket> sortedInt32KeyNode = root;
			foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
			{
				int num2 = ((item != null) ? equalityComparer.GetHashCode(item) : 0);
				if (sortedInt32KeyNode.TryGetValue(num2, out var value))
				{
					OperationResult result;
					HashBucket newBucket = value.Remove(item, equalityComparer, out result);
					if (result == OperationResult.SizeChanged)
					{
						num--;
						sortedInt32KeyNode = UpdateRoot(sortedInt32KeyNode, num2, hashBucketEqualityComparer, newBucket);
					}
				}
			}
			return new MutationResult(sortedInt32KeyNode, num);
		}

		private static MutationResult SymmetricExcept(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			ImmutableHashSet<T> immutableHashSet = ImmutableHashSet.CreateRange(origin.EqualityComparer, other);
			int num = 0;
			SortedInt32KeyNode<HashBucket> root = SortedInt32KeyNode<HashBucket>.EmptyNode;
			foreach (T item in new NodeEnumerable(origin.Root))
			{
				if (!immutableHashSet.Contains(item))
				{
					MutationResult mutationResult = Add(item, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num));
					root = mutationResult.Root;
					num += mutationResult.Count;
				}
			}
			foreach (T item2 in immutableHashSet)
			{
				if (!Contains(item2, origin))
				{
					MutationResult mutationResult2 = Add(item2, new MutationInput(root, origin.EqualityComparer, origin.HashBucketEqualityComparer, num));
					root = mutationResult2.Root;
					num += mutationResult2.Count;
				}
			}
			return new MutationResult(root, num, CountType.FinalValue);
		}

		private static bool IsProperSubsetOf(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			if (origin.Root.IsEmpty)
			{
				return other.Any();
			}
			HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer);
			if (origin.Count >= hashSet.Count)
			{
				return false;
			}
			int num = 0;
			bool flag = false;
			foreach (T item in hashSet)
			{
				if (Contains(item, origin))
				{
					num++;
				}
				else
				{
					flag = true;
				}
				if (num == origin.Count && flag)
				{
					return true;
				}
			}
			return false;
		}

		private static bool IsProperSupersetOf(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			if (origin.Root.IsEmpty)
			{
				return false;
			}
			int num = 0;
			foreach (T item in other.GetEnumerableDisposable<T, Enumerator>())
			{
				num++;
				if (!Contains(item, origin))
				{
					return false;
				}
			}
			return origin.Count > num;
		}

		private static bool IsSubsetOf(IEnumerable<T> other, MutationInput origin)
		{
			Requires.NotNull(other, "other");
			if (origin.Root.IsEmpty)
			{
				return true;
			}
			HashSet<T> hashSet = new HashSet<T>(other, origin.EqualityComparer);
			int num = 0;
			foreach (T item in hashSet)
			{
				if (Contains(item, origin))
				{
					num++;
				}
			}
			return num == origin.Count;
		}

		private static ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, IEqualityComparer<T> equalityComparer, int count)
		{
			Requires.NotNull(root, "root");
			Requires.NotNull(equalityComparer, "equalityComparer");
			Requires.Range(count >= 0, "count");
			return new ImmutableHashSet<T>(root, equalityComparer, count);
		}

		private static IEqualityComparer<HashBucket> GetHashBucketEqualityComparer(IEqualityComparer<T> valueComparer)
		{
			if (!ImmutableExtensions.IsValueType<T>())
			{
				return HashBucketByRefEqualityComparer.DefaultInstance;
			}
			if (valueComparer == EqualityComparer<T>.Default)
			{
				return HashBucketByValueEqualityComparer.DefaultInstance;
			}
			return new HashBucketByValueEqualityComparer(valueComparer);
		}

		private ImmutableHashSet<T> Wrap(SortedInt32KeyNode<HashBucket> root, int adjustedCountIfDifferentRoot)
		{
			if (root == _root)
			{
				return this;
			}
			return new ImmutableHashSet<T>(root, _equalityComparer, adjustedCountIfDifferentRoot);
		}

		private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer)
		{
			Requires.NotNull(items, "items");
			if (IsEmpty && !avoidWithComparer && items is ImmutableHashSet<T> immutableHashSet)
			{
				return immutableHashSet.WithComparer(KeyComparer);
			}
			return Union(items, Origin).Finalize(this);
		}
	}
	internal interface IStrongEnumerable<out T, TEnumerator> where TEnumerator : struct, IStrongEnumerator<T>
	{
		TEnumerator GetEnumerator();
	}
	internal interface IStrongEnumerator<T>
	{
		T Current { get; }

		bool MoveNext();
	}
	internal interface IOrderedCollection<out T> : IEnumerable<T>, IEnumerable
	{
		int Count { get; }

		T this[int index] { get; }
	}
	public static class ImmutableArray
	{
		internal static readonly byte[] TwoElementArray = new byte[2];

		public static ImmutableArray<T> Create<T>()
		{
			return ImmutableArray<T>.Empty;
		}

		public static ImmutableArray<T> Create<T>(T item)
		{
			return new ImmutableArray<T>(new T[1] { item });
		}

		public static ImmutableArray<T> Create<T>(T item1, T item2)
		{
			return new ImmutableArray<T>(new T[2] { item1, item2 });
		}

		public static ImmutableArray<T> Create<T>(T item1, T item2, T item3)
		{
			return new ImmutableArray<T>(new T[3] { item1, item2, item3 });
		}

		public static ImmutableArray<T> Create<T>(T item1, T item2, T item3, T item4)
		{
			return new ImmutableArray<T>(new T[4] { item1, item2, item3, item4 });
		}

		public static ImmutableArray<T> Create<T>([ParamCollection] scoped ReadOnlySpan<T> items)
		{
			if (items.IsEmpty)
			{
				return ImmutableArray<T>.Empty;
			}
			return new ImmutableArray<T>(items.ToArray());
		}

		public static ImmutableArray<T> Create<T>(Span<T> items)
		{
			return Create((ReadOnlySpan<T>)items);
		}

		public static ImmutableArray<T> ToImmutableArray<T>(this ReadOnlySpan<T> items)
		{
			return Create(items);
		}

		public static ImmutableArray<T> ToImmutableArray<T>(this Span<T> items)
		{
			return Create((ReadOnlySpan<T>)items);
		}

		public static ImmutableArray<T> CreateRange<T>(IEnumerable<T> items)
		{
			Requires.NotNull(items, "items");
			if (items is IImmutableArray immutableArray)
			{
				return new ImmutableArray<T>((T[])(immutableArray.Array ?? throw new InvalidOperationException(System.SR.InvalidOperationOnDefaultArray)));
			}
			if (items.TryGetCount(out var count))
			{
				return new ImmutableArray<T>(items.ToArray(count));
			}
			return new ImmutableArray<T>(items.ToArray());
		}

		public static ImmutableArray<T> Create<T>(params T[]? items)
		{
			if (items == null || items.Length == 0)
			{
				return ImmutableArray<T>.Empty;
			}
			T[] array = new T[items.Length];
			Array.Copy(items, array, items.Length);
			return new ImmutableArray<T>(array);
		}

		public static ImmutableArray<T> Create<T>(T[] items, int start, int length)
		{
			Requires.NotNull(items, "items");
			Requires.Range(start >= 0 && start <= items.Length, "start");
			Requires.Range(length >= 0 && start + length <= items.Length, "length");
			if (length == 0)
			{
				return Create<T>();
			}
			T[] array = new T[length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = items[start + i];
			}
			return new ImmutableArray<T>(array);
		}

		public static ImmutableArray<T> Create<T>(ImmutableArray<T> items, int start, int length)
		{
			Requires.Range(start >= 0 && start <= items.Length, "start");
			Requires.Range(length >= 0 && start + length <= items.Length, "length");
			if (length == 0)
			{
				return Create<T>();
			}
			if (start == 0 && length == items.Length)
			{
				return items;
			}
			T[] array = new T[length];
			Array.Copy(items.array, start, array, 0, length);
			return new ImmutableArray<T>(array);
		}

		public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, Func<TSource, TResult> selector)
		{
			Requires.NotNull(selector, "selector");
			int length = items.Length;
			if (length == 0)
			{
				return Create<TResult>();
			}
			TResult[] array = new TResult[length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = selector(items[i]);
			}
			return new ImmutableArray<TResult>(array);
		}

		public static ImmutableArray<TResult> CreateRange<TSource, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TResult> selector)
		{
			int length2 = items.Length;
			Requires.Range(start >= 0 && start <= length2, "start");
			Requires.Range(length >= 0 && start + length <= length2, "length");
			Requires.NotNull(selector, "selector");
			if (length == 0)
			{
				return Create<TResult>();
			}
			TResult[] array = new TResult[length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = selector(items[i + start]);
			}
			return new ImmutableArray<TResult>(array);
		}

		public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, Func<TSource, TArg, TResult> selector, TArg arg)
		{
			Requires.NotNull(selector, "selector");
			int length = items.Length;
			if (length == 0)
			{
				return Create<TResult>();
			}
			TResult[] array = new TResult[length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = selector(items[i], arg);
			}
			return new ImmutableArray<TResult>(array);
		}

		public static ImmutableArray<TResult> CreateRange<TSource, TArg, TResult>(ImmutableArray<TSource> items, int start, int length, Func<TSource, TArg, TResult> selector, TArg arg)
		{
			int length2 = items.Length;
			Requires.Range(start >= 0 && start <= length2, "start");
			Requires.Range(length >= 0 && start + length <= length2, "length");
			Requires.NotNull(selector, "selector");
			if (length == 0)
			{
				return Create<TResult>();
			}
			TResult[] array = new TResult[length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = selector(items[i + start], arg);
			}
			return new ImmutableArray<TResult>(array);
		}

		public static ImmutableArray<T>.Builder CreateBuilder<T>()
		{
			return Create<T>().ToBuilder();
		}

		public static ImmutableArray<T>.Builder CreateBuilder<T>(int initialCapacity)
		{
			return new ImmutableArray<T>.Builder(initialCapacity);
		}

		public static ImmutableArray<TSource> ToImmutableArray<TSource>(this IEnumerable<TSource> items)
		{
			if (items is ImmutableArray<TSource>)
			{
				return (ImmutableArray<TSource>)(object)items;
			}
			return CreateRange(items);
		}

		public static ImmutableArray<TSource> ToImmutableArray<TSource>(this ImmutableArray<TSource>.Builder builder)
		{
			Requires.NotNull(builder, "builder");
			return builder.ToImmutable();
		}

		public static int BinarySearch<T>(this ImmutableArray<T> array, T value)
		{
			return Array.BinarySearch(array.array, value);
		}

		public static int BinarySearch<T>(this ImmutableArray<T> array, T value, IComparer<T>? comparer)
		{
			return Array.BinarySearch(array.array, value, comparer);
		}

		public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value)
		{
			return Array.BinarySearch(array.array, index, length, value);
		}

		public static int BinarySearch<T>(this ImmutableArray<T> array, int index, int length, T value, IComparer<T>? comparer)
		{
			return Array.BinarySearch(array.array, index, length, value, comparer);
		}
	}
	[CollectionBuilder(typeof(ImmutableArray), "Create")]
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	[System.Runtime.Versioning.NonVersionable]
	public readonly struct ImmutableArray<T> : IReadOnlyList<T>, IEnumerable<T>, IEnumerable, IReadOnlyCollection<T>, IList<T>, ICollection<T>, IEquatable<ImmutableArray<T>>, IList, ICollection, IImmutableArray, IStructuralComparable, IStructuralEquatable, IImmutableList<T>
	{
		[DebuggerDisplay("Count = {Count}")]
		[DebuggerTypeProxy(typeof(ImmutableArrayBuilderDebuggerProxy<>))]
		public sealed class Builder : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IReadOnlyList<T>, IReadOnlyCollection<T>
		{
			private T[] _elements;

			private int _count;

			public int Capacity
			{
				get
				{
					return _elements.Length;
				}
				set
				{
					if (value < _count)
					{
						throw new ArgumentException(System.SR.CapacityMustBeGreaterThanOrEqualToCount, "value");
					}
					if (value == _elements.Length)
					{
						return;
					}
					if (value > 0)
					{
						T[] array = new T[value];
						if (_count > 0)
						{
							Array.Copy(_elements, array, _count);
						}
						_elements = array;
					}
					else
					{
						_elements = ImmutableArray<T>.Empty.array;
					}
				}
			}

			public int Count
			{
				get
				{
					return _count;
				}
				set
				{
					Requires.Range(value >= 0, "value");
					if (value < _count)
					{
						if (_count - value > 64)
						{
							Array.Clear(_elements, value, _count - value);
						}
						else
						{
							for (int i = value; i < Count; i++)
							{
								_elements[i] = default(T);
							}
						}
					}
					else if (value > _count)
					{
						EnsureCapacity(value);
					}
					_count = value;
				}
			}

			public T this[int index]
			{
				get
				{
					if (index >= Count)
					{
						ThrowIndexOutOfRangeException();
					}
					return _elements[index];
				}
				set
				{
					if (index >= Count)
					{
						ThrowIndexOutOfRangeException();
					}
					_elements[index] = value;
				}
			}

			bool ICollection<T>.IsReadOnly => false;

			internal Builder(int capacity)
			{
				Requires.Range(capacity >= 0, "capacity");
				_elements = new T[capacity];
				_count = 0;
			}

			internal Builder()
				: this(8)
			{
			}

			private static void ThrowIndexOutOfRangeException()
			{
				throw new IndexOutOfRangeException();
			}

			public ref readonly T ItemRef(int index)
			{
				if (index >= Count)
				{
					ThrowIndexOutOfRangeException();
				}
				return ref _elements[index];
			}

			public ImmutableArray<T> ToImmutable()
			{
				return new ImmutableArray<T>(ToArray());
			}

			public ImmutableArray<T> MoveToImmutable()
			{
				if (Capacity != Count)
				{
					throw new InvalidOperationException(System.SR.CapacityMustEqualCountOnMove);
				}
				T[] elements = _elements;
				_elements = ImmutableArray<T>.Empty.array;
				_count = 0;
				return new ImmutableArray<T>(elements);
			}

			public ImmutableArray<T> DrainToImmutable()
			{
				T[] array = _elements;
				if (array.Length != _count)
				{
					array = ToArray();
				}
				_elements = ImmutableArray<T>.Empty.array;
				_count = 0;
				return new ImmutableArray<T>(array);
			}

			public void Clear()
			{
				Count = 0;
			}

			public void Insert(int index, T item)
			{
				Requires.Range(index >= 0 && index <= Count, "index");
				EnsureCapacity(Count + 1);
				if (index < Count)
				{
					Array.Copy(_elements, index, _elements, index + 1, Count - index);
				}
				_count++;
				_elements[index] = item;
			}

			public void InsertRange(int index, IEnumerable<T> items)
			{
				Requires.Range(index >= 0 && index <= Count, "index");
				Requires.NotNull(items, "items");
				int count = ImmutableExtensions.GetCount(ref items);
				EnsureCapacity(Count + count);
				if (index != Count)
				{
					Array.Copy(_elements, index, _elements, index + count, _count - index);
				}
				if (!items.TryCopyTo(_elements, index))
				{
					foreach (T item in items)
					{
						_elements[index++] = item;
					}
				}
				_count += count;
			}

			public void InsertRange(int index, ImmutableArray<T> items)
			{
				Requires.Range(index >= 0 && index <= Count, "index");
				if (!items.IsEmpty)
				{
					EnsureCapacity(Count + items.Length);
					if (index != Count)
					{
						Array.Copy(_elements, index, _elements, index + items.Length, _count - index);
					}
					Array.Copy(items.array, 0, _elements, index, items.Length);
					_count += items.Length;
				}
			}

			public void Add(T item)
			{
				int num = _count + 1;
				EnsureCapacity(num);
				_elements[_count] = item;
				_count = num;
			}

			public void AddRange(IEnumerable<T> items)
			{
				Requires.NotNull(items, "items");
				if (items.TryGetCount(out var count))
				{
					EnsureCapacity(Count + count);
					if (items.TryCopyTo(_elements, _count))
					{
						_count += count;
						return;
					}
				}
				foreach (T item in items)
				{
					Add(item);
				}
			}

			public void AddRange(params T[] items)
			{
				Requires.NotNull(items, "items");
				int count = Count;
				Count += items.Length;
				Array.Copy(items, 0, _elements, count, items.Length);
			}

			public void AddRange<TDerived>(TDerived[] items) where TDerived : T
			{
				Requires.NotNull(items, "items");
				int count = Count;
				Count += items.Length;
				Array.Copy(items, 0, _elements, count, items.Length);
			}

			public void AddRange(T[] items, int length)
			{
				Requires.NotNull(items, "items");
				Requires.Range(length >= 0 && length <= items.Length, "length");
				int count = Count;
				Count += length;
				Array.Copy(items, 0, _elements, count, length);
			}

			public void AddRange(ImmutableArray<T> items)
			{
				AddRange(items, items.Length);
			}

			public void AddRange(ImmutableArray<T> items, int length)
			{
				Requires.Range(length >= 0, "length");
				if (items.array != null)
				{
					AddRange(items.array, length);
				}
			}

			public void AddRange([ParamCollection] scoped ReadOnlySpan<T> items)
			{
				int count = Count;
				Count += items.Length;
				items.CopyTo(new Span<T>(_elements, count, items.Length));
			}

			public void AddRange<TDerived>([ParamCollection] scoped ReadOnlySpan<TDerived> items) where TDerived : T
			{
				int count = Count;
				Count += items.Length;
				Span<T> span = new Span<T>(_elements, count, items.Length);
				for (int i = 0; i < items.Length; i++)
				{
					span[i] = (T)(object)items[i];
				}
			}

			public void AddRange<TDerived>(ImmutableArray<TDerived> items) where TDerived : T
			{
				if (items.array != null)
				{
					this.AddRange<TDerived>(items.array);
				}
			}

			public void AddRange(Builder items)
			{
				Requires.NotNull(items, "items");
				AddRange(items._elements, items.Count);
			}

			public void AddRange<TDerived>(ImmutableArray<TDerived>.Builder items) where TDerived : T
			{
				Requires.NotNull(items, "items");
				AddRange<TDerived>(items._elements, items.Count);
			}

			public bool Remove(T element)
			{
				int num = IndexOf(element);
				if (num >= 0)
				{
					RemoveAt(num);
					return true;
				}
				return false;
			}

			public bool Remove(T element, IEqualityComparer<T>? equalityComparer)
			{
				int num = IndexOf(element, 0, _count, equalityComparer);
				if (num >= 0)
				{
					RemoveAt(num);
					return true;
				}
				return false;
			}

			public void RemoveAll(Predicate<T> match)
			{
				List<int> list = null;
				for (int i = 0; i < _count; i++)
				{
					if (match(_elements[i]))
					{
						if (list == null)
						{
							list = new List<int>();
						}
						list.Add(i);
					}
				}
				if (list != null)
				{
					RemoveAtRange(list);
				}
			}

			public void RemoveAt(int index)
			{
				Requires.Range(index >= 0 && index < Count, "index");
				if (index < Count - 1)
				{
					Array.Copy(_elements, index + 1, _elements, index, Count - index - 1);
				}
				Count--;
			}

			public void RemoveRange(int index, int length)
			{
				Requires.Range(index >= 0 && index <= _count, "index");
				Requires.Range(length >= 0 && index <= _count - length, "length");
				if (length != 0)
				{
					if (index + length < _count)
					{
						Array.Copy(_elements, index + length, _elements, index, Count - index - length);
					}
					_count -= length;
				}
			}

			public void RemoveRange(IEnumerable<T> items)
			{
				RemoveRange(items, EqualityComparer<T>.Default);
			}

			public void RemoveRange(IEnumerable<T> items, IEqualityComparer<T>? equalityComparer)
			{
				Requires.NotNull(items, "items");
				SortedSet<int> sortedSet = new SortedSet<int>();
				foreach (T item in items)
				{
					int num = IndexOf(item, 0, _count, equalityComparer);
					while (num >= 0 && !sortedSet.Add(num) && num + 1 < _count)
					{
						num = IndexOf(item, num + 1, equalityComparer);
					}
				}
				RemoveAtRange(sortedSet);
			}

			public void Replace(T oldValue, T newValue)
			{
				Replace(oldValue, newValue, EqualityComparer<T>.Default);
			}

			public void Replace(T oldValue, T newValue, IEqualityComparer<T>? equalityComparer)
			{
				int num = IndexOf(oldValue, 0, _count, equalityComparer);
				if (num >= 0)
				{
					_elements[num] = newValue;
				}
			}

			public bool Contains(T item)
			{
				return IndexOf(item) >= 0;
			}

			public T[] ToArray()
			{
				if (Count == 0)
				{
					return ImmutableArray<T>.Empty.array;
				}
				T[] array = new T[Count];
				Array.Copy(_elements, array, Count);
				return array;
			}

			public void CopyTo(T[] array, int index)
			{
				Requires.NotNull(array, "array");
				Requires.Range(index >= 0 && index + Count <= array.Length, "index");
				Array.Copy(_elements, 0, array, index, Count);
			}

			public void CopyTo(T[] destination)
			{
				Requires.NotNull(destination, "destination");
				Array.Copy(_elements, 0, destination, 0, Count);
			}

			public void CopyTo(int sourceIndex, T[] destination, int destinationIndex, int length)
			{
				Requires.NotNull(destination, "destination");
				Requires.Range(length >= 0, "length");
				Requires.Range(sourceIndex >= 0 && sourceIndex + length <= Count, "sourceIndex");
				Requires.Range(destinationIndex >= 0 && destinationIndex + length <= destination.Length, "destinationIndex");
				Array.Copy(_elements, sourceIndex, destination, destinationIndex, length);
			}

			private void EnsureCapacity(int capacity)
			{
				if (_elements.Length < capacity)
				{
					int newSize = Math.Max(_elements.Length * 2, capacity);
					Array.Resize(ref _elements, newSize);
				}
			}

			public int IndexOf(T item)
			{
				return IndexOf(item, 0, _count, EqualityComparer<T>.Default);
			}

			public int IndexOf(T item, int startIndex)
			{
				return IndexOf(item, startIndex, Count - startIndex, EqualityComparer<T>.Default);
			}

			public int IndexOf(T item, int startIndex, int count)
			{
				return IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
			}

			public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer)
			{
				if (count == 0 && startIndex == 0)
				{
					return -1;
				}
				Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex");
				Requires.Range(count >= 0 && startIndex + count <= Count, "count");
				if (equalityComparer == null)
				{
					equalityComparer = EqualityComparer<T>.Default;
				}
				if (equalityComparer == EqualityComparer<T>.Default)
				{
					return Array.IndexOf(_elements, item, startIndex, count);
				}
				for (int i = startIndex; i < startIndex + count; i++)
				{
					if (equalityComparer.Equals(_elements[i], item))
					{
						return i;
					}
				}
				return -1;
			}

			public int IndexOf(T item, int startIndex, IEqualityComparer<T>? equalityComparer)
			{
				return IndexOf(item, startIndex, Count - startIndex, equalityComparer);
			}

			public int LastIndexOf(T item)
			{
				if (Count == 0)
				{
					return -1;
				}
				return LastIndexOf(item, Count - 1, Count, EqualityComparer<T>.Default);
			}

			public int LastIndexOf(T item, int startIndex)
			{
				if (Count == 0 && startIndex == 0)
				{
					return -1;
				}
				Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex");
				return LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
			}

			public int LastIndexOf(T item, int startIndex, int count)
			{
				return LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
			}

			public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer)
			{
				if (count == 0 && startIndex == 0)
				{
					return -1;
				}
				Requires.Range(startIndex >= 0 && startIndex < Count, "startIndex");
				Requires.Range(count >= 0 && startIndex - count + 1 >= 0, "count");
				if (equalityComparer == null)
				{
					equalityComparer = EqualityComparer<T>.Default;
				}
				if (equalityComparer == EqualityComparer<T>.Default)
				{
					return Array.LastIndexOf(_elements, item, startIndex, count);
				}
				for (int num = startIndex; num >= startIndex - count + 1; num--)
				{
					if (equalityComparer.Equals(item, _elements[num]))
					{
						return num;
					}
				}
				return -1;
			}

			public void Reverse()
			{
				int num = 0;
				int num2 = _count - 1;
				T[] elements = _elements;
				while (num < num2)
				{
					T val = elements[num];
					elements[num] = elements[num2];
					elements[num2] = val;
					num++;
					num2--;
				}
			}

			public void Sort()
			{
				if (Count > 1)
				{
					Array.Sort(_elements, 0, Count, Comparer<T>.Default);
				}
			}

			public void Sort(Comparison<T> comparison)
			{
				Requires.NotNull(comparison, "comparison");
				if (Count > 1)
				{
					Array.Sort(_elements, 0, _count, Comparer<T>.Create(comparison));
				}
			}

			public void Sort(IComparer<T>? comparer)
			{
				if (Count > 1)
				{
					Array.Sort(_elements, 0, _count, comparer);
				}
			}

			public void Sort(int index, int count, IComparer<T>? comparer)
			{
				Requires.Range(index >= 0, "index");
				Requires.Range(count >= 0 && index + count <= Count, "count");
				if (count > 1)
				{
					Array.Sort(_elements, index, count, comparer);
				}
			}

			public void CopyTo(Span<T> destination)
			{
				Requires.Range(Count <= destination.Length, "destination");
				new ReadOnlySpan<T>(_elements, 0, Count).CopyTo(destination);
			}

			public IEnumerator<T> GetEnumerator()
			{
				for (int i = 0; i < Count; i++)
				{
					yield return this[i];
				}
			}

			IEnumerator<T> IEnumerable<T>.GetEnumerator()
			{
				return GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}

			private void AddRange<TDerived>(TDerived[] items, int length) where TDerived : T
			{
				EnsureCapacity(Count + length);
				int count = Count;
				Count += length;
				T[] elements = _elements;
				for (int i = 0; i < length; i++)
				{
					elements[count + i] = (T)(object)items[i];
				}
			}

			private void RemoveAtRange(ICollection<int> indicesToRemove)
			{
				Requires.NotNull(indicesToRemove, "indicesToRemove");
				if (indicesToRemove.Count == 0)
				{
					return;
				}
				int num = 0;
				int num2 = 0;
				int num3 = -1;
				foreach (int item in indicesToRemove)
				{
					int num4 = ((num3 == -1) ? item : (item - num3 - 1));
					Array.Copy(_elements, num + num2, _elements, num, num4);
					num2++;
					num += num4;
					num3 = item;
				}
				Array.Copy(_elements, num + num2, _elements, num, _elements.Length - (num + num2));
				_count -= indicesToRemove.Count;
			}
		}

		public struct Enumerator
		{
			private readonly T[] _array;

			private int _index;

			public T Current => _array[_index];

			internal Enumerator(T[] array)
			{
				_array = array;
				_index = -1;
			}

			public bool MoveNext()
			{
				return ++_index < _array.Length;
			}
		}

		private sealed class EnumeratorObject : IEnumerator<T>, IEnumerator, IDisposable
		{
			private static readonly IEnumerator<T> s_EmptyEnumerator = new EnumeratorObject(ImmutableArray<T>.Empty.array);

			private readonly T[] _array;

			private int _index;

			public T Current
			{
				get
				{
					if ((uint)_index < (uint)_array.Length)
					{
						return _array[_index];
					}
					throw new InvalidOperationException();
				}
			}

			object IEnumerator.Current => Current;

			private EnumeratorObject(T[] array)
			{
				_index = -1;
				_array = array;
			}

			public bool MoveNext()
			{
				int num = _index + 1;
				int num2 = _array.Length;
				if ((uint)num <= (uint)num2)
				{
					_index = num;
					return (uint)num < (uint)num2;
				}
				return false;
			}

			void IEnumerator.Reset()
			{
				_index = -1;
			}

			public void Dispose()
			{
			}

			internal static IEnumerator<T> Create(T[] array)
			{
				if (array.Length != 0)
				{
					return new EnumeratorObject(array);
				}
				return s_EmptyEnumerator;
			}
		}

		public static readonly ImmutableArray<T> Empty = new ImmutableArray<T>(new T[0]);

		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		internal readonly T[]? array;

		T IList<T>.this[int index]
		{
			get
			{
				ImmutableArray<T> immutableArray = this;
				immutableArray.ThrowInvalidOperationIfNotInitialized();
				return immutableArray[index];
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		bool ICollection<T>.IsReadOnly => true;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		int ICollection<T>.Count
		{
			get
			{
				ImmutableArray<T> immutableArray = this;
				immutableArray.ThrowInvalidOperationIfNotInitialized();
				return immutableArray.Length;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		int IReadOnlyCollection<T>.Count
		{
			get
			{
				ImmutableArray<T> immutableArray = this;
				immutableArray.ThrowInvalidOperationIfNotInitialized();
				return immutableArray.Length;
			}
		}

		T IReadOnlyList<T>.this[int index]
		{
			get
			{
				ImmutableArray<T> immutableArray = this;
				immutableArray.ThrowInvalidOperationIfNotInitialized();
				return immutableArray[index];
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		bool IList.IsFixedSize => true;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		bool IList.IsReadOnly => true;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		int ICollection.Count
		{
			get
			{
				ImmutableArray<T> immutableArray = this;
				immutableArray.ThrowInvalidOperationIfNotInitialized();
				return immutableArray.Length;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		bool ICollection.IsSynchronized => true;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		object ICollection.SyncRoot
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		object? IList.this[int index]
		{
			get
			{
				ImmutableArray<T> immutableArray = this;
				immutableArray.ThrowInvalidOperationIfNotInitialized();
				return immutableArray[index];
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public T this[int index]
		{
			[System.Runtime.Versioning.NonVersionable]
			get
			{
				return array[index];
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public bool IsEmpty
		{
			[System.Runtime.Versioning.NonVersionable]
			get
			{
				return array.Length == 0;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public int Length
		{
			[System.Runtime.Versioning.NonVersionable]
			get
			{
				return array.Length;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public bool IsDefault => array == null;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		public bool IsDefaultOrEmpty
		{
			get
			{
				ImmutableArray<T> immutableArray = this;
				if (immutableArray.array != null)
				{
					return immutableArray.array.Length == 0;
				}
				return true;
			}
		}

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		Array? IImmutableArray.Array => array;

		[DebuggerBrowsable(DebuggerBrowsableState.Never)]
		private string DebuggerDisplay
		{
			get
			{
				ImmutableArray<T> immutableArray = this;
				if (!immutableArray.IsDefault)
				{
					return $"Length = {immutableArray.Length}";
				}
				return "Uninitialized";
			}
		}

		public ReadOnlySpan<T> AsSpan()
		{
			return new ReadOnlySpan<T>(array);
		}

		public ReadOnlyMemory<T> AsMemory()
		{
			return new ReadOnlyMemory<T>(array);
		}

		public int IndexOf(T item)
		{
			ImmutableArray<T> immutableArray = this;
			return immutableArray.IndexOf(item, 0, immutableArray.Length, EqualityComparer<T>.Default);
		}

		public int IndexOf(T item, int startIndex, IEqualityComparer<T>? equalityComparer)
		{
			ImmutableArray<T> immutableArray = this;
			return immutableArray.IndexOf(item, startIndex, immutableArray.Length - startIndex, equalityComparer);
		}

		public int IndexOf(T item, int startIndex)
		{
			ImmutableArray<T> immutableArray = this;
			return immutableArray.IndexOf(item, startIndex, immutableArray.Length - startIndex, EqualityComparer<T>.Default);
		}

		public int IndexOf(T item, int startIndex, int count)
		{
			return IndexOf(item, startIndex, count, EqualityComparer<T>.Default);
		}

		public int IndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equalityComparer)
		{
			ImmutableArray<T> immutableArray = this;
			immutableArray.ThrowNullRefIfNotInitialized();
			if (count == 0 && startIndex == 0)
			{
				return -1;
			}
			Requires.Range(startIndex >= 0 && startIndex < immutableArray.Length, "startIndex");
			Requires.Range(count >= 0 && startIndex + count <= immutableArray.Length, "count");
			if (equalityComparer == null)
			{
				equalityComparer = EqualityComparer<T>.Default;
			}
			if (equalityComparer == EqualityComparer<T>.Default)
			{
				return Array.IndexOf(immutableArray.array, item, startIndex, count);
			}
			for (int i = startIndex; i < startIndex + count; i++)
			{
				if (equalityComparer.Equals(immutableArray.array[i], item))
				{
					return i;
				}
			}
			return -1;
		}

		public int LastIndexOf(T item)
		{
			ImmutableArray<T> immutableArray = this;
			if (immutableArray.IsEmpty)
			{
				return -1;
			}
			return immutableArray.LastIndexOf(item, immutableArray.Length - 1, immutableArray.Length, EqualityComparer<T>.Default);
		}

		public int LastIndexOf(T item, int startIndex)
		{
			ImmutableArray<T> immutableArray = this;
			if (immutableArray.IsEmpty && startIndex == 0)
			{
				return -1;
			}
			return immutableArray.LastIndexOf(item, startIndex, startIndex + 1, EqualityComparer<T>.Default);
		}

		public int LastIndexOf(T item, int startIndex, int count)
		{
			return LastIndexOf(item, startIndex, count, EqualityComparer<T>.Default);
		}

		public int LastIndexOf(T item, int startIndex, int count, IEqualityComparer<T>? equali

BepInEx/core/System.ComponentModel.Composition.dll

Decompiled 2 weeks ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.AttributedModel;
using System.ComponentModel.Composition.Diagnostics;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.ComponentModel.Composition.ReflectionModel;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Text;
using System.Threading;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
using Microsoft.Internal.Runtime.Serialization;
using Unity;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.ComponentModel.Composition.dll")]
[assembly: AssemblyDescription("System.ComponentModel.Composition.dll")]
[assembly: AssemblyDefaultAlias("System.ComponentModel.Composition.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Microsoft Corporation. All rights reserved.")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: InternalsVisibleTo("net_4_x_System.ComponentModel.Composition_xunit-test, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
[assembly: SecurityCritical]
[assembly: AllowPartiallyTrustedCallers]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("4.0.0.0")]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
namespace Microsoft.Internal
{
	internal static class Assumes
	{
		[Serializable]
		private class InternalErrorException : Exception
		{
			public InternalErrorException(string message)
				: base(string.Format(CultureInfo.CurrentCulture, Strings.InternalExceptionMessage, message))
			{
			}

			[SecuritySafeCritical]
			protected InternalErrorException(SerializationInfo info, StreamingContext context)
				: base(info, context)
			{
			}
		}

		[DebuggerStepThrough]
		internal static void NotNull<T>(T value) where T : class
		{
			IsTrue(value != null);
		}

		[DebuggerStepThrough]
		internal static void NotNull<T1, T2>(T1 value1, T2 value2) where T1 : class where T2 : class
		{
			NotNull(value1);
			NotNull(value2);
		}

		[DebuggerStepThrough]
		internal static void NotNull<T1, T2, T3>(T1 value1, T2 value2, T3 value3) where T1 : class where T2 : class where T3 : class
		{
			NotNull(value1);
			NotNull(value2);
			NotNull(value3);
		}

		[DebuggerStepThrough]
		internal static void NotNullOrEmpty(string value)
		{
			NotNull(value);
			IsTrue(value.Length > 0);
		}

		[DebuggerStepThrough]
		internal static void IsTrue(bool condition)
		{
			if (!condition)
			{
				throw UncatchableException(null);
			}
		}

		[DebuggerStepThrough]
		internal static void IsTrue(bool condition, string message)
		{
			if (!condition)
			{
				throw UncatchableException(message);
			}
		}

		[DebuggerStepThrough]
		internal static T NotReachable<T>()
		{
			throw UncatchableException("Code path should never be reached!");
		}

		[DebuggerStepThrough]
		private static Exception UncatchableException(string message)
		{
			return new InternalErrorException(message);
		}
	}
	internal static class AttributeServices
	{
		public static T[] GetAttributes<T>(this ICustomAttributeProvider attributeProvider) where T : class
		{
			return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit: false);
		}

		public static T[] GetAttributes<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class
		{
			return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit);
		}

		public static T GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider) where T : class
		{
			return attributeProvider.GetAttributes<T>().FirstOrDefault();
		}

		public static T GetFirstAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class
		{
			return attributeProvider.GetAttributes<T>(inherit).FirstOrDefault();
		}

		public static bool IsAttributeDefined<T>(this ICustomAttributeProvider attributeProvider) where T : class
		{
			return attributeProvider.IsDefined(typeof(T), inherit: false);
		}

		public static bool IsAttributeDefined<T>(this ICustomAttributeProvider attributeProvider, bool inherit) where T : class
		{
			return attributeProvider.IsDefined(typeof(T), inherit);
		}
	}
	internal static class ContractServices
	{
		public static bool TryCast(Type contractType, object value, out object result)
		{
			if (value == null)
			{
				result = null;
				return true;
			}
			if (contractType.IsInstanceOfType(value))
			{
				result = value;
				return true;
			}
			if (typeof(Delegate).IsAssignableFrom(contractType) && value is ExportedDelegate exportedDelegate)
			{
				result = exportedDelegate.CreateDelegate(contractType.UnderlyingSystemType);
				return result != null;
			}
			result = null;
			return false;
		}
	}
	internal static class GenerationServices
	{
		private static readonly MethodInfo _typeGetTypeFromHandleMethod = typeof(Type).GetMethod("GetTypeFromHandle");

		private static readonly Type TypeType = typeof(Type);

		private static readonly Type StringType = typeof(string);

		private static readonly Type CharType = typeof(char);

		private static readonly Type BooleanType = typeof(bool);

		private static readonly Type ByteType = typeof(byte);

		private static readonly Type SByteType = typeof(sbyte);

		private static readonly Type Int16Type = typeof(short);

		private static readonly Type UInt16Type = typeof(ushort);

		private static readonly Type Int32Type = typeof(int);

		private static readonly Type UInt32Type = typeof(uint);

		private static readonly Type Int64Type = typeof(long);

		private static readonly Type UInt64Type = typeof(ulong);

		private static readonly Type DoubleType = typeof(double);

		private static readonly Type SingleType = typeof(float);

		private static readonly Type IEnumerableTypeofT = typeof(IEnumerable<>);

		private static readonly Type IEnumerableType = typeof(IEnumerable);

		private static readonly MethodInfo ExceptionGetData = typeof(Exception).GetProperty("Data").GetGetMethod();

		private static readonly MethodInfo DictionaryAdd = typeof(IDictionary).GetMethod("Add");

		private static readonly ConstructorInfo ObjectCtor = typeof(object).GetConstructor(Type.EmptyTypes);

		public static ILGenerator CreateGeneratorForPublicConstructor(this TypeBuilder typeBuilder, Type[] ctrArgumentTypes)
		{
			ILGenerator iLGenerator = typeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard, ctrArgumentTypes).GetILGenerator();
			iLGenerator.Emit(OpCodes.Ldarg_0);
			iLGenerator.Emit(OpCodes.Call, ObjectCtor);
			return iLGenerator;
		}

		public static void LoadValue(this ILGenerator ilGenerator, object value)
		{
			Assumes.NotNull(ilGenerator);
			if (value == null)
			{
				ilGenerator.LoadNull();
				return;
			}
			Type type = value.GetType();
			object obj = value;
			if (type.IsEnum)
			{
				obj = Convert.ChangeType(value, Enum.GetUnderlyingType(type), null);
				type = obj.GetType();
			}
			if (type == StringType)
			{
				ilGenerator.LoadString((string)obj);
				return;
			}
			if (TypeType.IsAssignableFrom(type))
			{
				ilGenerator.LoadTypeOf((Type)obj);
				return;
			}
			if (IEnumerableType.IsAssignableFrom(type))
			{
				ilGenerator.LoadEnumerable((IEnumerable)obj);
				return;
			}
			if (type == CharType || type == BooleanType || type == ByteType || type == SByteType || type == Int16Type || type == UInt16Type || type == Int32Type)
			{
				ilGenerator.LoadInt((int)Convert.ChangeType(obj, typeof(int), CultureInfo.InvariantCulture));
				return;
			}
			if (type == UInt32Type)
			{
				ilGenerator.LoadInt((int)(uint)obj);
				return;
			}
			if (type == Int64Type)
			{
				ilGenerator.LoadLong((long)obj);
				return;
			}
			if (type == UInt64Type)
			{
				ilGenerator.LoadLong((long)(ulong)obj);
				return;
			}
			if (type == SingleType)
			{
				ilGenerator.LoadFloat((float)obj);
				return;
			}
			if (type == DoubleType)
			{
				ilGenerator.LoadDouble((double)obj);
				return;
			}
			throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.InvalidMetadataValue, value.GetType().FullName));
		}

		public static void AddItemToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, object value)
		{
			Assumes.NotNull(ilGenerator);
			Assumes.NotNull(dictionary);
			Assumes.NotNull(key);
			Assumes.NotNull(value);
			ilGenerator.Emit(OpCodes.Ldloc, dictionary);
			ilGenerator.LoadValue(key);
			ilGenerator.LoadValue(value);
			ilGenerator.Emit(OpCodes.Callvirt, DictionaryAdd);
		}

		public static void AddLocalToLocalDictionary(this ILGenerator ilGenerator, LocalBuilder dictionary, object key, LocalBuilder value)
		{
			Assumes.NotNull(ilGenerator);
			Assumes.NotNull(dictionary);
			Assumes.NotNull(key);
			Assumes.NotNull(value);
			ilGenerator.Emit(OpCodes.Ldloc, dictionary);
			ilGenerator.LoadValue(key);
			ilGenerator.Emit(OpCodes.Ldloc, value);
			ilGenerator.Emit(OpCodes.Callvirt, DictionaryAdd);
		}

		public static void GetExceptionDataAndStoreInLocal(this ILGenerator ilGenerator, LocalBuilder exception, LocalBuilder dataStore)
		{
			Assumes.NotNull(ilGenerator);
			Assumes.NotNull(exception);
			Assumes.NotNull(dataStore);
			ilGenerator.Emit(OpCodes.Ldloc, exception);
			ilGenerator.Emit(OpCodes.Callvirt, ExceptionGetData);
			ilGenerator.Emit(OpCodes.Stloc, dataStore);
		}

		private static void LoadEnumerable(this ILGenerator ilGenerator, IEnumerable enumerable)
		{
			Assumes.NotNull(ilGenerator);
			Assumes.NotNull(enumerable);
			Type type = null;
			Type targetClosedInterfaceType = null;
			type = ((!ReflectionServices.TryGetGenericInterfaceType(enumerable.GetType(), IEnumerableTypeofT, out targetClosedInterfaceType)) ? typeof(object) : targetClosedInterfaceType.GetGenericArguments()[0]);
			Type localType = type.MakeArrayType();
			LocalBuilder local = ilGenerator.DeclareLocal(localType);
			ilGenerator.LoadInt(enumerable.Cast<object>().Count());
			ilGenerator.Emit(OpCodes.Newarr, type);
			ilGenerator.Emit(OpCodes.Stloc, local);
			int num = 0;
			foreach (object item in enumerable)
			{
				ilGenerator.Emit(OpCodes.Ldloc, local);
				ilGenerator.LoadInt(num);
				ilGenerator.LoadValue(item);
				if (IsBoxingRequiredForValue(item) && !type.IsValueType)
				{
					ilGenerator.Emit(OpCodes.Box, item.GetType());
				}
				ilGenerator.Emit(OpCodes.Stelem, type);
				num++;
			}
			ilGenerator.Emit(OpCodes.Ldloc, local);
		}

		private static bool IsBoxingRequiredForValue(object value)
		{
			return value?.GetType().IsValueType ?? false;
		}

		private static void LoadNull(this ILGenerator ilGenerator)
		{
			ilGenerator.Emit(OpCodes.Ldnull);
		}

		private static void LoadString(this ILGenerator ilGenerator, string s)
		{
			Assumes.NotNull(ilGenerator);
			if (s == null)
			{
				ilGenerator.LoadNull();
			}
			else
			{
				ilGenerator.Emit(OpCodes.Ldstr, s);
			}
		}

		private static void LoadInt(this ILGenerator ilGenerator, int value)
		{
			Assumes.NotNull(ilGenerator);
			ilGenerator.Emit(OpCodes.Ldc_I4, value);
		}

		private static void LoadLong(this ILGenerator ilGenerator, long value)
		{
			Assumes.NotNull(ilGenerator);
			ilGenerator.Emit(OpCodes.Ldc_I8, value);
		}

		private static void LoadFloat(this ILGenerator ilGenerator, float value)
		{
			Assumes.NotNull(ilGenerator);
			ilGenerator.Emit(OpCodes.Ldc_R4, value);
		}

		private static void LoadDouble(this ILGenerator ilGenerator, double value)
		{
			Assumes.NotNull(ilGenerator);
			ilGenerator.Emit(OpCodes.Ldc_R8, value);
		}

		private static void LoadTypeOf(this ILGenerator ilGenerator, Type type)
		{
			Assumes.NotNull(ilGenerator);
			ilGenerator.Emit(OpCodes.Ldtoken, type);
			ilGenerator.EmitCall(OpCodes.Call, _typeGetTypeFromHandleMethod, null);
		}
	}
	internal static class LazyServices
	{
		public static T GetNotNullValue<T>(this Lazy<T> lazy, string argument) where T : class
		{
			Assumes.NotNull(lazy);
			return lazy.Value ?? throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings.LazyServices_LazyResolvesToNull, typeof(T), argument));
		}
	}
	internal struct ReadLock : IDisposable
	{
		private readonly Lock _lock;

		private int _isDisposed;

		public ReadLock(Lock @lock)
		{
			_isDisposed = 0;
			_lock = @lock;
			_lock.EnterReadLock();
		}

		public void Dispose()
		{
			if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
			{
				_lock.ExitReadLock();
			}
		}
	}
	internal struct WriteLock : IDisposable
	{
		private readonly Lock _lock;

		private int _isDisposed;

		public WriteLock(Lock @lock)
		{
			_isDisposed = 0;
			_lock = @lock;
			_lock.EnterWriteLock();
		}

		public void Dispose()
		{
			if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
			{
				_lock.ExitWriteLock();
			}
		}
	}
	internal sealed class Lock : IDisposable
	{
		private ReaderWriterLockSlim _thisLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

		private int _isDisposed;

		public void EnterReadLock()
		{
			_thisLock.EnterReadLock();
		}

		public void EnterWriteLock()
		{
			_thisLock.EnterWriteLock();
		}

		public void ExitReadLock()
		{
			_thisLock.ExitReadLock();
		}

		public void ExitWriteLock()
		{
			_thisLock.ExitWriteLock();
		}

		public void Dispose()
		{
			if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
			{
				_thisLock.Dispose();
			}
		}
	}
	internal static class ReflectionInvoke
	{
		public static object SafeCreateInstance(this Type type, params object[] arguments)
		{
			DemandMemberAccessIfNeeded(type);
			return Activator.CreateInstance(type, arguments);
		}

		public static object SafeInvoke(this ConstructorInfo constructor, params object[] arguments)
		{
			DemandMemberAccessIfNeeded(constructor);
			return constructor.Invoke(arguments);
		}

		public static object SafeInvoke(this MethodInfo method, object instance, params object[] arguments)
		{
			DemandMemberAccessIfNeeded(method);
			return method.Invoke(instance, arguments);
		}

		public static object SafeGetValue(this FieldInfo field, object instance)
		{
			DemandMemberAccessIfNeeded(field);
			return field.GetValue(instance);
		}

		public static void SafeSetValue(this FieldInfo field, object instance, object value)
		{
			DemandMemberAccessIfNeeded(field);
			field.SetValue(instance, value);
		}

		public static void DemandMemberAccessIfNeeded(MethodInfo method)
		{
		}

		private static void DemandMemberAccessIfNeeded(ConstructorInfo constructor)
		{
		}

		private static void DemandMemberAccessIfNeeded(FieldInfo field)
		{
		}

		public static void DemandMemberAccessIfNeeded(Type type)
		{
		}
	}
	internal static class ReflectionServices
	{
		public static Assembly Assembly(this MemberInfo member)
		{
			Type type = member as Type;
			if (type != null)
			{
				return type.Assembly;
			}
			return member.DeclaringType.Assembly;
		}

		public static bool IsVisible(this ConstructorInfo constructor)
		{
			if (constructor.DeclaringType.IsVisible)
			{
				return constructor.IsPublic;
			}
			return false;
		}

		public static bool IsVisible(this FieldInfo field)
		{
			if (field.DeclaringType.IsVisible)
			{
				return field.IsPublic;
			}
			return false;
		}

		public static bool IsVisible(this MethodInfo method)
		{
			if (!method.DeclaringType.IsVisible)
			{
				return false;
			}
			if (!method.IsPublic)
			{
				return false;
			}
			if (method.IsGenericMethod)
			{
				Type[] genericArguments = method.GetGenericArguments();
				for (int i = 0; i < genericArguments.Length; i++)
				{
					if (!genericArguments[i].IsVisible)
					{
						return false;
					}
				}
			}
			return true;
		}

		public static string GetDisplayName(Type declaringType, string name)
		{
			Assumes.NotNull(declaringType);
			return declaringType.GetDisplayName() + "." + name;
		}

		public static string GetDisplayName(this MemberInfo member)
		{
			Assumes.NotNull(member);
			MemberTypes memberType = member.MemberType;
			if (memberType == MemberTypes.TypeInfo || memberType == MemberTypes.NestedType)
			{
				return AttributedModelServices.GetTypeIdentity((Type)member);
			}
			return GetDisplayName(member.DeclaringType, member.Name);
		}

		internal static bool TryGetGenericInterfaceType(Type instanceType, Type targetOpenInterfaceType, out Type targetClosedInterfaceType)
		{
			Assumes.IsTrue(targetOpenInterfaceType.IsInterface);
			Assumes.IsTrue(targetOpenInterfaceType.IsGenericTypeDefinition);
			Assumes.IsTrue(!instanceType.IsGenericTypeDefinition);
			if (instanceType.IsInterface && instanceType.IsGenericType && instanceType.UnderlyingSystemType.GetGenericTypeDefinition() == targetOpenInterfaceType.UnderlyingSystemType)
			{
				targetClosedInterfaceType = instanceType;
				return true;
			}
			try
			{
				Type @interface = instanceType.GetInterface(targetOpenInterfaceType.Name, ignoreCase: false);
				if (@interface != null && @interface.UnderlyingSystemType.GetGenericTypeDefinition() == targetOpenInterfaceType.UnderlyingSystemType)
				{
					targetClosedInterfaceType = @interface;
					return true;
				}
			}
			catch (AmbiguousMatchException)
			{
			}
			targetClosedInterfaceType = null;
			return false;
		}

		internal static IEnumerable<PropertyInfo> GetAllProperties(this Type type)
		{
			return type.GetInterfaces().Concat(new Type[1] { type }).SelectMany((Type itf) => itf.GetProperties());
		}

		internal static IEnumerable<MethodInfo> GetAllMethods(this Type type)
		{
			IEnumerable<MethodInfo> declaredMethods = type.GetDeclaredMethods();
			Type baseType = type.BaseType;
			if (baseType.UnderlyingSystemType != typeof(object))
			{
				return declaredMethods.Concat(baseType.GetAllMethods());
			}
			return declaredMethods;
		}

		private static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type)
		{
			MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			for (int i = 0; i < methods.Length; i++)
			{
				yield return methods[i];
			}
		}

		public static IEnumerable<FieldInfo> GetAllFields(this Type type)
		{
			IEnumerable<FieldInfo> declaredFields = type.GetDeclaredFields();
			Type baseType = type.BaseType;
			if (baseType.UnderlyingSystemType != typeof(object))
			{
				return declaredFields.Concat(baseType.GetAllFields());
			}
			return declaredFields;
		}

		private static IEnumerable<FieldInfo> GetDeclaredFields(this Type type)
		{
			FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			for (int i = 0; i < fields.Length; i++)
			{
				yield return fields[i];
			}
		}
	}
	internal static class Requires
	{
		[DebuggerStepThrough]
		public static void NotNull<T>(T value, string parameterName) where T : class
		{
			if (value == null)
			{
				throw new ArgumentNullException(parameterName);
			}
		}

		[DebuggerStepThrough]
		public static void NotNullOrEmpty(string value, string parameterName)
		{
			NotNull(value, parameterName);
			if (value.Length == 0)
			{
				throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.ArgumentException_EmptyString, parameterName), parameterName);
			}
		}

		[DebuggerStepThrough]
		public static void NotNullOrNullElements<T>(IEnumerable<T> values, string parameterName) where T : class
		{
			NotNull(values, parameterName);
			NotNullElements(values, parameterName);
		}

		[DebuggerStepThrough]
		public static void NullOrNotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> values, string parameterName) where TKey : class where TValue : class
		{
			NotNullElements(values, parameterName);
		}

		[DebuggerStepThrough]
		public static void NullOrNotNullElements<T>(IEnumerable<T> values, string parameterName) where T : class
		{
			NotNullElements(values, parameterName);
		}

		private static void NotNullElements<T>(IEnumerable<T> values, string parameterName) where T : class
		{
			if (values != null && !Contract.ForAll(values, (T value) => value != null))
			{
				throw ExceptionBuilder.CreateContainsNullElement(parameterName);
			}
		}

		private static void NotNullElements<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> values, string parameterName) where TKey : class where TValue : class
		{
			if (values != null && !Contract.ForAll(values, (KeyValuePair<TKey, TValue> keyValue) => keyValue.Key != null && keyValue.Value != null))
			{
				throw ExceptionBuilder.CreateContainsNullElement(parameterName);
			}
		}

		[DebuggerStepThrough]
		public static void IsInMembertypeSet(MemberTypes value, string parameterName, MemberTypes enumFlagSet)
		{
			if ((value & enumFlagSet) != value || (value & (value - 1)) != 0)
			{
				throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.ArgumentOutOfRange_InvalidEnumInSet, parameterName, value, enumFlagSet.ToString()), parameterName);
			}
		}
	}
	internal static class StringComparers
	{
		public static StringComparer ContractName => StringComparer.Ordinal;

		public static StringComparer MetadataKeyNames => StringComparer.Ordinal;
	}
	[GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
	[DebuggerNonUserCode]
	[CompilerGenerated]
	internal class Strings
	{
		private static ResourceManager resourceMan;

		private static CultureInfo resourceCulture;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static ResourceManager ResourceManager
		{
			get
			{
				if (resourceMan == null)
				{
					resourceMan = new ResourceManager("Microsoft.Internal.Strings", typeof(Strings).Assembly);
				}
				return resourceMan;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		internal static CultureInfo Culture
		{
			get
			{
				return resourceCulture;
			}
			set
			{
				resourceCulture = value;
			}
		}

		internal static string Argument_AssemblyReflectionOnly => ResourceManager.GetString("Argument_AssemblyReflectionOnly", resourceCulture);

		internal static string Argument_ElementReflectionOnlyType => ResourceManager.GetString("Argument_ElementReflectionOnlyType", resourceCulture);

		internal static string Argument_ExportsEmpty => ResourceManager.GetString("Argument_ExportsEmpty", resourceCulture);

		internal static string Argument_ExportsTooMany => ResourceManager.GetString("Argument_ExportsTooMany", resourceCulture);

		internal static string Argument_NullElement => ResourceManager.GetString("Argument_NullElement", resourceCulture);

		internal static string Argument_ReflectionContextReturnsReflectionOnlyType => ResourceManager.GetString("Argument_ReflectionContextReturnsReflectionOnlyType", resourceCulture);

		internal static string ArgumentException_EmptyString => ResourceManager.GetString("ArgumentException_EmptyString", resourceCulture);

		internal static string ArgumentOutOfRange_InvalidEnum => ResourceManager.GetString("ArgumentOutOfRange_InvalidEnum", resourceCulture);

		internal static string ArgumentOutOfRange_InvalidEnumInSet => ResourceManager.GetString("ArgumentOutOfRange_InvalidEnumInSet", resourceCulture);

		internal static string ArgumentValueType => ResourceManager.GetString("ArgumentValueType", resourceCulture);

		internal static string AssemblyFileNotFoundOrWrongType => ResourceManager.GetString("AssemblyFileNotFoundOrWrongType", resourceCulture);

		internal static string AtomicComposition_AlreadyCompleted => ResourceManager.GetString("AtomicComposition_AlreadyCompleted", resourceCulture);

		internal static string AtomicComposition_AlreadyNested => ResourceManager.GetString("AtomicComposition_AlreadyNested", resourceCulture);

		internal static string AtomicComposition_PartOfAnotherAtomicComposition => ResourceManager.GetString("AtomicComposition_PartOfAnotherAtomicComposition", resourceCulture);

		internal static string CardinalityMismatch_NoExports => ResourceManager.GetString("CardinalityMismatch_NoExports", resourceCulture);

		internal static string CardinalityMismatch_TooManyExports => ResourceManager.GetString("CardinalityMismatch_TooManyExports", resourceCulture);

		internal static string CatalogMutation_Invalid => ResourceManager.GetString("CatalogMutation_Invalid", resourceCulture);

		internal static string CompositionElement_UnknownOrigin => ResourceManager.GetString("CompositionElement_UnknownOrigin", resourceCulture);

		internal static string CompositionException_ChangesRejected => ResourceManager.GetString("CompositionException_ChangesRejected", resourceCulture);

		internal static string CompositionException_ElementPrefix => ResourceManager.GetString("CompositionException_ElementPrefix", resourceCulture);

		internal static string CompositionException_ErrorPrefix => ResourceManager.GetString("CompositionException_ErrorPrefix", resourceCulture);

		internal static string CompositionException_MetadataViewInvalidConstructor => ResourceManager.GetString("CompositionException_MetadataViewInvalidConstructor", resourceCulture);

		internal static string CompositionException_MultipleErrorsWithMultiplePaths => ResourceManager.GetString("CompositionException_MultipleErrorsWithMultiplePaths", resourceCulture);

		internal static string CompositionException_OriginFormat => ResourceManager.GetString("CompositionException_OriginFormat", resourceCulture);

		internal static string CompositionException_OriginSeparator => ResourceManager.GetString("CompositionException_OriginSeparator", resourceCulture);

		internal static string CompositionException_PathsCountSeparator => ResourceManager.GetString("CompositionException_PathsCountSeparator", resourceCulture);

		internal static string CompositionException_ReviewErrorProperty => ResourceManager.GetString("CompositionException_ReviewErrorProperty", resourceCulture);

		internal static string CompositionException_SingleErrorWithMultiplePaths => ResourceManager.GetString("CompositionException_SingleErrorWithMultiplePaths", resourceCulture);

		internal static string CompositionException_SingleErrorWithSinglePath => ResourceManager.GetString("CompositionException_SingleErrorWithSinglePath", resourceCulture);

		internal static string CompositionTrace_Discovery_AssemblyLoadFailed => ResourceManager.GetString("CompositionTrace_Discovery_AssemblyLoadFailed", resourceCulture);

		internal static string CompositionTrace_Discovery_DefinitionContainsNoExports => ResourceManager.GetString("CompositionTrace_Discovery_DefinitionContainsNoExports", resourceCulture);

		internal static string CompositionTrace_Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute => ResourceManager.GetString("CompositionTrace_Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute", resourceCulture);

		internal static string CompositionTrace_Discovery_DefinitionMismatchedExportArity => ResourceManager.GetString("CompositionTrace_Discovery_DefinitionMismatchedExportArity", resourceCulture);

		internal static string CompositionTrace_Discovery_MemberMarkedWithMultipleImportAndImportMany => ResourceManager.GetString("CompositionTrace_Discovery_MemberMarkedWithMultipleImportAndImportMany", resourceCulture);

		internal static string CompositionTrace_Rejection_DefinitionRejected => ResourceManager.GetString("CompositionTrace_Rejection_DefinitionRejected", resourceCulture);

		internal static string CompositionTrace_Rejection_DefinitionResurrected => ResourceManager.GetString("CompositionTrace_Rejection_DefinitionResurrected", resourceCulture);

		internal static string ContractMismatch_ExportedValueCannotBeCastToT => ResourceManager.GetString("ContractMismatch_ExportedValueCannotBeCastToT", resourceCulture);

		internal static string ContractMismatch_InvalidCastOnMetadataField => ResourceManager.GetString("ContractMismatch_InvalidCastOnMetadataField", resourceCulture);

		internal static string ContractMismatch_MetadataViewImplementationCanNotBeNull => ResourceManager.GetString("ContractMismatch_MetadataViewImplementationCanNotBeNull", resourceCulture);

		internal static string ContractMismatch_MetadataViewImplementationDoesNotImplementViewInterface => ResourceManager.GetString("ContractMismatch_MetadataViewImplementationDoesNotImplementViewInterface", resourceCulture);

		internal static string ContractMismatch_NullReferenceOnMetadataField => ResourceManager.GetString("ContractMismatch_NullReferenceOnMetadataField", resourceCulture);

		internal static string DirectoryNotFound => ResourceManager.GetString("DirectoryNotFound", resourceCulture);

		internal static string Discovery_DuplicateMetadataNameValues => ResourceManager.GetString("Discovery_DuplicateMetadataNameValues", resourceCulture);

		internal static string Discovery_MetadataContainsValueWithInvalidType => ResourceManager.GetString("Discovery_MetadataContainsValueWithInvalidType", resourceCulture);

		internal static string Discovery_ReservedMetadataNameUsed => ResourceManager.GetString("Discovery_ReservedMetadataNameUsed", resourceCulture);

		internal static string ExportDefinitionNotOnThisComposablePart => ResourceManager.GetString("ExportDefinitionNotOnThisComposablePart", resourceCulture);

		internal static string ExportFactory_TooManyGenericParameters => ResourceManager.GetString("ExportFactory_TooManyGenericParameters", resourceCulture);

		internal static string ExportNotValidOnIndexers => ResourceManager.GetString("ExportNotValidOnIndexers", resourceCulture);

		internal static string ImportDefinitionNotOnThisComposablePart => ResourceManager.GetString("ImportDefinitionNotOnThisComposablePart", resourceCulture);

		internal static string ImportEngine_ComposeTookTooManyIterations => ResourceManager.GetString("ImportEngine_ComposeTookTooManyIterations", resourceCulture);

		internal static string ImportEngine_InvalidStateForRecomposition => ResourceManager.GetString("ImportEngine_InvalidStateForRecomposition", resourceCulture);

		internal static string ImportEngine_PartCannotActivate => ResourceManager.GetString("ImportEngine_PartCannotActivate", resourceCulture);

		internal static string ImportEngine_PartCannotGetExportedValue => ResourceManager.GetString("ImportEngine_PartCannotGetExportedValue", resourceCulture);

		internal static string ImportEngine_PartCannotSetImport => ResourceManager.GetString("ImportEngine_PartCannotSetImport", resourceCulture);

		internal static string ImportEngine_PartCycle => ResourceManager.GetString("ImportEngine_PartCycle", resourceCulture);

		internal static string ImportEngine_PreventedByExistingImport => ResourceManager.GetString("ImportEngine_PreventedByExistingImport", resourceCulture);

		internal static string ImportNotSetOnPart => ResourceManager.GetString("ImportNotSetOnPart", resourceCulture);

		internal static string ImportNotValidOnIndexers => ResourceManager.GetString("ImportNotValidOnIndexers", resourceCulture);

		internal static string InternalExceptionMessage => ResourceManager.GetString("InternalExceptionMessage", resourceCulture);

		internal static string InvalidArgument_ReflectionContext => ResourceManager.GetString("InvalidArgument_ReflectionContext", resourceCulture);

		internal static string InvalidMetadataValue => ResourceManager.GetString("InvalidMetadataValue", resourceCulture);

		internal static string InvalidMetadataView => ResourceManager.GetString("InvalidMetadataView", resourceCulture);

		internal static string InvalidOperation_DefinitionCannotBeRecomposed => ResourceManager.GetString("InvalidOperation_DefinitionCannotBeRecomposed", resourceCulture);

		internal static string InvalidOperation_GetExportedValueBeforePrereqImportSet => ResourceManager.GetString("InvalidOperation_GetExportedValueBeforePrereqImportSet", resourceCulture);

		internal static string InvalidOperationReentrantCompose => ResourceManager.GetString("InvalidOperationReentrantCompose", resourceCulture);

		internal static string InvalidPartCreationPolicyOnImport => ResourceManager.GetString("InvalidPartCreationPolicyOnImport", resourceCulture);

		internal static string InvalidPartCreationPolicyOnPart => ResourceManager.GetString("InvalidPartCreationPolicyOnPart", resourceCulture);

		internal static string InvalidSetterOnMetadataField => ResourceManager.GetString("InvalidSetterOnMetadataField", resourceCulture);

		internal static string LazyMemberInfo_AccessorsNull => ResourceManager.GetString("LazyMemberInfo_AccessorsNull", resourceCulture);

		internal static string LazyMemberInfo_InvalidAccessorOnSimpleMember => ResourceManager.GetString("LazyMemberInfo_InvalidAccessorOnSimpleMember", resourceCulture);

		internal static string LazyMemberinfo_InvalidEventAccessors_AccessorType => ResourceManager.GetString("LazyMemberinfo_InvalidEventAccessors_AccessorType", resourceCulture);

		internal static string LazyMemberInfo_InvalidEventAccessors_Cardinality => ResourceManager.GetString("LazyMemberInfo_InvalidEventAccessors_Cardinality", resourceCulture);

		internal static string LazyMemberinfo_InvalidPropertyAccessors_AccessorType => ResourceManager.GetString("LazyMemberinfo_InvalidPropertyAccessors_AccessorType", resourceCulture);

		internal static string LazyMemberInfo_InvalidPropertyAccessors_Cardinality => ResourceManager.GetString("LazyMemberInfo_InvalidPropertyAccessors_Cardinality", resourceCulture);

		internal static string LazyMemberInfo_NoAccessors => ResourceManager.GetString("LazyMemberInfo_NoAccessors", resourceCulture);

		internal static string LazyServices_LazyResolvesToNull => ResourceManager.GetString("LazyServices_LazyResolvesToNull", resourceCulture);

		internal static string MetadataItemNotSupported => ResourceManager.GetString("MetadataItemNotSupported", resourceCulture);

		internal static string NotImplemented_NotOverriddenByDerived => ResourceManager.GetString("NotImplemented_NotOverriddenByDerived", resourceCulture);

		internal static string NotSupportedCatalogChanges => ResourceManager.GetString("NotSupportedCatalogChanges", resourceCulture);

		internal static string NotSupportedInterfaceMetadataView => ResourceManager.GetString("NotSupportedInterfaceMetadataView", resourceCulture);

		internal static string NotSupportedReadOnlyDictionary => ResourceManager.GetString("NotSupportedReadOnlyDictionary", resourceCulture);

		internal static string ObjectAlreadyInitialized => ResourceManager.GetString("ObjectAlreadyInitialized", resourceCulture);

		internal static string ObjectMustBeInitialized => ResourceManager.GetString("ObjectMustBeInitialized", resourceCulture);

		internal static string ReentrantCompose => ResourceManager.GetString("ReentrantCompose", resourceCulture);

		internal static string ReflectionContext_Requires_DefaultConstructor => ResourceManager.GetString("ReflectionContext_Requires_DefaultConstructor", resourceCulture);

		internal static string ReflectionContext_Type_Required => ResourceManager.GetString("ReflectionContext_Type_Required", resourceCulture);

		internal static string ReflectionModel_ExportNotReadable => ResourceManager.GetString("ReflectionModel_ExportNotReadable", resourceCulture);

		internal static string ReflectionModel_ExportThrewException => ResourceManager.GetString("ReflectionModel_ExportThrewException", resourceCulture);

		internal static string ReflectionModel_ImportCollectionAddThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionAddThrewException", resourceCulture);

		internal static string ReflectionModel_ImportCollectionClearThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionClearThrewException", resourceCulture);

		internal static string ReflectionModel_ImportCollectionConstructionThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionConstructionThrewException", resourceCulture);

		internal static string ReflectionModel_ImportCollectionGetThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionGetThrewException", resourceCulture);

		internal static string ReflectionModel_ImportCollectionIsReadOnlyThrewException => ResourceManager.GetString("ReflectionModel_ImportCollectionIsReadOnlyThrewException", resourceCulture);

		internal static string ReflectionModel_ImportCollectionNotWritable => ResourceManager.GetString("ReflectionModel_ImportCollectionNotWritable", resourceCulture);

		internal static string ReflectionModel_ImportCollectionNull => ResourceManager.GetString("ReflectionModel_ImportCollectionNull", resourceCulture);

		internal static string ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned => ResourceManager.GetString("ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned", resourceCulture);

		internal static string ReflectionModel_ImportNotAssignableFromExport => ResourceManager.GetString("ReflectionModel_ImportNotAssignableFromExport", resourceCulture);

		internal static string ReflectionModel_ImportNotWritable => ResourceManager.GetString("ReflectionModel_ImportNotWritable", resourceCulture);

		internal static string ReflectionModel_ImportThrewException => ResourceManager.GetString("ReflectionModel_ImportThrewException", resourceCulture);

		internal static string ReflectionModel_InvalidExportDefinition => ResourceManager.GetString("ReflectionModel_InvalidExportDefinition", resourceCulture);

		internal static string ReflectionModel_InvalidImportDefinition => ResourceManager.GetString("ReflectionModel_InvalidImportDefinition", resourceCulture);

		internal static string ReflectionModel_InvalidMemberImportDefinition => ResourceManager.GetString("ReflectionModel_InvalidMemberImportDefinition", resourceCulture);

		internal static string ReflectionModel_InvalidParameterImportDefinition => ResourceManager.GetString("ReflectionModel_InvalidParameterImportDefinition", resourceCulture);

		internal static string ReflectionModel_InvalidPartDefinition => ResourceManager.GetString("ReflectionModel_InvalidPartDefinition", resourceCulture);

		internal static string ReflectionModel_PartConstructorMissing => ResourceManager.GetString("ReflectionModel_PartConstructorMissing", resourceCulture);

		internal static string ReflectionModel_PartConstructorThrewException => ResourceManager.GetString("ReflectionModel_PartConstructorThrewException", resourceCulture);

		internal static string ReflectionModel_PartOnImportsSatisfiedThrewException => ResourceManager.GetString("ReflectionModel_PartOnImportsSatisfiedThrewException", resourceCulture);

		internal static string TypeCatalog_DisplayNameFormat => ResourceManager.GetString("TypeCatalog_DisplayNameFormat", resourceCulture);

		internal static string TypeCatalog_Empty => ResourceManager.GetString("TypeCatalog_Empty", resourceCulture);

		internal Strings()
		{
		}
	}
}
namespace Microsoft.Internal.Runtime.Serialization
{
	internal static class SerializationServices
	{
		public static T GetValue<T>(this SerializationInfo info, string name)
		{
			Assumes.NotNull(info, name);
			return (T)info.GetValue(name, typeof(T));
		}
	}
}
namespace Microsoft.Internal.Collections
{
	internal static class CollectionServices
	{
		private class CollectionOfObjectList : ICollection<object>, IEnumerable<object>, IEnumerable
		{
			private readonly IList _list;

			public int Count => Assumes.NotReachable<int>();

			public bool IsReadOnly => _list.IsReadOnly;

			public CollectionOfObjectList(IList list)
			{
				_list = list;
			}

			public void Add(object item)
			{
				_list.Add(item);
			}

			public void Clear()
			{
				_list.Clear();
			}

			public bool Contains(object item)
			{
				return Assumes.NotReachable<bool>();
			}

			public void CopyTo(object[] array, int arrayIndex)
			{
				Assumes.NotReachable<object>();
			}

			public bool Remove(object item)
			{
				return Assumes.NotReachable<bool>();
			}

			public IEnumerator<object> GetEnumerator()
			{
				return Assumes.NotReachable<IEnumerator<object>>();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return Assumes.NotReachable<IEnumerator>();
			}
		}

		private class CollectionOfObject<T> : ICollection<object>, IEnumerable<object>, IEnumerable
		{
			private readonly ICollection<T> _collectionOfT;

			public int Count => Assumes.NotReachable<int>();

			public bool IsReadOnly => _collectionOfT.IsReadOnly;

			public CollectionOfObject(object collectionOfT)
			{
				_collectionOfT = (ICollection<T>)collectionOfT;
			}

			public void Add(object item)
			{
				_collectionOfT.Add((T)item);
			}

			public void Clear()
			{
				_collectionOfT.Clear();
			}

			public bool Contains(object item)
			{
				return Assumes.NotReachable<bool>();
			}

			public void CopyTo(object[] array, int arrayIndex)
			{
				Assumes.NotReachable<object>();
			}

			public bool Remove(object item)
			{
				return Assumes.NotReachable<bool>();
			}

			public IEnumerator<object> GetEnumerator()
			{
				return Assumes.NotReachable<IEnumerator<object>>();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return Assumes.NotReachable<IEnumerator>();
			}
		}

		private static readonly Type StringType = typeof(string);

		private static readonly Type IEnumerableType = typeof(IEnumerable);

		private static readonly Type IEnumerableOfTType = typeof(IEnumerable<>);

		private static readonly Type ICollectionOfTType = typeof(ICollection<>);

		public static ICollection<object> GetCollectionWrapper(Type itemType, object collectionObject)
		{
			Assumes.NotNull(itemType, collectionObject);
			Type underlyingSystemType = itemType.UnderlyingSystemType;
			if (underlyingSystemType == typeof(object))
			{
				return (ICollection<object>)collectionObject;
			}
			if (typeof(IList).IsAssignableFrom(collectionObject.GetType()))
			{
				return new CollectionOfObjectList((IList)collectionObject);
			}
			return (ICollection<object>)Activator.CreateInstance(typeof(CollectionOfObject<>).MakeGenericType(underlyingSystemType), collectionObject);
		}

		public static bool IsEnumerableOfT(Type type)
		{
			if (type.IsGenericType && type.GetGenericTypeDefinition().UnderlyingSystemType == IEnumerableOfTType)
			{
				return true;
			}
			return false;
		}

		public static Type GetEnumerableElementType(Type type)
		{
			if (type.UnderlyingSystemType == StringType || !IEnumerableType.IsAssignableFrom(type))
			{
				return null;
			}
			if (ReflectionServices.TryGetGenericInterfaceType(type, IEnumerableOfTType, out var targetClosedInterfaceType))
			{
				return targetClosedInterfaceType.GetGenericArguments()[0];
			}
			return null;
		}

		public static Type GetCollectionElementType(Type type)
		{
			if (ReflectionServices.TryGetGenericInterfaceType(type, ICollectionOfTType, out var targetClosedInterfaceType))
			{
				return targetClosedInterfaceType.GetGenericArguments()[0];
			}
			return null;
		}

		public static ReadOnlyCollection<T> ToReadOnlyCollection<T>(this IEnumerable<T> source)
		{
			Assumes.NotNull(source);
			return new ReadOnlyCollection<T>(source.AsArray());
		}

		public static IEnumerable<T> ConcatAllowingNull<T>(this IEnumerable<T> source, IEnumerable<T> second)
		{
			if (second == null || !second.FastAny())
			{
				return source;
			}
			if (source == null || !source.FastAny())
			{
				return second;
			}
			return source.Concat(second);
		}

		public static ICollection<T> ConcatAllowingNull<T>(this ICollection<T> source, ICollection<T> second)
		{
			if (second == null || second.Count == 0)
			{
				return source;
			}
			if (source == null || source.Count == 0)
			{
				return second;
			}
			List<T> list = new List<T>(source);
			list.AddRange(second);
			return list;
		}

		public static List<T> FastAppendToListAllowNulls<T>(this List<T> source, IEnumerable<T> second)
		{
			if (second == null)
			{
				return source;
			}
			if (source == null || source.Count == 0)
			{
				return second.AsList();
			}
			if (second is List<T> list)
			{
				if (list.Count == 0)
				{
					return source;
				}
				if (list.Count == 1)
				{
					source.Add(list[0]);
					return source;
				}
			}
			source.AddRange(second);
			return source;
		}

		public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
		{
			foreach (T item in source)
			{
				action(item);
			}
		}

		public static EnumerableCardinality GetCardinality<T>(this IEnumerable<T> source)
		{
			Assumes.NotNull(source);
			if (source is ICollection collection)
			{
				return collection.Count switch
				{
					0 => EnumerableCardinality.Zero, 
					1 => EnumerableCardinality.One, 
					_ => EnumerableCardinality.TwoOrMore, 
				};
			}
			using IEnumerator<T> enumerator = source.GetEnumerator();
			if (!enumerator.MoveNext())
			{
				return EnumerableCardinality.Zero;
			}
			if (!enumerator.MoveNext())
			{
				return EnumerableCardinality.One;
			}
			return EnumerableCardinality.TwoOrMore;
		}

		public static bool FastAny<T>(this IEnumerable<T> source)
		{
			if (source is ICollection collection)
			{
				return collection.Count > 0;
			}
			return source.Any();
		}

		public static Stack<T> Copy<T>(this Stack<T> stack)
		{
			Assumes.NotNull(stack);
			return new Stack<T>(stack.Reverse());
		}

		public static T[] AsArray<T>(this IEnumerable<T> enumerable)
		{
			if (enumerable is T[] result)
			{
				return result;
			}
			return enumerable.ToArray();
		}

		public static List<T> AsList<T>(this IEnumerable<T> enumerable)
		{
			if (enumerable is List<T> result)
			{
				return result;
			}
			return enumerable.ToList();
		}

		public static bool IsArrayEqual<T>(this T[] thisArray, T[] thatArray)
		{
			if (thisArray.Length != thatArray.Length)
			{
				return false;
			}
			for (int i = 0; i < thisArray.Length; i++)
			{
				if (!thisArray[i].Equals(thatArray[i]))
				{
					return false;
				}
			}
			return true;
		}

		public static bool IsCollectionEqual<T>(this IList<T> thisList, IList<T> thatList)
		{
			if (thisList.Count != thatList.Count)
			{
				return false;
			}
			for (int i = 0; i < thisList.Count; i++)
			{
				if (!thisList[i].Equals(thatList[i]))
				{
					return false;
				}
			}
			return true;
		}
	}
	internal enum EnumerableCardinality
	{
		Zero,
		One,
		TwoOrMore
	}
	internal class WeakReferenceCollection<T> where T : class
	{
		private readonly List<WeakReference> _items = new List<WeakReference>();

		public void Add(T item)
		{
			if (_items.Capacity == _items.Count)
			{
				CleanupDeadReferences();
			}
			_items.Add(new WeakReference(item));
		}

		public void Remove(T item)
		{
			int num = IndexOf(item);
			if (num != -1)
			{
				_items.RemoveAt(num);
			}
		}

		public bool Contains(T item)
		{
			return IndexOf(item) >= 0;
		}

		public void Clear()
		{
			_items.Clear();
		}

		private int IndexOf(T item)
		{
			int count = _items.Count;
			for (int i = 0; i < count; i++)
			{
				if (_items[i].Target == item)
				{
					return i;
				}
			}
			return -1;
		}

		private void CleanupDeadReferences()
		{
			_items.RemoveAll((WeakReference w) => !w.IsAlive);
		}

		public List<T> AliveItemsToList()
		{
			List<T> list = new List<T>();
			foreach (WeakReference item2 in _items)
			{
				if (item2.Target is T item)
				{
					list.Add(item);
				}
			}
			return list;
		}
	}
}
namespace System
{
	[Serializable]
	public class Lazy<T, TMetadata> : Lazy<T>
	{
		private TMetadata _metadata;

		public TMetadata Metadata => _metadata;

		public Lazy(Func<T> valueFactory, TMetadata metadata)
			: base(valueFactory)
		{
			_metadata = metadata;
		}

		public Lazy(TMetadata metadata)
		{
			_metadata = metadata;
		}

		public Lazy(TMetadata metadata, bool isThreadSafe)
			: base(isThreadSafe)
		{
			_metadata = metadata;
		}

		public Lazy(Func<T> valueFactory, TMetadata metadata, bool isThreadSafe)
			: base(valueFactory, isThreadSafe)
		{
			_metadata = metadata;
		}

		public Lazy(TMetadata metadata, LazyThreadSafetyMode mode)
			: base(mode)
		{
			_metadata = metadata;
		}

		public Lazy(Func<T> valueFactory, TMetadata metadata, LazyThreadSafetyMode mode)
			: base(valueFactory, mode)
		{
			_metadata = metadata;
		}
	}
}
namespace System.ComponentModel
{
	[Conditional("NOT_FEATURE_LEGACYCOMPONENTMODEL")]
	internal sealed class LocalizableAttribute : Attribute
	{
		public LocalizableAttribute(bool isLocalizable)
		{
		}
	}
}
namespace System.ComponentModel.Composition
{
	public static class AttributedModelServices
	{
		public static TMetadataView GetMetadataView<TMetadataView>(IDictionary<string, object> metadata)
		{
			Requires.NotNull(metadata, "metadata");
			return MetadataViewProvider.GetMetadataView<TMetadataView>(metadata);
		}

		public static ComposablePart CreatePart(object attributedPart)
		{
			Requires.NotNull(attributedPart, "attributedPart");
			return AttributedModelDiscovery.CreatePart(attributedPart);
		}

		public static ComposablePart CreatePart(object attributedPart, ReflectionContext reflectionContext)
		{
			Requires.NotNull(attributedPart, "attributedPart");
			Requires.NotNull(reflectionContext, "reflectionContext");
			return AttributedModelDiscovery.CreatePart(attributedPart, reflectionContext);
		}

		public static ComposablePart CreatePart(ComposablePartDefinition partDefinition, object attributedPart)
		{
			Requires.NotNull(partDefinition, "partDefinition");
			Requires.NotNull(attributedPart, "attributedPart");
			return AttributedModelDiscovery.CreatePart((partDefinition as ReflectionComposablePartDefinition) ?? throw ExceptionBuilder.CreateReflectionModelInvalidPartDefinition("partDefinition", partDefinition.GetType()), attributedPart);
		}

		public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin)
		{
			Requires.NotNull(type, "type");
			return CreatePartDefinition(type, origin, ensureIsDiscoverable: false);
		}

		public static ComposablePartDefinition CreatePartDefinition(Type type, ICompositionElement origin, bool ensureIsDiscoverable)
		{
			Requires.NotNull(type, "type");
			if (ensureIsDiscoverable)
			{
				return AttributedModelDiscovery.CreatePartDefinitionIfDiscoverable(type, origin);
			}
			return AttributedModelDiscovery.CreatePartDefinition(type, null, ignoreConstructorImports: false, origin);
		}

		public static string GetTypeIdentity(Type type)
		{
			Requires.NotNull(type, "type");
			return ContractNameServices.GetTypeIdentity(type);
		}

		public static string GetTypeIdentity(MethodInfo method)
		{
			Requires.NotNull(method, "method");
			return ContractNameServices.GetTypeIdentityFromMethod(method);
		}

		public static string GetContractName(Type type)
		{
			Requires.NotNull(type, "type");
			return GetTypeIdentity(type);
		}

		public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, T exportedValue)
		{
			Requires.NotNull(batch, "batch");
			string contractName = GetContractName(typeof(T));
			return batch.AddExportedValue(contractName, exportedValue);
		}

		public static void ComposeExportedValue<T>(this CompositionContainer container, T exportedValue)
		{
			Requires.NotNull(container, "container");
			CompositionBatch batch = new CompositionBatch();
			batch.AddExportedValue(exportedValue);
			container.Compose(batch);
		}

		public static ComposablePart AddExportedValue<T>(this CompositionBatch batch, string contractName, T exportedValue)
		{
			Requires.NotNull(batch, "batch");
			string typeIdentity = GetTypeIdentity(typeof(T));
			IDictionary<string, object> dictionary = new Dictionary<string, object>();
			dictionary.Add("ExportTypeIdentity", typeIdentity);
			return batch.AddExport(new Export(contractName, dictionary, () => exportedValue));
		}

		public static void ComposeExportedValue<T>(this CompositionContainer container, string contractName, T exportedValue)
		{
			Requires.NotNull(container, "container");
			CompositionBatch batch = new CompositionBatch();
			batch.AddExportedValue(contractName, exportedValue);
			container.Compose(batch);
		}

		public static ComposablePart AddPart(this CompositionBatch batch, object attributedPart)
		{
			Requires.NotNull(batch, "batch");
			Requires.NotNull(attributedPart, "attributedPart");
			ComposablePart composablePart = CreatePart(attributedPart);
			batch.AddPart(composablePart);
			return composablePart;
		}

		public static void ComposeParts(this CompositionContainer container, params object[] attributedParts)
		{
			Requires.NotNull(container, "container");
			Requires.NotNullOrNullElements(attributedParts, "attributedParts");
			CompositionBatch batch = new CompositionBatch(attributedParts.Select((object attributedPart) => CreatePart(attributedPart)).ToArray(), Enumerable.Empty<ComposablePart>());
			container.Compose(batch);
		}

		public static ComposablePart SatisfyImportsOnce(this ICompositionService compositionService, object attributedPart)
		{
			Requires.NotNull(compositionService, "compositionService");
			Requires.NotNull(attributedPart, "attributedPart");
			ComposablePart composablePart = CreatePart(attributedPart);
			compositionService.SatisfyImportsOnce(composablePart);
			return composablePart;
		}

		public static ComposablePart SatisfyImportsOnce(this ICompositionService compositionService, object attributedPart, ReflectionContext reflectionContext)
		{
			Requires.NotNull(compositionService, "compositionService");
			Requires.NotNull(attributedPart, "attributedPart");
			Requires.NotNull(reflectionContext, "reflectionContext");
			ComposablePart composablePart = CreatePart(attributedPart, reflectionContext);
			compositionService.SatisfyImportsOnce(composablePart);
			return composablePart;
		}

		public static bool Exports(this ComposablePartDefinition part, Type contractType)
		{
			Requires.NotNull(part, "part");
			Requires.NotNull(contractType, "contractType");
			return part.Exports(GetContractName(contractType));
		}

		public static bool Exports<T>(this ComposablePartDefinition part)
		{
			Requires.NotNull(part, "part");
			return part.Exports(typeof(T));
		}

		public static bool Imports(this ComposablePartDefinition part, Type contractType)
		{
			Requires.NotNull(part, "part");
			Requires.NotNull(contractType, "contractType");
			return part.Imports(GetContractName(contractType));
		}

		public static bool Imports<T>(this ComposablePartDefinition part)
		{
			Requires.NotNull(part, "part");
			return part.Imports(typeof(T));
		}

		public static bool Imports(this ComposablePartDefinition part, Type contractType, ImportCardinality importCardinality)
		{
			Requires.NotNull(part, "part");
			Requires.NotNull(contractType, "contractType");
			return part.Imports(GetContractName(contractType), importCardinality);
		}

		public static bool Imports<T>(this ComposablePartDefinition part, ImportCardinality importCardinality)
		{
			Requires.NotNull(part, "part");
			return part.Imports(typeof(T), importCardinality);
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = true)]
	public class CatalogReflectionContextAttribute : Attribute
	{
		private Type _reflectionContextType;

		public CatalogReflectionContextAttribute(Type reflectionContextType)
		{
			Requires.NotNull(reflectionContextType, "reflectionContextType");
			_reflectionContextType = reflectionContextType;
		}

		public ReflectionContext CreateReflectionContext()
		{
			Assumes.NotNull(_reflectionContextType);
			ReflectionContext reflectionContext = null;
			try
			{
				return (ReflectionContext)Activator.CreateInstance(_reflectionContextType);
			}
			catch (InvalidCastException innerException)
			{
				throw new InvalidOperationException(Strings.ReflectionContext_Type_Required, innerException);
			}
			catch (MissingMethodException inner)
			{
				throw new MissingMethodException(Strings.ReflectionContext_Requires_DefaultConstructor, inner);
			}
		}
	}
	[Serializable]
	public class ChangeRejectedException : CompositionException
	{
		public override string Message => string.Format(CultureInfo.CurrentCulture, Strings.CompositionException_ChangesRejected, base.Message);

		public ChangeRejectedException()
			: this(null, null)
		{
		}

		public ChangeRejectedException(string message)
			: this(message, null)
		{
		}

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

		public ChangeRejectedException(IEnumerable<CompositionError> errors)
			: base(null, null, errors)
		{
		}
	}
	[Serializable]
	public class CompositionContractMismatchException : Exception
	{
		public CompositionContractMismatchException()
			: this(null, null)
		{
		}

		public CompositionContractMismatchException(string message)
			: this(message, null)
		{
		}

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

		[SecuritySafeCritical]
		protected CompositionContractMismatchException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	[Serializable]
	[DebuggerTypeProxy(typeof(CompositionErrorDebuggerProxy))]
	public class CompositionError
	{
		private readonly CompositionErrorId _id;

		private readonly string _description;

		private readonly Exception _exception;

		private readonly ICompositionElement _element;

		public ICompositionElement Element => _element;

		public string Description => _description;

		public Exception Exception => _exception;

		internal CompositionErrorId Id => _id;

		internal Exception InnerException => Exception;

		public CompositionError(string message)
			: this(CompositionErrorId.Unknown, message, null, null)
		{
		}

		public CompositionError(string message, ICompositionElement element)
			: this(CompositionErrorId.Unknown, message, element, null)
		{
		}

		public CompositionError(string message, Exception exception)
			: this(CompositionErrorId.Unknown, message, null, exception)
		{
		}

		public CompositionError(string message, ICompositionElement element, Exception exception)
			: this(CompositionErrorId.Unknown, message, element, exception)
		{
		}

		internal CompositionError(CompositionErrorId id, string description, ICompositionElement element, Exception exception)
		{
			_id = id;
			_description = description ?? string.Empty;
			_element = element;
			_exception = exception;
		}

		public override string ToString()
		{
			return Description;
		}

		internal static CompositionError Create(CompositionErrorId id, string format, params object[] parameters)
		{
			return Create(id, null, null, format, parameters);
		}

		internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, string format, params object[] parameters)
		{
			return Create(id, element, null, format, parameters);
		}

		internal static CompositionError Create(CompositionErrorId id, ICompositionElement element, Exception exception, string format, params object[] parameters)
		{
			return new CompositionError(id, string.Format(CultureInfo.CurrentCulture, format, parameters), element, exception);
		}
	}
	internal class CompositionErrorDebuggerProxy
	{
		private readonly CompositionError _error;

		public string Description => _error.Description;

		public Exception Exception => _error.Exception;

		public ICompositionElement Element => _error.Element;

		public CompositionErrorDebuggerProxy(CompositionError error)
		{
			Requires.NotNull(error, "error");
			_error = error;
		}
	}
	internal enum CompositionErrorId
	{
		Unknown,
		InvalidExportMetadata,
		ImportNotSetOnPart,
		ImportEngine_ComposeTookTooManyIterations,
		ImportEngine_ImportCardinalityMismatch,
		ImportEngine_PartCycle,
		ImportEngine_PartCannotSetImport,
		ImportEngine_PartCannotGetExportedValue,
		ImportEngine_PartCannotActivate,
		ImportEngine_PreventedByExistingImport,
		ImportEngine_InvalidStateForRecomposition,
		ReflectionModel_ImportThrewException,
		ReflectionModel_ImportNotAssignableFromExport,
		ReflectionModel_ImportCollectionNull,
		ReflectionModel_ImportCollectionNotWritable,
		ReflectionModel_ImportCollectionConstructionThrewException,
		ReflectionModel_ImportCollectionGetThrewException,
		ReflectionModel_ImportCollectionIsReadOnlyThrewException,
		ReflectionModel_ImportCollectionClearThrewException,
		ReflectionModel_ImportCollectionAddThrewException,
		ReflectionModel_ImportManyOnParameterCanOnlyBeAssigned
	}
	[Serializable]
	[DebuggerDisplay("{Message}")]
	[DebuggerTypeProxy(typeof(CompositionExceptionDebuggerProxy))]
	public class CompositionException : Exception
	{
		[Serializable]
		private struct CompositionExceptionData : ISafeSerializationData
		{
			public CompositionError[] _errors;

			void ISafeSerializationData.CompleteDeserialization(object obj)
			{
				(obj as CompositionException)._errors = new ReadOnlyCollection<CompositionError>(_errors);
			}
		}

		private struct VisitContext
		{
			public Stack<CompositionError> Path;

			public Action<Stack<CompositionError>> LeafVisitor;
		}

		private const string ErrorsKey = "Errors";

		private ReadOnlyCollection<CompositionError> _errors;

		public ReadOnlyCollection<CompositionError> Errors => _errors;

		public override string Message
		{
			get
			{
				if (Errors.Count == 0)
				{
					return base.Message;
				}
				return BuildDefaultMessage();
			}
		}

		public ReadOnlyCollection<Exception> RootCauses
		{
			get
			{
				//IL_0007: Expected O, but got I4
				ThrowStub.ThrowNotSupportedException();
				return (ReadOnlyCollection<Exception>)0;
			}
		}

		public CompositionException()
			: this(null, null, null)
		{
		}

		public CompositionException(string message)
			: this(message, null, null)
		{
		}

		public CompositionException(string message, Exception innerException)
			: this(message, innerException, null)
		{
		}

		internal CompositionException(CompositionError error)
			: this(new CompositionError[1] { error })
		{
		}

		public CompositionException(IEnumerable<CompositionError> errors)
			: this(null, null, errors)
		{
		}

		internal CompositionException(string message, Exception innerException, IEnumerable<CompositionError> errors)
			: base(message, innerException)
		{
			Requires.NullOrNotNullElements(errors, "errors");
			base.SerializeObjectState += delegate(object exception, SafeSerializationEventArgs eventArgs)
			{
				CompositionExceptionData compositionExceptionData = default(CompositionExceptionData);
				if (_errors != null)
				{
					compositionExceptionData._errors = _errors.Select((CompositionError error) => new CompositionError(error.Id, error.Description, error.Element.ToSerializableElement(), error.Exception)).ToArray();
				}
				else
				{
					compositionExceptionData._errors = new CompositionError[0];
				}
				eventArgs.AddSerializedState(compositionExceptionData);
			};
			_errors = new ReadOnlyCollection<CompositionError>((errors == null) ? ((IList<CompositionError>)new CompositionError[0]) : ((IList<CompositionError>)errors.ToArray()));
		}

		private string BuildDefaultMessage()
		{
			IEnumerable<IEnumerable<CompositionError>> enumerable = CalculatePaths(this);
			StringBuilder stringBuilder = new StringBuilder();
			WriteHeader(stringBuilder, Errors.Count, enumerable.Count());
			WritePaths(stringBuilder, enumerable);
			return stringBuilder.ToString();
		}

		private static void WriteHeader(StringBuilder writer, int errorsCount, int pathCount)
		{
			if (errorsCount > 1 && pathCount > 1)
			{
				writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_MultipleErrorsWithMultiplePaths, pathCount);
			}
			else if (errorsCount == 1 && pathCount > 1)
			{
				writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_SingleErrorWithMultiplePaths, pathCount);
			}
			else
			{
				Assumes.IsTrue(errorsCount == 1);
				Assumes.IsTrue(pathCount == 1);
				writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_SingleErrorWithSinglePath, pathCount);
			}
			writer.Append(' ');
			writer.AppendLine(Strings.CompositionException_ReviewErrorProperty);
		}

		private static void WritePaths(StringBuilder writer, IEnumerable<IEnumerable<CompositionError>> paths)
		{
			int num = 0;
			foreach (IEnumerable<CompositionError> path in paths)
			{
				num++;
				WritePath(writer, path, num);
			}
		}

		private static void WritePath(StringBuilder writer, IEnumerable<CompositionError> path, int ordinal)
		{
			writer.AppendLine();
			writer.Append(ordinal.ToString(CultureInfo.CurrentCulture));
			writer.Append(Strings.CompositionException_PathsCountSeparator);
			writer.Append(' ');
			WriteError(writer, path.First());
			foreach (CompositionError item in path.Skip(1))
			{
				writer.AppendLine();
				writer.Append(Strings.CompositionException_ErrorPrefix);
				writer.Append(' ');
				WriteError(writer, item);
			}
		}

		private static void WriteError(StringBuilder writer, CompositionError error)
		{
			writer.AppendLine(error.Description);
			if (error.Element != null)
			{
				WriteElementGraph(writer, error.Element);
			}
		}

		private static void WriteElementGraph(StringBuilder writer, ICompositionElement element)
		{
			writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_ElementPrefix, element.DisplayName);
			while ((element = element.Origin) != null)
			{
				writer.AppendFormat(CultureInfo.CurrentCulture, Strings.CompositionException_OriginFormat, Strings.CompositionException_OriginSeparator, element.DisplayName);
			}
			writer.AppendLine();
		}

		private static IEnumerable<IEnumerable<CompositionError>> CalculatePaths(CompositionException exception)
		{
			List<IEnumerable<CompositionError>> paths = new List<IEnumerable<CompositionError>>();
			VisitContext context = default(VisitContext);
			context.Path = new Stack<CompositionError>();
			context.LeafVisitor = delegate(Stack<CompositionError> path)
			{
				paths.Add(path.Copy());
			};
			VisitCompositionException(exception, context);
			return paths;
		}

		private static void VisitCompositionException(CompositionException exception, VisitContext context)
		{
			foreach (CompositionError error in exception.Errors)
			{
				VisitError(error, context);
			}
			if (exception.InnerException != null)
			{
				VisitException(exception.InnerException, context);
			}
		}

		private static void VisitError(CompositionError error, VisitContext context)
		{
			context.Path.Push(error);
			if (error.Exception == null)
			{
				context.LeafVisitor(context.Path);
			}
			else
			{
				VisitException(error.Exception, context);
			}
			context.Path.Pop();
		}

		private static void VisitException(Exception exception, VisitContext context)
		{
			if (exception is CompositionException exception2)
			{
				VisitCompositionException(exception2, context);
			}
			else
			{
				VisitError(new CompositionError(exception.Message, exception.InnerException), context);
			}
		}
	}
	internal class CompositionExceptionDebuggerProxy
	{
		private readonly CompositionException _exception;

		public ReadOnlyCollection<Exception> Exceptions
		{
			get
			{
				List<Exception> list = new List<Exception>();
				foreach (CompositionError error in _exception.Errors)
				{
					if (error.Exception != null)
					{
						list.Add(error.Exception);
					}
				}
				return list.ToReadOnlyCollection();
			}
		}

		public string Message => _exception.Message;

		public ReadOnlyCollection<Exception> RootCauses
		{
			get
			{
				List<Exception> list = new List<Exception>();
				foreach (CompositionError error in _exception.Errors)
				{
					if (error.Exception == null)
					{
						continue;
					}
					if (error.Exception is CompositionException exception)
					{
						CompositionExceptionDebuggerProxy compositionExceptionDebuggerProxy = new CompositionExceptionDebuggerProxy(exception);
						if (compositionExceptionDebuggerProxy.RootCauses.Count > 0)
						{
							list.AddRange(compositionExceptionDebuggerProxy.RootCauses);
							continue;
						}
					}
					list.Add(error.Exception);
				}
				return list.ToReadOnlyCollection();
			}
		}

		public CompositionExceptionDebuggerProxy(CompositionException exception)
		{
			Requires.NotNull(exception, "exception");
			_exception = exception;
		}
	}
	internal struct CompositionResult
	{
		public static readonly CompositionResult SucceededResult;

		private readonly IEnumerable<CompositionError> _errors;

		public bool Succeeded
		{
			get
			{
				if (_errors != null)
				{
					return !_errors.FastAny();
				}
				return true;
			}
		}

		public IEnumerable<CompositionError> Errors => _errors ?? Enumerable.Empty<CompositionError>();

		public CompositionResult(params CompositionError[] errors)
			: this((IEnumerable<CompositionError>)errors)
		{
		}

		public CompositionResult(IEnumerable<CompositionError> errors)
		{
			_errors = errors;
		}

		public CompositionResult MergeResult(CompositionResult result)
		{
			if (Succeeded)
			{
				return result;
			}
			if (result.Succeeded)
			{
				return this;
			}
			return MergeErrors(result._errors);
		}

		public CompositionResult MergeError(CompositionError error)
		{
			return MergeErrors(new CompositionError[1] { error });
		}

		public CompositionResult MergeErrors(IEnumerable<CompositionError> errors)
		{
			return new CompositionResult(_errors.ConcatAllowingNull(errors));
		}

		public CompositionResult<T> ToResult<T>(T value)
		{
			return new CompositionResult<T>(value, _errors);
		}

		public void ThrowOnErrors()
		{
			ThrowOnErrors(null);
		}

		public void ThrowOnErrors(AtomicComposition atomicComposition)
		{
			if (!Succeeded)
			{
				if (atomicComposition == null)
				{
					throw new CompositionException(_errors);
				}
				throw new ChangeRejectedException(_errors);
			}
		}
	}
	internal struct CompositionResult<T>
	{
		private readonly IEnumerable<CompositionError> _errors;

		private readonly T _value;

		public bool Succeeded
		{
			get
			{
				if (_errors != null)
				{
					return !_errors.FastAny();
				}
				return true;
			}
		}

		public IEnumerable<CompositionError> Errors => _errors ?? Enumerable.Empty<CompositionError>();

		public T Value
		{
			get
			{
				ThrowOnErrors();
				return _value;
			}
		}

		public CompositionResult(T value)
			: this(value, null)
		{
		}

		public CompositionResult(params CompositionError[] errors)
			: this(default(T), errors)
		{
		}

		public CompositionResult(IEnumerable<CompositionError> errors)
			: this(default(T), errors)
		{
		}

		internal CompositionResult(T value, IEnumerable<CompositionError> errors)
		{
			_errors = errors;
			_value = value;
		}

		internal CompositionResult<TValue> ToResult<TValue>()
		{
			return new CompositionResult<TValue>(_errors);
		}

		internal CompositionResult ToResult()
		{
			return new CompositionResult(_errors);
		}

		private void ThrowOnErrors()
		{
			if (!Succeeded)
			{
				throw new CompositionException(_errors);
			}
		}
	}
	internal static class ConstraintServices
	{
		private static readonly PropertyInfo _exportDefinitionContractNameProperty = typeof(ExportDefinition).GetProperty("ContractName");

		private static readonly PropertyInfo _exportDefinitionMetadataProperty = typeof(ExportDefinition).GetProperty("Metadata");

		private static readonly MethodInfo _metadataContainsKeyMethod = typeof(IDictionary<string, object>).GetMethod("ContainsKey");

		private static readonly MethodInfo _metadataItemMethod = typeof(IDictionary<string, object>).GetMethod("get_Item");

		private static readonly MethodInfo _metadataEqualsMethod = typeof(object).GetMethod("Equals", new Type[1] { typeof(object) });

		private static readonly MethodInfo _typeIsInstanceOfTypeMethod = typeof(Type).GetMethod("IsInstanceOfType");

		public static Expression<Func<ExportDefinition, bool>> CreateConstraint(string contractName, string requiredTypeIdentity, IEnumerable<KeyValuePair<string, Type>> requiredMetadata, CreationPolicy requiredCreationPolicy)
		{
			ParameterExpression parameterExpression = Expression.Parameter(typeof(ExportDefinition), "exportDefinition");
			Expression expression = CreateContractConstraintBody(contractName, parameterExpression);
			if (!string.IsNullOrEmpty(requiredTypeIdentity))
			{
				Expression right = CreateTypeIdentityContraint(requiredTypeIdentity, parameterExpression);
				expression = Expression.AndAlso(expression, right);
			}
			if (requiredMetadata != null)
			{
				Expression expression2 = CreateMetadataConstraintBody(requiredMetadata, parameterExpression);
				if (expression2 != null)
				{
					expression = Expression.AndAlso(expression, expression2);
				}
			}
			if (requiredCreationPolicy != 0)
			{
				Expression right2 = CreateCreationPolicyContraint(requiredCreationPolicy, parameterExpression);
				expression = Expression.AndAlso(expression, right2);
			}
			return Expression.Lambda<Func<ExportDefinition, bool>>(expression, new ParameterExpression[1] { parameterExpression });
		}

		private static Expression CreateContractConstraintBody(string contractName, ParameterExpression parameter)
		{
			Assumes.NotNull(parameter);
			return Expression.Equal(Expression.Property(parameter, _exportDefinitionContractNameProperty), Expression.Constant(contractName ?? string.Empty, typeof(string)));
		}

		private static Expression CreateMetadataConstraintBody(IEnumerable<KeyValuePair<string, Type>> requiredMetadata, ParameterExpression parameter)
		{
			Assumes.NotNull(requiredMetadata);
			Assumes.NotNull(parameter);
			Expression expression = null;
			foreach (KeyValuePair<string, Type> requiredMetadatum in requiredMetadata)
			{
				Expression expression2 = CreateMetadataContainsKeyExpression(parameter, requiredMetadatum.Key);
				expression = ((expression != null) ? Expression.AndAlso(expression, expression2) : expression2);
				expression = Expression.AndAlso(expression, CreateMetadataOfTypeExpression(parameter, requiredMetadatum.Key, requiredMetadatum.Value));
			}
			return expression;
		}

		private static Expression CreateCreationPolicyContraint(CreationPolicy policy, ParameterExpression parameter)
		{
			Assumes.IsTrue(policy != CreationPolicy.Any);
			Assumes.NotNull(parameter);
			return Expression.MakeBinary(ExpressionType.OrElse, Expression.MakeBinary(ExpressionType.OrElse, Expression.Not(CreateMetadataContainsKeyExpression(parameter, "System.ComponentModel.Composition.CreationPolicy")), CreateMetadataValueEqualsExpression(parameter, CreationPolicy.Any, "System.ComponentModel.Composition.CreationPolicy")), CreateMetadataValueEqualsExpression(parameter, policy, "System.ComponentModel.Composition.CreationPolicy"));
		}

		private static Expression CreateTypeIdentityContraint(string requiredTypeIdentity, ParameterExpression parameter)
		{
			Assumes.NotNull(requiredTypeIdentity);
			Assumes.NotNull(parameter);
			return Expression.MakeBinary(ExpressionType.AndAlso, CreateMetadataContainsKeyExpression(parameter, "ExportTypeIdentity"), CreateMetadataValueEqualsExpression(parameter, requiredTypeIdentity, "ExportTypeIdentity"));
		}

		private static Expression CreateMetadataContainsKeyExpression(ParameterExpression parameter, string constantKey)
		{
			Assumes.NotNull(parameter, constantKey);
			return Expression.Call(Expression.Property(parameter, _exportDefinitionMetadataProperty), _metadataContainsKeyMethod, Expression.Constant(constantKey));
		}

		private static Expression CreateMetadataOfTypeExpression(ParameterExpression parameter, string constantKey, Type constantType)
		{
			Assumes.NotNull(parameter, constantKey);
			Assumes.NotNull(parameter, constantType);
			return Expression.Call(Expression.Constant(constantType, typeof(Type)), _typeIsInstanceOfTypeMethod, Expression.Call(Expression.Property(parameter, _exportDefinitionMetadataProperty), _metadataItemMethod, Expression.Constant(constantKey)));
		}

		private static Expression CreateMetadataValueEqualsExpression(ParameterExpression parameter, object constantValue, string metadataName)
		{
			Assumes.NotNull(parameter, constantValue);
			return Expression.Call(Expression.Constant(constantValue), _metadataEqualsMethod, Expression.Call(Expression.Property(parameter, _exportDefinitionMetadataProperty), _metadataItemMethod, Expression.Constant(metadataName)));
		}

		public static Expression<Func<ExportDefinition, bool>> CreatePartCreatorConstraint(Expression<Func<ExportDefinition, bool>> baseConstraint, ImportDefinition productImportDefinition)
		{
			ParameterExpression parameterExpression = baseConstraint.Parameters[0];
			Expression instance = Expression.Property(parameterExpression, _exportDefinitionMetadataProperty);
			Expression left = Expression.Call(instance, _metadataContainsKeyMethod, Expression.Constant("ProductDefinition"));
			Expression expression = Expression.Call(instance, _metadataItemMethod, Expression.Constant("ProductDefinition"));
			Expression right = Expression.Invoke(productImportDefinition.Constraint, Expression.Convert(expression, typeof(ExportDefinition)));
			return Expression.Lambda<Func<ExportDefinition, bool>>(Expression.AndAlso(baseConstraint.Body, Expression.AndAlso(left, right)), new ParameterExpression[1] { parameterExpression });
		}
	}
	internal static class ContractNameServices
	{
		private const char NamespaceSeparator = '.';

		private const char ArrayOpeningBracket = '[';

		private const char ArrayClosingBracket = ']';

		private const char ArraySeparator = ',';

		private const char PointerSymbol = '*';

		private const char ReferenceSymbol = '&';

		private const char GenericArityBackQuote = '`';

		private const char NestedClassSeparator = '+';

		private const char ContractNameGenericOpeningBracket = '(';

		private const char ContractNameGenericClosingBracket = ')';

		private const char ContractNameGenericArgumentSeparator = ',';

		private const char CustomModifiersSeparator = ' ';

		private const char GenericFormatOpeningBracket = '{';

		private const char GenericFormatClosingBracket = '}';

		[ThreadStatic]
		private static Dictionary<Type, string> typeIdentityCache;

		private static Dictionary<Type, string> TypeIdentityCache
		{
			get
			{
				Dictionary<Type, string> result = typeIdentityCache ?? new Dictionary<Type, string>();
				typeIdentityCache = result;
				return result;
			}
		}

		internal static string GetTypeIdentity(Type type)
		{
			return GetTypeIdentity(type, formatGenericName: true);
		}

		internal static string GetTypeIdentity(Type type, bool formatGenericName)
		{
			Assumes.NotNull(type);
			string value = null;
			if (!TypeIdentityCache.TryGetValue(type, out value))
			{
				if (!type.IsAbstract && type.IsSubclassOf(typeof(Delegate)))
				{
					value = GetTypeIdentityFromMethod(type.GetMethod("Invoke"));
				}
				else if (type.IsGenericParameter)
				{
					StringBuilder stringBuilder = new StringBuilder();
					WriteTypeArgument(stringBuilder, isDefinition: false, type, formatGenericName);
					stringBuilder.Remove(stringBuilder.Length - 1, 1);
					value = stringBuilder.ToString();
				}
				else
				{
					StringBuilder stringBuilder2 = new StringBuilder();
					WriteTypeWithNamespace(stringBuilder2, type, formatGenericName);
					value = stringBuilder2.ToString();
				}
				Assumes.IsTrue(!string.IsNullOrEmpty(value));
				TypeIdentityCache.Add(type, value);
			}
			return value;
		}

		internal static string GetTypeIdentityFromMethod(MethodInfo method)
		{
			return GetTypeIdentityFromMethod(method, formatGenericName: true);
		}

		internal static string GetTypeIdentityFromMethod(MethodInfo method, bool formatGenericName)
		{
			StringBuilder stringBuilder = new StringBuilder();
			WriteTypeWithNamespace(stringBuilder, method.ReturnType, formatGenericName);
			stringBuilder.Append("(");
			ParameterInfo[] parameters = method.GetParameters();
			for (int i = 0; i < parameters.Length; i++)
			{
				if (i != 0)
				{
					stringBuilder.Append(",");
				}
				WriteTypeWithNamespace(stringBuilder, parameters[i].ParameterType, formatGenericName);
			}
			stringBuilder.Append(")");
			return stringBuilder.ToString();
		}

		private static void WriteTypeWithNamespace(StringBuilder typeName, Type type, bool formatGenericName)
		{
			if (!string.IsNullOrEmpty(type.Namespace))
			{
				typeName.Append(type.Namespace);
				typeName.Append('.');
			}
			WriteType(typeName, type, formatGenericName);
		}

		private static void WriteType(StringBuilder typeName, Type type, bool formatGenericName)
		{
			if (type.IsGenericType)
			{
				Queue<Type> queue = new Queue<Type>(type.GetGenericArguments());
				WriteGenericType(typeName, type, type.IsGenericTypeDefinition, queue, formatGenericName);
				Assumes.IsTrue(queue.Count == 0, "Expecting genericTypeArguments queue to be empty.");
			}
			else
			{
				WriteNonGenericType(typeName, type, formatGenericName);
			}
		}

		private static void WriteNonGenericType(StringBuilder typeName, Type type, bool formatGenericName)
		{
			if (type.DeclaringType != null)
			{
				WriteType(typeName, type.DeclaringType, formatGenericName);
				typeName.Append('+');
			}
			if (type.IsArray)
			{
				WriteArrayType(typeName, type, formatGenericName);
			}
			else if (type.IsPointer)
			{
				WritePointerType(typeName, type, formatGenericName);
			}
			else if (type.IsByRef)
			{
				WriteByRefType(typeName, type, formatGenericName);
			}
			else
			{
				typeName.Append(type.Name);
			}
		}

		private static void WriteArrayType(StringBuilder typeName, Type type, bool formatGenericName)
		{
			Type type2 = FindArrayElementType(type);
			WriteType(typeName, type2, formatGenericName);
			Type type3 = type;
			do
			{
				WriteArrayTypeDimensions(typeName, type3);
			}
			while ((type3 = type3.GetElementType()) != null && type3.IsArray);
		}

		private static void WritePointerType(StringBuilder typeName, Type type, bool formatGenericName)
		{
			WriteType(typeName, type.GetElementType(), formatGenericName);
			typeName.Append('*');
		}

		private static void WriteByRefType(StringBuilder typeName, Type type, bool formatGenericName)
		{
			WriteType(typeName, type.GetElementType(), formatGenericName);
			typeName.Append('&');
		}

		private static void WriteArrayTypeDimensions(StringBuilder typeName, Type type)
		{
			typeName.Append('[');
			int arrayRank = type.GetArrayRank();
			for (int i = 1; i < arrayRank; i++)
			{
				typeName.Append(',');
			}
			typeName.Append(']');
		}

		private static void WriteGenericType(StringBuilder typeName, Type type, bool isDefinition, Queue<Type> genericTypeArguments, bool formatGenericName)
		{
			if (type.DeclaringType != null)
			{
				if (type.DeclaringType.IsGenericType)
				{
					WriteGenericType(typeName, type.DeclaringType, isDefinition, genericTypeArguments, formatGenericName);
				}
				else
				{
					WriteNonGenericType(typeName, type.DeclaringType, formatGenericName);
				}
				typeName.Append('+');
			}
			WriteGenericTypeName(typeName, type, isDefinition, genericTypeArguments, formatGenericName);
		}

		private static void WriteGenericTypeName(StringBuilder typeName, Type type, bool isDefinition, Queue<Type> genericTypeArguments, bool formatGenericName)
		{
			Assumes.IsTrue(type.IsGenericType, "Expecting type to be a generic type");
			int genericArity = GetGenericArity(type);
			string value = FindGenericTypeName(type.GetGenericTypeDefinition().Name);
			typeName.Append(value);
			WriteTypeArgumentsString(typeName, genericArity, isDefinition, genericTypeArguments, formatGenericName);
		}

		private static void WriteTypeArgumentsString(StringBuilder typeName, int argumentsCount, bool isDefinition, Queue<Type> genericTypeArguments, bool formatGenericName)
		{
			if (argumentsCount != 0)
			{
				typeName.Append('(');
				for (int i = 0; i < argumentsCount; i++)
				{
					Assumes.IsTrue(genericTypeArguments.Count > 0, "Expecting genericTypeArguments to contain at least one Type");
					Type genericTypeArgument = genericTypeArguments.Dequeue();
					WriteTypeArgument(typeName, isDefinition, genericTypeArgument, formatGenericName);
				}
				typeName.Remove(typeName.Length - 1, 1);
				typeName.Append(')');
			}
		}

		private static void WriteTypeArgument(StringBuilder typeName, bool isDefinition, Type genericTypeArgument, bool formatGenericName)
		{
			if (!isDefinition && !genericTypeArgument.IsGenericParameter)
			{
				WriteTypeWithNamespace(typeName, genericTypeArgument, formatGenericName);
			}
			if (formatGenericName && genericTypeArgument.IsGenericParameter)
			{
				typeName.Append('{');
				typeName.Append(genericTypeArgument.GenericParameterPosition);
				typeName.Append('}');
			}
			typeName.Append(',');
		}

		internal static void WriteCustomModifiers(StringBuilder typeName, string customKeyword, Type[] types, bool formatGenericName)
		{
			typeName.Append(' ');
			typeName.Append(customKeyword);
			Queue<Type> queue = new Queue<Type>(types);
			WriteTypeArgumentsString(typeName, types.Length, isDefinition: false, queue, formatGenericName);
			Assumes.IsTrue(queue.Count == 0, "Expecting genericTypeArguments queue to be empty.");
		}

		private static Type FindArrayElementType(Type type)
		{
			Type type2 = type;
			while ((type2 = type2.GetElementType()) != null && type2.IsArray)
			{
			}
			return type2;
		}

		private static string FindGenericTypeName(string genericName)
		{
			int num = genericName.IndexOf('`');
			if (num > -1)
			{
				genericName = genericName.Substring(0, num);
			}
			return genericName;
		}

		private static int GetGenericArity(Type type)
		{
			if (type.DeclaringType == null)
			{
				return type.GetGenericArguments().Length;
			}
			int num = type.DeclaringType.GetGenericArguments().Length;
			int num2 = type.GetGenericArguments().Length;
			Assumes.IsTrue(num2 >= num);
			return num2 - num;
		}
	}
	public enum CreationPolicy
	{
		Any,
		Shared,
		NonShared,
		NewScope
	}
	internal static class ErrorBuilder
	{
		public static CompositionError PreventedByExistingImport(ComposablePart part, ImportDefinition import)
		{
			return CompositionError.Create(CompositionErrorId.ImportEngine_PreventedByExistingImport, Strings.ImportEngine_PreventedByExistingImport, import.ToElement().DisplayName, part.ToElement().DisplayName);
		}

		public static CompositionError InvalidStateForRecompposition(ComposablePart part)
		{
			return CompositionError.Create(CompositionErrorId.ImportEngine_InvalidStateForRecomposition, Strings.ImportEngine_InvalidStateForRecomposition, part.ToElement().DisplayName);
		}

		public static CompositionError ComposeTookTooManyIterations(int maximumNumberOfCompositionIterations)
		{
			return CompositionError.Create(CompositionErrorId.ImportEngine_ComposeTookTooManyIterations, Strings.ImportEngine_ComposeTookTooManyIterations, maximumNumberOfCompositionIterations);
		}

		public static CompositionError CreateImportCardinalityMismatch(ImportCardinalityMismatchException exception, ImportDefinition definition)
		{
			Assumes.NotNull(exception, definition);
			return CompositionError.Create(CompositionErrorId.ImportEngine_ImportCardinalityMismatch, exception.Message, definition.ToElement(), null);
		}

		public static CompositionError CreatePartCannotActivate(ComposablePart part, Exception innerException)
		{
			Assumes.NotNull(part, innerException);
			ICompositionElement compositionElement = part.ToElement();
			return CompositionError.Create(CompositionErrorId.ImportEngine_PartCannotActivate, compositionElement, innerException, Strings.ImportEngine_PartCannotActivate, compositionElement.DisplayName);
		}

		public static CompositionError CreatePartCannotSetImport(ComposablePart part, ImportDefinition definition, Exception innerException)
		{
			Assumes.NotNull(part, definition, innerException);
			ICompositionElement compositionElement = definition.ToElement();
			return CompositionError.Create(CompositionErrorId.ImportEngine_PartCannotSetImport, compositionElement, innerException, Strings.ImportEngine_PartCannotSetImport, compositionElement.DisplayName, part.ToElement().DisplayName);
		}

		public static CompositionError CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException)
		{
			Assumes.NotNull(part, definition, innerException);
			ICompositionElement compositionElement = definition.ToElement();
			return CompositionError.Create(CompositionErrorId.ImportEngine_PartCannotGetExportedValue, compositionElement, innerException, Strings.ImportEngine_PartCannotGetExportedValue, compositionElement.DisplayName, part.ToElement().DisplayName);
		}

		public static CompositionError CreatePartCycle(ComposablePart part)
		{
			Assumes.NotNull(part);
			ICompositionElement compositionElement = part.ToElement();
			return CompositionError.Create(CompositionErrorId.ImportEngine_PartCycle, compositionElement, Strings.ImportEngine_PartCycle, compositionElement.DisplayName);
		}
	}
	internal static class ExceptionBuilder
	{
		public static Exception CreateDiscoveryException(string messageFormat, params string[] arguments)
		{
			return new InvalidOperationException(Format(messageFormat, arguments));
		}

		public static ArgumentException CreateContainsNullElement(string parameterName)
		{
			Assumes.NotNull(parameterName);
			return new ArgumentException(Format(Strings.Argument_NullElement, parameterName), parameterName);
		}

		public static ObjectDisposedException CreateObjectDisposed(object instance)
		{
			Assumes.NotNull(instance);
			return new ObjectDisposedException(instance.GetType().ToString());
		}

		public static NotImplementedException CreateNotOverriddenByDerived(string memberName)
		{
			Assumes.NotNullOrEmpty(memberName);
			return new NotImplementedException(Format(Strings.NotImplemented_NotOverriddenByDerived, memberName));
		}

		public static ArgumentException CreateExportDefinitionNotOnThisComposablePart(string parameterName)
		{
			Assumes.NotNullOrEmpty(parameterName);
			return new ArgumentException(Format(Strings.ExportDefinitionNotOnThisComposablePart, parameterName), parameterName);
		}

		public static ArgumentException CreateImportDefinitionNotOnThisComposablePart(string parameterName)
		{
			Assumes.NotNullOrEmpty(parameterName);
			return new ArgumentException(Format(Strings.ImportDefinitionNotOnThisComposablePart, parameterName), parameterName);
		}

		public static CompositionException CreateCannotGetExportedValue(ComposablePart part, ExportDefinition definition, Exception innerException)
		{
			Assumes.NotNull(part, definition, innerException);
			return new CompositionException(ErrorBuilder.CreateCannotGetExportedValue(part, definition, innerException));
		}

		public static ArgumentException CreateReflectionModelInvalidPartDefinition(string parameterName, Type partDefinitionType)
		{
			Assumes.NotNullOrEmpty(parameterName);
			Assumes.NotNull(partDefinitionType);
			return new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.ReflectionModel_InvalidPartDefinition, partDefinitionType), parameterName);
		}

		public static ArgumentException ExportFactory_TooManyGenericParameters(string typeName)
		{
			Assumes.NotNullOrEmpty(typeName);
			return new ArgumentException(Format(Strings.ExportFactory_TooManyGenericParameters, typeName), typeName);
		}

		private static string Format(string format, params string[] arguments)
		{
			return string.Format(CultureInfo.CurrentCulture, format, arguments);
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	public class ExportAttribute : Attribute
	{
		public string ContractName { get; private set; }

		public Type ContractType { get; private set; }

		public ExportAttribute()
			: this(null, null)
		{
		}

		public ExportAttribute(Type contractType)
			: this(null, contractType)
		{
		}

		public ExportAttribute(string contractName)
			: this(contractName, null)
		{
		}

		public ExportAttribute(string contractName, Type contractType)
		{
			ContractName = contractName;
			ContractType = contractType;
		}
	}
	internal enum ExportCardinalityCheckResult
	{
		Match,
		NoExports,
		TooManyExports
	}
	public class ExportFactory<T>
	{
		private Func<Tuple<T, Action>> _exportLifetimeContextCreator;

		public ExportFactory(Func<Tuple<T, Action>> exportLifetimeContextCreator)
		{
			if (exportLifetimeContextCreator == null)
			{
				throw new ArgumentNullException("exportLifetimeContextCreator");
			}
			_exportLifetimeContextCreator = exportLifetimeContextCreator;
		}

		public ExportLifetimeContext<T> CreateExport()
		{
			Tuple<T, Action> tuple = _exportLifetimeContextCreator();
			return new ExportLifetimeContext<T>(tuple.Item1, tuple.Item2);
		}

		internal bool IncludeInScopedCatalog(ComposablePartDefinition composablePartDefinition)
		{
			return OnFilterScopedCatalog(composablePartDefinition);
		}

		protected virtual bool OnFilterScopedCatalog(ComposablePartDefinition composablePartDefinition)
		{
			return true;
		}
	}
	public class ExportFactory<T, TMetadata> : ExportFactory<T>
	{
		private readonly TMetadata _metadata;

		public TMetadata Metadata => _metadata;

		public ExportFactory(Func<Tuple<T, Action>> exportLifetimeContextCreator, TMetadata metadata)
			: base(exportLifetimeContextCreator)
		{
			_metadata = metadata;
		}
	}
	public sealed class ExportLifetimeContext<T> : IDisposable
	{
		private readonly T _value;

		private readonly Action _disposeAction;

		public T Value => _value;

		public ExportLifetimeContext(T value, Action disposeAction)
		{
			_value = value;
			_disposeAction = disposeAction;
		}

		public void Dispose()
		{
			if (_disposeAction != null)
			{
				_disposeAction();
			}
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	public sealed class ExportMetadataAttribute : Attribute
	{
		public string Name { get; private set; }

		public object Value { get; private set; }

		public bool IsMultiple { get; set; }

		public ExportMetadataAttribute(string name, object value)
		{
			Name = name ?? string.Empty;
			Value = value;
		}
	}
	internal static class ExportServices
	{
		private sealed class DisposableLazy<T, TMetadataView> : Lazy<T, TMetadataView>, IDisposable
		{
			private IDisposable _disposable;

			public DisposableLazy(Func<T> valueFactory, TMetadataView metadataView, IDisposable disposable, LazyThreadSafetyMode mode)
				: base(valueFactory, metadataView, mode)
			{
				Assumes.NotNull(disposable);
				_disposable = disposable;
			}

			void IDisposable.Dispose()
			{
				_disposable.Dispose();
			}
		}

		private sealed class DisposableLazy<T> : Lazy<T>, IDisposable
		{
			private IDisposable _disposable;

			public DisposableLazy(Func<T> valueFactory, IDisposable disposable, LazyThreadSafetyMode mode)
				: base(valueFactory, mode)
			{
				Assumes.NotNull(disposable);
				_disposable = disposable;
			}

			void IDisposable.Dispose()
			{
				_disposable.Dispose();
			}
		}

		private static readonly MethodInfo _createStronglyTypedLazyOfTM = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfTM", BindingFlags.Static | BindingFlags.NonPublic);

		private static readonly MethodInfo _createStronglyTypedLazyOfT = typeof(ExportServices).GetMethod("CreateStronglyTypedLazyOfT", BindingFlags.Static | BindingFlags.NonPublic);

		private static readonly MethodInfo _createSemiStronglyTypedLazy = typeof(ExportServices).GetMethod("CreateSemiStronglyTypedLazy", BindingFlags.Static | BindingFlags.NonPublic);

		internal static readonly Type DefaultMetadataViewType = typeof(IDictionary<string, object>);

		internal static readonly Type DefaultExportedValueType = typeof(object);

		internal static bool IsDefaultMetadataViewType(Type metadataViewType)
		{
			Assumes.NotNull(metadataViewType);
			return metadataViewType.IsAssignableFrom(DefaultMetadataViewType);
		}

		internal static bool IsDictionaryConstructorViewType(Type metadataViewType)
		{
			Assumes.NotNull(metadataViewType);
			return metadataViewType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Type.DefaultBinder, new Type[1] { typeof(IDictionary<string, object>) }, new ParameterModifier[0]) != null;
		}

		internal static Func<Export, object> CreateStronglyTypedLazyFactory(Type exportType, Type metadataViewType)
		{
			MethodInfo methodInfo = null;
			methodInfo = ((!(metadataViewType != null)) ? _createStronglyTypedLazyOfT.MakeGenericMethod(exportType ?? DefaultExportedValueType) : _createStronglyTypedLazyOfTM.MakeGenericMethod(exportType ?? DefaultExportedValueType, metadataViewType));
			Assumes.NotNull(methodInfo);
			return (Func<Export, object>)Delegate.CreateDelegate(typeof(Func<Export, object>), methodInfo);
		}

		internal static Func<Export, Lazy<object

BepInEx/core/System.Composition.AttributedModel.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Composition.AttributedModel")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides the foundational attributes that allow you to declare parts for composition, such as imports, exports, and metadata with the Managed Extensibility Framework (MEF).")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Composition.AttributedModel")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Composition
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
	public class ExportAttribute : Attribute
	{
		public string ContractName { get; }

		public Type ContractType { get; }

		public ExportAttribute()
			: this(null, null)
		{
		}

		public ExportAttribute(Type contractType)
			: this(null, contractType)
		{
		}

		public ExportAttribute(string contractName)
			: this(contractName, null)
		{
		}

		public ExportAttribute(string contractName, Type contractType)
		{
			ContractName = contractName;
			ContractType = contractType;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	public sealed class ExportMetadataAttribute : Attribute
	{
		public string Name { get; }

		public object Value { get; }

		public ExportMetadataAttribute(string name, object value)
		{
			Name = name ?? string.Empty;
			Value = value;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public class ImportAttribute : Attribute
	{
		public string ContractName { get; }

		public bool AllowDefault { get; set; }

		public ImportAttribute()
			: this(null)
		{
		}

		public ImportAttribute(string contractName)
		{
			ContractName = contractName;
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)]
	public sealed class ImportingConstructorAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	public class ImportManyAttribute : Attribute
	{
		public string ContractName { get; }

		public ImportManyAttribute()
			: this(null)
		{
		}

		public ImportManyAttribute(string contractName)
		{
			ContractName = contractName;
		}
	}
	[AttributeUsage(AttributeTargets.Property, Inherited = false)]
	public sealed class ImportMetadataConstraintAttribute : Attribute
	{
		public string Name { get; }

		public object Value { get; }

		public ImportMetadataConstraintAttribute(string name, object value)
		{
			Name = name;
			Value = value;
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
	public sealed class MetadataAttributeAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	public sealed class OnImportsSatisfiedAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
	public class PartMetadataAttribute : Attribute
	{
		public string Name { get; }

		public object Value { get; }

		public PartMetadataAttribute(string name, object value)
		{
			Name = name ?? throw new ArgumentNullException("name");
			Value = value;
		}
	}
	[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
	public sealed class PartNotDiscoverableAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class, Inherited = false)]
	public class SharedAttribute : PartMetadataAttribute
	{
		private const string SharingBoundaryPartMetadataName = "SharingBoundary";

		public string SharingBoundary => (string)base.Value;

		public SharedAttribute()
			: base("SharingBoundary", null)
		{
		}

		public SharedAttribute(string sharingBoundaryName)
			: base("SharingBoundary", sharingBoundaryName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter, Inherited = false)]
	[MetadataAttribute]
	[CLSCompliant(false)]
	public sealed class SharingBoundaryAttribute : Attribute
	{
		private readonly string[] _sharingBoundaryNames;

		public ReadOnlyCollection<string> SharingBoundaryNames => Array.AsReadOnly(_sharingBoundaryNames);

		public SharingBoundaryAttribute(params string[] sharingBoundaryNames)
		{
			_sharingBoundaryNames = sharingBoundaryNames ?? throw new ArgumentNullException("sharingBoundaryNames");
		}
	}
}
namespace System.Composition.Convention
{
	public abstract class AttributedModelProvider
	{
		public abstract IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, MemberInfo member);

		public abstract IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, ParameterInfo parameter);
	}
}

BepInEx/core/System.Composition.Convention.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Composition.Diagnostics;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using FxResources.System.Composition.Convention;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Composition.Convention")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides types that support using Managed Extensibility Framework (MEF) with a convention-based configuration model.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Composition.Convention")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.System.Composition.Convention
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArgumentOutOfRange_InvalidEnumInSet => GetResourceString("ArgumentOutOfRange_InvalidEnumInSet");

		internal static string Argument_ExpressionMustBeNew => GetResourceString("Argument_ExpressionMustBeNew");

		internal static string Argument_ExpressionMustBePropertyMember => GetResourceString("Argument_ExpressionMustBePropertyMember");

		internal static string Registration_ConstructorConventionOverridden => GetResourceString("Registration_ConstructorConventionOverridden");

		internal static string Registration_TypeExportConventionOverridden => GetResourceString("Registration_TypeExportConventionOverridden");

		internal static string Registration_MemberExportConventionOverridden => GetResourceString("Registration_MemberExportConventionOverridden");

		internal static string Registration_MemberImportConventionOverridden => GetResourceString("Registration_MemberImportConventionOverridden");

		internal static string Registration_MemberImportConventionMatchedTwice => GetResourceString("Registration_MemberImportConventionMatchedTwice");

		internal static string Registration_ParameterImportConventionOverridden => GetResourceString("Registration_ParameterImportConventionOverridden");

		internal static string Registration_PartCreationConventionOverridden => GetResourceString("Registration_PartCreationConventionOverridden");

		internal static string Registration_PartMetadataConventionOverridden => GetResourceString("Registration_PartMetadataConventionOverridden");

		internal static string Argument_ExpressionMustBeVoidMethodWithNoArguments => GetResourceString("Argument_ExpressionMustBeVoidMethodWithNoArguments");

		internal static string Registration_OnSatisfiedImportNotificationOverridden => GetResourceString("Registration_OnSatisfiedImportNotificationOverridden");

		internal static string Diagnostic_InternalExceptionMessage => GetResourceString("Diagnostic_InternalExceptionMessage");

		internal static string Diagnostic_TraceUnnecessaryWork => GetResourceString("Diagnostic_TraceUnnecessaryWork");

		internal static string ArgumentException_EmptyString => GetResourceString("ArgumentException_EmptyString");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Composition.Diagnostics
{
	internal static class CompositionTrace
	{
		public static void Registration_ConstructorConventionOverridden(Type type)
		{
			if (type == null)
			{
				throw new Exception(System.SR.Diagnostic_InternalExceptionMessage);
			}
			if (CompositionTraceSource.CanWriteInformation)
			{
				CompositionTraceSource.WriteInformation(CompositionTraceId.Registration_ConstructorConventionOverridden, System.SR.Registration_ConstructorConventionOverridden, type.FullName);
			}
		}

		public static void Registration_TypeExportConventionOverridden(Type type)
		{
			if (type == null)
			{
				throw new Exception(System.SR.Diagnostic_InternalExceptionMessage);
			}
			if (CompositionTraceSource.CanWriteWarning)
			{
				CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_TypeExportConventionOverridden, System.SR.Registration_TypeExportConventionOverridden, type.FullName);
			}
		}

		public static void Registration_MemberExportConventionOverridden(Type type, MemberInfo member)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (CompositionTraceSource.CanWriteWarning)
			{
				CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberExportConventionOverridden, System.SR.Registration_MemberExportConventionOverridden, member.Name, type.FullName);
			}
		}

		public static void Registration_MemberImportConventionOverridden(Type type, MemberInfo member)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (CompositionTraceSource.CanWriteWarning)
			{
				CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionOverridden, System.SR.Registration_MemberImportConventionOverridden, member.Name, type.FullName);
			}
		}

		public static void Registration_OnSatisfiedImportNotificationOverridden(Type type, MemberInfo member)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (CompositionTraceSource.CanWriteWarning)
			{
				CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_OnSatisfiedImportNotificationOverridden, System.SR.Registration_OnSatisfiedImportNotificationOverridden, member.Name, type.FullName);
			}
		}

		public static void Registration_PartCreationConventionOverridden(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (CompositionTraceSource.CanWriteWarning)
			{
				CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartCreationConventionOverridden, System.SR.Registration_PartCreationConventionOverridden, type.FullName);
			}
		}

		public static void Registration_MemberImportConventionMatchedTwice(Type type, MemberInfo member)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (CompositionTraceSource.CanWriteWarning)
			{
				CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_MemberImportConventionMatchedTwice, System.SR.Registration_MemberImportConventionMatchedTwice, member.Name, type.FullName);
			}
		}

		public static void Registration_PartMetadataConventionOverridden(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (CompositionTraceSource.CanWriteWarning)
			{
				CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_PartMetadataConventionOverridden, System.SR.Registration_PartMetadataConventionOverridden, type.FullName);
			}
		}

		public static void Registration_ParameterImportConventionOverridden(ParameterInfo parameter, ConstructorInfo constructor)
		{
			if (parameter == null)
			{
				throw new ArgumentNullException("parameter");
			}
			if ((object)constructor == null)
			{
				throw new ArgumentNullException("constructor");
			}
			if (CompositionTraceSource.CanWriteWarning)
			{
				CompositionTraceSource.WriteWarning(CompositionTraceId.Registration_ParameterImportConventionOverridden, System.SR.Registration_ParameterImportConventionOverridden, parameter.Name, constructor.Name);
			}
		}
	}
	internal enum CompositionTraceId : ushort
	{
		Rejection_DefinitionRejected = 1,
		Rejection_DefinitionResurrected = 2,
		Discovery_AssemblyLoadFailed = 3,
		Discovery_DefinitionMarkedWithPartNotDiscoverableAttribute = 4,
		Discovery_DefinitionMismatchedExportArity = 5,
		Discovery_DefinitionContainsNoExports = 6,
		Discovery_MemberMarkedWithMultipleImportAndImportMany = 7,
		Registration_ConstructorConventionOverridden = 101,
		Registration_TypeExportConventionOverridden = 102,
		Registration_MemberExportConventionOverridden = 103,
		Registration_MemberImportConventionOverridden = 104,
		Registration_PartCreationConventionOverridden = 105,
		Registration_MemberImportConventionMatchedTwice = 106,
		Registration_PartMetadataConventionOverridden = 107,
		Registration_ParameterImportConventionOverridden = 108,
		Registration_OnSatisfiedImportNotificationOverridden = 109
	}
	internal static class CompositionTraceSource
	{
		private static readonly DebuggerTraceWriter s_source = new DebuggerTraceWriter();

		public static bool CanWriteInformation => s_source.CanWriteInformation;

		public static bool CanWriteWarning => s_source.CanWriteWarning;

		public static bool CanWriteError => s_source.CanWriteError;

		public static void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments)
		{
			EnsureEnabled(CanWriteInformation);
			s_source.WriteInformation(traceId, format, arguments);
		}

		public static void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments)
		{
			EnsureEnabled(CanWriteWarning);
			s_source.WriteWarning(traceId, format, arguments);
		}

		public static void WriteError(CompositionTraceId traceId, string format, params object[] arguments)
		{
			EnsureEnabled(CanWriteError);
			s_source.WriteError(traceId, format, arguments);
		}

		private static void EnsureEnabled(bool condition)
		{
			if (!condition)
			{
				throw new Exception(System.SR.Format(System.SR.Diagnostic_InternalExceptionMessage, System.SR.Diagnostic_TraceUnnecessaryWork));
			}
		}
	}
	internal sealed class DebuggerTraceWriter : TraceWriter
	{
		public enum TraceEventType
		{
			Error = 2,
			Warning = 4,
			Information = 8
		}

		private static readonly string s_sourceName = typeof(DebuggerTraceWriter).Assembly.GetName().Name;

		public override bool CanWriteInformation => false;

		public override bool CanWriteWarning => Debugger.IsLogging();

		public override bool CanWriteError => Debugger.IsLogging();

		public override void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments)
		{
			WriteEvent(TraceEventType.Information, traceId, format, arguments);
		}

		public override void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments)
		{
			WriteEvent(TraceEventType.Warning, traceId, format, arguments);
		}

		public override void WriteError(CompositionTraceId traceId, string format, params object[] arguments)
		{
			WriteEvent(TraceEventType.Error, traceId, format, arguments);
		}

		private static void WriteEvent(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments)
		{
			if (Debugger.IsLogging())
			{
				string message = CreateLogMessage(eventType, traceId, format, arguments);
				Debugger.Log(0, null, message);
			}
		}

		private static string CreateLogMessage(TraceEventType eventType, CompositionTraceId traceId, string format, params object[] arguments)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append($"{s_sourceName} {eventType}: {(int)traceId} : ");
			if (arguments == null)
			{
				stringBuilder.Append(format);
			}
			else
			{
				stringBuilder.AppendFormat(CultureInfo.InvariantCulture, format, arguments);
			}
			stringBuilder.AppendLine();
			return stringBuilder.ToString();
		}
	}
	internal abstract class TraceWriter
	{
		public abstract bool CanWriteInformation { get; }

		public abstract bool CanWriteWarning { get; }

		public abstract bool CanWriteError { get; }

		public abstract void WriteInformation(CompositionTraceId traceId, string format, params object[] arguments);

		public abstract void WriteWarning(CompositionTraceId traceId, string format, params object[] arguments);

		public abstract void WriteError(CompositionTraceId traceId, string format, params object[] arguments);
	}
}
namespace System.Composition.Convention
{
	public class ConventionBuilder : AttributedModelProvider
	{
		private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion);

		private readonly List<PartConventionBuilder> _conventions = new List<PartConventionBuilder>();

		private readonly Dictionary<MemberInfo, List<Attribute>> _memberInfos = new Dictionary<MemberInfo, List<Attribute>>();

		private readonly Dictionary<ParameterInfo, List<Attribute>> _parameters = new Dictionary<ParameterInfo, List<Attribute>>();

		public PartConventionBuilder<T> ForTypesDerivedFrom<T>()
		{
			PartConventionBuilder<T> partConventionBuilder = new PartConventionBuilder<T>((Type t) => IsDescendentOf(t, typeof(T)));
			_conventions.Add(partConventionBuilder);
			return partConventionBuilder;
		}

		public PartConventionBuilder ForTypesDerivedFrom(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			PartConventionBuilder partConventionBuilder = new PartConventionBuilder((Type t) => IsDescendentOf(t, type));
			_conventions.Add(partConventionBuilder);
			return partConventionBuilder;
		}

		public PartConventionBuilder<T> ForType<T>()
		{
			PartConventionBuilder<T> partConventionBuilder = new PartConventionBuilder<T>((Type t) => t == typeof(T));
			_conventions.Add(partConventionBuilder);
			return partConventionBuilder;
		}

		public PartConventionBuilder ForType(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			PartConventionBuilder partConventionBuilder = new PartConventionBuilder((Type t) => t == type);
			_conventions.Add(partConventionBuilder);
			return partConventionBuilder;
		}

		public PartConventionBuilder<T> ForTypesMatching<T>(Predicate<Type> typeFilter)
		{
			if (typeFilter == null)
			{
				throw new ArgumentNullException("typeFilter");
			}
			PartConventionBuilder<T> partConventionBuilder = new PartConventionBuilder<T>(typeFilter);
			_conventions.Add(partConventionBuilder);
			return partConventionBuilder;
		}

		public PartConventionBuilder ForTypesMatching(Predicate<Type> typeFilter)
		{
			if (typeFilter == null)
			{
				throw new ArgumentNullException("typeFilter");
			}
			PartConventionBuilder partConventionBuilder = new PartConventionBuilder(typeFilter);
			_conventions.Add(partConventionBuilder);
			return partConventionBuilder;
		}

		private List<Tuple<object, List<Attribute>>> EvaluateThisTypeInfoAgainstTheConvention(TypeInfo typeInfo)
		{
			List<Attribute> list = new List<Attribute>();
			List<Tuple<object, List<Attribute>>> configuredMembers = new List<Tuple<object, List<Attribute>>>();
			bool flag = false;
			bool flag2 = false;
			Type type = typeInfo.AsType();
			foreach (PartConventionBuilder item in _conventions.Where((PartConventionBuilder c) => c.SelectType(type)))
			{
				list.AddRange(item.BuildTypeAttributes(type));
				flag |= item.BuildConstructorAttributes(type, ref configuredMembers);
				item.BuildPropertyAttributes(type, ref configuredMembers);
				item.BuildOnImportsSatisfiedNotification(type, ref configuredMembers);
				flag2 = true;
			}
			if (flag2 && !flag)
			{
				PartConventionBuilder.BuildDefaultConstructorAttributes(type, ref configuredMembers);
			}
			configuredMembers.Add(Tuple.Create((object)type.GetTypeInfo(), list));
			return configuredMembers;
		}

		public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, MemberInfo member)
		{
			if ((object)member == null)
			{
				throw new ArgumentNullException("member");
			}
			List<Attribute> value = null;
			TypeInfo typeInfo = member as TypeInfo;
			if (typeInfo != null)
			{
				MemberInfo key = typeInfo;
				_lock.EnterReadLock();
				try
				{
					_memberInfos.TryGetValue(key, out value);
				}
				finally
				{
					_lock.ExitReadLock();
				}
				if (value == null)
				{
					_lock.EnterWriteLock();
					try
					{
						if (!_memberInfos.TryGetValue(key, out value))
						{
							foreach (Tuple<object, List<Attribute>> item in EvaluateThisTypeInfoAgainstTheConvention(typeInfo))
							{
								if (item.Item2 == null)
								{
									continue;
								}
								MemberInfo memberInfo = item.Item1 as MemberInfo;
								if (memberInfo != null)
								{
									if (memberInfo != null && (memberInfo is ConstructorInfo || memberInfo is TypeInfo || memberInfo is PropertyInfo || memberInfo is MethodInfo) && !_memberInfos.TryGetValue(memberInfo, out var _))
									{
										_memberInfos.Add(memberInfo, item.Item2);
									}
									continue;
								}
								if (!(item.Item1 is ParameterInfo key2))
								{
									throw new Exception(System.SR.Diagnostic_InternalExceptionMessage);
								}
								if (!_parameters.TryGetValue(key2, out var _))
								{
									_parameters.Add(key2, item.Item2);
								}
							}
						}
						_memberInfos.TryGetValue(key, out value);
					}
					finally
					{
						_lock.ExitWriteLock();
					}
				}
			}
			else if (member is PropertyInfo || member is ConstructorInfo || member is MethodInfo)
			{
				value = ReadMemberCustomAttributes(reflectedType, member);
			}
			IEnumerable<Attribute> enumerable = ((member is TypeInfo || !(member.DeclaringType != reflectedType)) ? member.GetCustomAttributes<Attribute>(inherit: false) : Enumerable.Empty<Attribute>());
			if (value != null)
			{
				return enumerable.Concat(value);
			}
			return enumerable;
		}

		private List<Attribute> ReadMemberCustomAttributes(Type reflectedType, MemberInfo member)
		{
			List<Attribute> value = null;
			bool flag = false;
			_lock.EnterReadLock();
			try
			{
				if (!_memberInfos.TryGetValue(member, out value))
				{
					if (reflectedType != null && !_memberInfos.TryGetValue(member.DeclaringType.GetTypeInfo(), out value))
					{
						flag = true;
					}
					value = null;
				}
			}
			finally
			{
				_lock.ExitReadLock();
			}
			if (flag)
			{
				((AttributedModelProvider)this).GetCustomAttributes((Type)null, (MemberInfo)reflectedType.GetTypeInfo());
				_lock.EnterReadLock();
				try
				{
					_memberInfos.TryGetValue(member, out value);
				}
				finally
				{
					_lock.ExitReadLock();
				}
			}
			return value;
		}

		public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, ParameterInfo parameter)
		{
			if (parameter == null)
			{
				throw new ArgumentNullException("parameter");
			}
			IEnumerable<Attribute> customAttributes = parameter.GetCustomAttributes<Attribute>(inherit: false);
			List<Attribute> list = ReadParameterCustomAttributes(reflectedType, parameter);
			if (list != null)
			{
				return customAttributes.Concat(list);
			}
			return customAttributes;
		}

		private List<Attribute> ReadParameterCustomAttributes(Type reflectedType, ParameterInfo parameter)
		{
			List<Attribute> value = null;
			bool flag = false;
			_lock.EnterReadLock();
			try
			{
				if (!_parameters.TryGetValue(parameter, out value))
				{
					if (reflectedType != null && !_memberInfos.TryGetValue(reflectedType.GetTypeInfo(), out value))
					{
						flag = true;
					}
					value = null;
				}
			}
			finally
			{
				_lock.ExitReadLock();
			}
			if (flag)
			{
				((AttributedModelProvider)this).GetCustomAttributes((Type)null, (MemberInfo)reflectedType.GetTypeInfo());
				_lock.EnterReadLock();
				try
				{
					_parameters.TryGetValue(parameter, out value);
				}
				finally
				{
					_lock.ExitReadLock();
				}
			}
			return value;
		}

		private static bool IsGenericDescendentOf(TypeInfo derivedType, TypeInfo baseType)
		{
			if (derivedType.BaseType == null)
			{
				return false;
			}
			if (derivedType.BaseType == baseType.AsType())
			{
				return true;
			}
			foreach (Type implementedInterface in derivedType.ImplementedInterfaces)
			{
				if (implementedInterface.IsConstructedGenericType && implementedInterface.GetGenericTypeDefinition() == baseType.AsType())
				{
					return true;
				}
			}
			return IsGenericDescendentOf(derivedType.BaseType.GetTypeInfo(), baseType);
		}

		private static bool IsDescendentOf(Type type, Type baseType)
		{
			if (type == baseType || type == typeof(object) || type == null)
			{
				return false;
			}
			TypeInfo typeInfo = type.GetTypeInfo();
			TypeInfo typeInfo2 = baseType.GetTypeInfo();
			if (typeInfo.IsGenericTypeDefinition || typeInfo2.IsGenericTypeDefinition)
			{
				return IsGenericDescendentOf(typeInfo, typeInfo2);
			}
			return typeInfo2.IsAssignableFrom(typeInfo);
		}
	}
	public sealed class ExportConventionBuilder
	{
		private string _contractName;

		private Type _contractType;

		private List<Tuple<string, object>> _metadataItems;

		private List<Tuple<string, Func<Type, object>>> _metadataItemFuncs;

		private Func<Type, string> _getContractNameFromPartType;

		internal ExportConventionBuilder()
		{
		}

		public ExportConventionBuilder AsContractType<T>()
		{
			return AsContractType(typeof(T));
		}

		public ExportConventionBuilder AsContractType(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			_contractType = type;
			return this;
		}

		public ExportConventionBuilder AsContractName(string contractName)
		{
			if (contractName == null)
			{
				throw new ArgumentNullException("contractName");
			}
			if (contractName.Length == 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "contractName"), "contractName");
			}
			_contractName = contractName;
			return this;
		}

		public ExportConventionBuilder AsContractName(Func<Type, string> getContractNameFromPartType)
		{
			if (getContractNameFromPartType == null)
			{
				throw new ArgumentNullException("getContractNameFromPartType");
			}
			_getContractNameFromPartType = getContractNameFromPartType;
			return this;
		}

		public ExportConventionBuilder AddMetadata(string name, object value)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name");
			}
			if (_metadataItems == null)
			{
				_metadataItems = new List<Tuple<string, object>>();
			}
			_metadataItems.Add(Tuple.Create(name, value));
			return this;
		}

		public ExportConventionBuilder AddMetadata(string name, Func<Type, object> getValueFromPartType)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (getValueFromPartType == null)
			{
				throw new ArgumentNullException("getValueFromPartType");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name");
			}
			if (_metadataItemFuncs == null)
			{
				_metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
			}
			_metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType));
			return this;
		}

		internal void BuildAttributes(Type type, ref List<Attribute> attributes)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Expected O, but got Unknown
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Expected O, but got Unknown
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Expected O, but got Unknown
			if (attributes == null)
			{
				attributes = new List<Attribute>();
			}
			string text = ((_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName);
			attributes.Add((Attribute)new ExportAttribute(text, _contractType));
			if (_metadataItems != null)
			{
				foreach (Tuple<string, object> metadataItem in _metadataItems)
				{
					attributes.Add((Attribute)new ExportMetadataAttribute(metadataItem.Item1, metadataItem.Item2));
				}
			}
			if (_metadataItemFuncs == null)
			{
				return;
			}
			foreach (Tuple<string, Func<Type, object>> metadataItemFunc in _metadataItemFuncs)
			{
				string item = metadataItemFunc.Item1;
				object obj = ((metadataItemFunc.Item2 != null) ? metadataItemFunc.Item2(type) : null);
				attributes.Add((Attribute)new ExportMetadataAttribute(item, obj));
			}
		}
	}
	public sealed class ImportConventionBuilder
	{
		private static readonly Type[] s_supportedImportManyTypes = new Type[3]
		{
			typeof(IList<>),
			typeof(ICollection<>),
			typeof(IEnumerable<>)
		};

		private string _contractName;

		private bool? _asMany;

		private bool _allowDefault;

		private Func<Type, string> _getContractNameFromPartType;

		private List<Tuple<string, object>> _metadataConstraintItems;

		private List<Tuple<string, Func<Type, object>>> _metadataConstraintItemFuncs;

		internal ImportConventionBuilder()
		{
		}

		public ImportConventionBuilder AsContractName(string contractName)
		{
			if (contractName == null)
			{
				throw new ArgumentNullException("contractName");
			}
			if (contractName.Length == 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "contractName"), "contractName");
			}
			_contractName = contractName;
			return this;
		}

		public ImportConventionBuilder AsContractName(Func<Type, string> getContractNameFromPartType)
		{
			if (getContractNameFromPartType == null)
			{
				throw new ArgumentNullException("getContractNameFromPartType");
			}
			_getContractNameFromPartType = getContractNameFromPartType;
			return this;
		}

		public ImportConventionBuilder AsMany()
		{
			return AsMany(isMany: true);
		}

		public ImportConventionBuilder AsMany(bool isMany)
		{
			_asMany = isMany;
			return this;
		}

		public ImportConventionBuilder AllowDefault()
		{
			_allowDefault = true;
			return this;
		}

		public ImportConventionBuilder AddMetadataConstraint(string name, object value)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name");
			}
			if (_metadataConstraintItems == null)
			{
				_metadataConstraintItems = new List<Tuple<string, object>>();
			}
			_metadataConstraintItems.Add(Tuple.Create(name, value));
			return this;
		}

		public ImportConventionBuilder AddMetadataConstraint(string name, Func<Type, object> getConstraintValueFromPartType)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (getConstraintValueFromPartType == null)
			{
				throw new ArgumentNullException("getConstraintValueFromPartType");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name");
			}
			if (_metadataConstraintItemFuncs == null)
			{
				_metadataConstraintItemFuncs = new List<Tuple<string, Func<Type, object>>>();
			}
			_metadataConstraintItemFuncs.Add(Tuple.Create(name, getConstraintValueFromPartType));
			return this;
		}

		internal void BuildAttributes(Type type, ref List<Attribute> attributes)
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Expected O, but got Unknown
			//IL_0044: 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_0056: Expected O, but got Unknown
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Expected O, but got Unknown
			//IL_010e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0118: Expected O, but got Unknown
			string text = ((_getContractNameFromPartType != null) ? _getContractNameFromPartType(type) : _contractName);
			Attribute item = ((_asMany ?? IsSupportedImportManyType(type.GetTypeInfo())) ? ((Attribute)new ImportManyAttribute(text)) : ((Attribute)new ImportAttribute(text)
			{
				AllowDefault = _allowDefault
			}));
			if (attributes == null)
			{
				attributes = new List<Attribute>();
			}
			attributes.Add(item);
			if (_metadataConstraintItems != null)
			{
				foreach (Tuple<string, object> metadataConstraintItem in _metadataConstraintItems)
				{
					attributes.Add((Attribute)new ImportMetadataConstraintAttribute(metadataConstraintItem.Item1, metadataConstraintItem.Item2));
				}
			}
			if (_metadataConstraintItemFuncs == null)
			{
				return;
			}
			foreach (Tuple<string, Func<Type, object>> metadataConstraintItemFunc in _metadataConstraintItemFuncs)
			{
				string item2 = metadataConstraintItemFunc.Item1;
				object obj = ((metadataConstraintItemFunc.Item2 != null) ? metadataConstraintItemFunc.Item2(type) : null);
				attributes.Add((Attribute)new ImportMetadataConstraintAttribute(item2, obj));
			}
		}

		private static bool IsSupportedImportManyType(TypeInfo typeInfo)
		{
			if (!typeInfo.IsArray && (!typeInfo.IsGenericTypeDefinition || !s_supportedImportManyTypes.Contains(typeInfo.AsType())))
			{
				if (typeInfo.AsType().IsConstructedGenericType)
				{
					return s_supportedImportManyTypes.Contains(typeInfo.GetGenericTypeDefinition());
				}
				return false;
			}
			return true;
		}
	}
	public abstract class ParameterImportConventionBuilder
	{
		private ParameterImportConventionBuilder()
		{
		}

		public T Import<T>()
		{
			return default(T);
		}

		public T Import<T>(Action<ImportConventionBuilder> configure)
		{
			return default(T);
		}
	}
	public class PartConventionBuilder
	{
		private readonly Type[] _emptyTypeArray = Type.EmptyTypes;

		private static List<Attribute> s_onImportsSatisfiedAttributeList;

		private static readonly List<Attribute> s_importingConstructorList = new List<Attribute> { (Attribute)new ImportingConstructorAttribute() };

		private static readonly Type s_exportAttributeType = typeof(ExportAttribute);

		private readonly List<ExportConventionBuilder> _typeExportBuilders;

		private bool _isShared;

		private string _sharingBoundary;

		private List<Tuple<string, object>> _metadataItems;

		private List<Tuple<string, Func<Type, object>>> _metadataItemFuncs;

		private Func<IEnumerable<ConstructorInfo>, ConstructorInfo> _constructorFilter;

		private Action<ParameterInfo, ImportConventionBuilder> _configureConstructorImports;

		private readonly List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type>> _propertyExports;

		private readonly List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>>> _propertyImports;

		private readonly List<Tuple<Predicate<Type>, Action<Type, ExportConventionBuilder>>> _interfaceExports;

		private readonly List<Predicate<MethodInfo>> _methodImportsSatisfiedNotifications;

		internal Predicate<Type> SelectType { get; }

		internal PartConventionBuilder(Predicate<Type> selectType)
		{
			SelectType = selectType;
			_typeExportBuilders = new List<ExportConventionBuilder>();
			_propertyExports = new List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type>>();
			_propertyImports = new List<Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>>>();
			_interfaceExports = new List<Tuple<Predicate<Type>, Action<Type, ExportConventionBuilder>>>();
			_methodImportsSatisfiedNotifications = new List<Predicate<MethodInfo>>();
		}

		public PartConventionBuilder Export()
		{
			ExportConventionBuilder item = new ExportConventionBuilder();
			_typeExportBuilders.Add(item);
			return this;
		}

		public PartConventionBuilder Export(Action<ExportConventionBuilder> exportConfiguration)
		{
			if (exportConfiguration == null)
			{
				throw new ArgumentNullException("exportConfiguration");
			}
			ExportConventionBuilder exportConventionBuilder = new ExportConventionBuilder();
			exportConfiguration(exportConventionBuilder);
			_typeExportBuilders.Add(exportConventionBuilder);
			return this;
		}

		public PartConventionBuilder Export<T>()
		{
			ExportConventionBuilder item = new ExportConventionBuilder().AsContractType<T>();
			_typeExportBuilders.Add(item);
			return this;
		}

		public PartConventionBuilder Export<T>(Action<ExportConventionBuilder> exportConfiguration)
		{
			if (exportConfiguration == null)
			{
				throw new ArgumentNullException("exportConfiguration");
			}
			ExportConventionBuilder exportConventionBuilder = new ExportConventionBuilder().AsContractType<T>();
			exportConfiguration(exportConventionBuilder);
			_typeExportBuilders.Add(exportConventionBuilder);
			return this;
		}

		public PartConventionBuilder SelectConstructor(Func<IEnumerable<ConstructorInfo>, ConstructorInfo> constructorSelector)
		{
			if (constructorSelector == null)
			{
				throw new ArgumentNullException("constructorSelector");
			}
			_constructorFilter = constructorSelector;
			return this;
		}

		public PartConventionBuilder SelectConstructor(Func<IEnumerable<ConstructorInfo>, ConstructorInfo> constructorSelector, Action<ParameterInfo, ImportConventionBuilder> importConfiguration)
		{
			if (importConfiguration == null)
			{
				throw new ArgumentNullException("importConfiguration");
			}
			_configureConstructorImports = importConfiguration;
			SelectConstructor(constructorSelector);
			return this;
		}

		public PartConventionBuilder ExportInterfaces(Predicate<Type> interfaceFilter)
		{
			if (interfaceFilter == null)
			{
				throw new ArgumentNullException("interfaceFilter");
			}
			return ExportInterfacesImpl(interfaceFilter, null);
		}

		public PartConventionBuilder ExportInterfaces()
		{
			return ExportInterfaces((Type t) => true);
		}

		public PartConventionBuilder ExportInterfaces(Predicate<Type> interfaceFilter, Action<Type, ExportConventionBuilder> exportConfiguration)
		{
			if (interfaceFilter == null)
			{
				throw new ArgumentNullException("interfaceFilter");
			}
			if (exportConfiguration == null)
			{
				throw new ArgumentNullException("exportConfiguration");
			}
			return ExportInterfacesImpl(interfaceFilter, exportConfiguration);
		}

		private PartConventionBuilder ExportInterfacesImpl(Predicate<Type> interfaceFilter, Action<Type, ExportConventionBuilder> exportConfiguration)
		{
			_interfaceExports.Add(Tuple.Create(interfaceFilter, exportConfiguration));
			return this;
		}

		public PartConventionBuilder ExportProperties(Predicate<PropertyInfo> propertyFilter)
		{
			if (propertyFilter == null)
			{
				throw new ArgumentNullException("propertyFilter");
			}
			return ExportPropertiesImpl(propertyFilter, null);
		}

		public PartConventionBuilder ExportProperties(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ExportConventionBuilder> exportConfiguration)
		{
			if (propertyFilter == null)
			{
				throw new ArgumentNullException("propertyFilter");
			}
			if (exportConfiguration == null)
			{
				throw new ArgumentNullException("exportConfiguration");
			}
			return ExportPropertiesImpl(propertyFilter, exportConfiguration);
		}

		private PartConventionBuilder ExportPropertiesImpl(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ExportConventionBuilder> exportConfiguration)
		{
			_propertyExports.Add(Tuple.Create<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type>(propertyFilter, exportConfiguration, null));
			return this;
		}

		public PartConventionBuilder ExportProperties<T>(Predicate<PropertyInfo> propertyFilter)
		{
			if (propertyFilter == null)
			{
				throw new ArgumentNullException("propertyFilter");
			}
			return ExportPropertiesImpl<T>(propertyFilter, null);
		}

		public PartConventionBuilder ExportProperties<T>(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ExportConventionBuilder> exportConfiguration)
		{
			if (propertyFilter == null)
			{
				throw new ArgumentNullException("propertyFilter");
			}
			if (exportConfiguration == null)
			{
				throw new ArgumentNullException("exportConfiguration");
			}
			return ExportPropertiesImpl<T>(propertyFilter, exportConfiguration);
		}

		private PartConventionBuilder ExportPropertiesImpl<T>(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ExportConventionBuilder> exportConfiguration)
		{
			_propertyExports.Add(Tuple.Create(propertyFilter, exportConfiguration, typeof(T)));
			return this;
		}

		public PartConventionBuilder ImportProperties(Predicate<PropertyInfo> propertyFilter)
		{
			if (propertyFilter == null)
			{
				throw new ArgumentNullException("propertyFilter");
			}
			return ImportPropertiesImpl(propertyFilter, null);
		}

		public PartConventionBuilder ImportProperties(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ImportConventionBuilder> importConfiguration)
		{
			if (propertyFilter == null)
			{
				throw new ArgumentNullException("propertyFilter");
			}
			if (importConfiguration == null)
			{
				throw new ArgumentNullException("importConfiguration");
			}
			return ImportPropertiesImpl(propertyFilter, importConfiguration);
		}

		private PartConventionBuilder ImportPropertiesImpl(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ImportConventionBuilder> importConfiguration)
		{
			_propertyImports.Add(Tuple.Create(propertyFilter, importConfiguration));
			return this;
		}

		public PartConventionBuilder ImportProperties<T>(Predicate<PropertyInfo> propertyFilter)
		{
			if (propertyFilter == null)
			{
				throw new ArgumentNullException("propertyFilter");
			}
			return ImportPropertiesImpl<T>(propertyFilter, null);
		}

		public PartConventionBuilder ImportProperties<T>(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ImportConventionBuilder> importConfiguration)
		{
			if (propertyFilter == null)
			{
				throw new ArgumentNullException("propertyFilter");
			}
			if (importConfiguration == null)
			{
				throw new ArgumentNullException("importConfiguration");
			}
			return ImportPropertiesImpl<T>(propertyFilter, importConfiguration);
		}

		private PartConventionBuilder ImportPropertiesImpl<T>(Predicate<PropertyInfo> propertyFilter, Action<PropertyInfo, ImportConventionBuilder> importConfiguration)
		{
			Predicate<PropertyInfo> item = (PropertyInfo pi) => pi.PropertyType.Equals(typeof(T)) && (propertyFilter == null || propertyFilter(pi));
			_propertyImports.Add(Tuple.Create(item, importConfiguration));
			return this;
		}

		public PartConventionBuilder NotifyImportsSatisfied(Predicate<MethodInfo> methodFilter)
		{
			_methodImportsSatisfiedNotifications.Add(methodFilter);
			return this;
		}

		public PartConventionBuilder Shared()
		{
			return SharedImpl(null);
		}

		public PartConventionBuilder Shared(string sharingBoundary)
		{
			if (sharingBoundary == null)
			{
				throw new ArgumentNullException("sharingBoundary");
			}
			if (sharingBoundary.Length == 0)
			{
				throw new ArgumentException(System.SR.ArgumentException_EmptyString);
			}
			return SharedImpl(sharingBoundary);
		}

		private PartConventionBuilder SharedImpl(string sharingBoundary)
		{
			_isShared = true;
			_sharingBoundary = sharingBoundary;
			return this;
		}

		public PartConventionBuilder AddPartMetadata(string name, object value)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name");
			}
			if (_metadataItems == null)
			{
				_metadataItems = new List<Tuple<string, object>>();
			}
			_metadataItems.Add(Tuple.Create(name, value));
			return this;
		}

		public PartConventionBuilder AddPartMetadata(string name, Func<Type, object> getValueFromPartType)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (getValueFromPartType == null)
			{
				throw new ArgumentNullException("getValueFromPartType");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException(System.SR.Format(System.SR.ArgumentException_EmptyString, "name"), "name");
			}
			if (_metadataItemFuncs == null)
			{
				_metadataItemFuncs = new List<Tuple<string, Func<Type, object>>>();
			}
			_metadataItemFuncs.Add(Tuple.Create(name, getValueFromPartType));
			return this;
		}

		private static bool MemberHasExportMetadata(MemberInfo member)
		{
			foreach (Attribute customAttribute in member.GetCustomAttributes<Attribute>(inherit: false))
			{
				if (customAttribute is ExportMetadataAttribute)
				{
					return true;
				}
				Type type = customAttribute.GetType();
				if (type != s_exportAttributeType && type.GetTypeInfo().IsDefined(typeof(MetadataAttributeAttribute), inherit: true))
				{
					return true;
				}
			}
			return false;
		}

		internal IEnumerable<Attribute> BuildTypeAttributes(Type type)
		{
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Expected O, but got Unknown
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Expected O, but got Unknown
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			List<Attribute> attributes = new List<Attribute>();
			if (_typeExportBuilders != null)
			{
				if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<ExportAttribute>(inherit: false).FirstOrDefault() != null || MemberHasExportMetadata(type.GetTypeInfo()))
				{
					CompositionTrace.Registration_TypeExportConventionOverridden(type);
				}
				else
				{
					foreach (ExportConventionBuilder typeExportBuilder in _typeExportBuilders)
					{
						typeExportBuilder.BuildAttributes(type, ref attributes);
					}
				}
			}
			if (_isShared)
			{
				if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<SharedAttribute>(inherit: false).FirstOrDefault() != null)
				{
					CompositionTrace.Registration_PartCreationConventionOverridden(type);
				}
				else
				{
					attributes.Add((Attribute)((_sharingBoundary == null) ? new SharedAttribute() : new SharedAttribute(_sharingBoundary)));
				}
			}
			if (_metadataItems != null)
			{
				if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<PartMetadataAttribute>(inherit: false).FirstOrDefault() != null)
				{
					CompositionTrace.Registration_PartMetadataConventionOverridden(type);
				}
				else
				{
					foreach (Tuple<string, object> metadataItem in _metadataItems)
					{
						attributes.Add((Attribute)new PartMetadataAttribute(metadataItem.Item1, metadataItem.Item2));
					}
				}
			}
			if (_metadataItemFuncs != null)
			{
				if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<PartMetadataAttribute>(inherit: false).FirstOrDefault() != null)
				{
					CompositionTrace.Registration_PartMetadataConventionOverridden(type);
				}
				else
				{
					foreach (Tuple<string, Func<Type, object>> metadataItemFunc in _metadataItemFuncs)
					{
						string item = metadataItemFunc.Item1;
						object obj = ((metadataItemFunc.Item2 != null) ? metadataItemFunc.Item2(type) : null);
						attributes.Add((Attribute)new PartMetadataAttribute(item, obj));
					}
				}
			}
			if (_interfaceExports.Count != 0 && _typeExportBuilders != null)
			{
				if (((MemberInfo)type.GetTypeInfo()).GetCustomAttributes<ExportAttribute>(inherit: false).FirstOrDefault() != null || MemberHasExportMetadata(type.GetTypeInfo()))
				{
					CompositionTrace.Registration_TypeExportConventionOverridden(type);
				}
				else
				{
					foreach (Type implementedInterface in type.GetTypeInfo().ImplementedInterfaces)
					{
						if (implementedInterface == typeof(IDisposable))
						{
							continue;
						}
						foreach (Tuple<Predicate<Type>, Action<Type, ExportConventionBuilder>> interfaceExport in _interfaceExports)
						{
							if (interfaceExport.Item1 != null && interfaceExport.Item1(implementedInterface))
							{
								ExportConventionBuilder exportConventionBuilder = new ExportConventionBuilder();
								exportConventionBuilder.AsContractType(implementedInterface);
								interfaceExport.Item2?.Invoke(implementedInterface, exportConventionBuilder);
								exportConventionBuilder.BuildAttributes(implementedInterface, ref attributes);
							}
						}
					}
				}
			}
			return attributes;
		}

		internal bool BuildConstructorAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers)
		{
			ConstructorInfo[] constructors = type.GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			ConstructorInfo[] array = constructors;
			for (int i = 0; i < array.Length; i++)
			{
				if (Attribute.GetCustomAttributes(array[i], typeof(ImportingConstructorAttribute), inherit: false).Length != 0)
				{
					CompositionTrace.Registration_ConstructorConventionOverridden(type);
					return true;
				}
			}
			if (_constructorFilter != null)
			{
				ConstructorInfo constructorInfo = _constructorFilter(constructors);
				if (constructorInfo != null)
				{
					ConfigureConstructorAttributes(constructorInfo, ref configuredMembers, _configureConstructorImports);
				}
				return true;
			}
			if (_configureConstructorImports != null)
			{
				bool result = false;
				{
					foreach (ConstructorInfo item in FindLongestConstructors(constructors))
					{
						ConfigureConstructorAttributes(item, ref configuredMembers, _configureConstructorImports);
						result = true;
					}
					return result;
				}
			}
			return false;
		}

		internal static void BuildDefaultConstructorAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers)
		{
			foreach (ConstructorInfo item in FindLongestConstructors(type.GetConstructors(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)))
			{
				ConfigureConstructorAttributes(item, ref configuredMembers, null);
			}
		}

		private static void ConfigureConstructorAttributes(ConstructorInfo constructorInfo, ref List<Tuple<object, List<Attribute>>> configuredMembers, Action<ParameterInfo, ImportConventionBuilder> configureConstructorImports)
		{
			if (configuredMembers == null)
			{
				configuredMembers = new List<Tuple<object, List<Attribute>>>();
			}
			configuredMembers.Add(Tuple.Create((object)constructorInfo, s_importingConstructorList));
			ParameterInfo[] parameters = constructorInfo.GetParameters();
			foreach (ParameterInfo parameterInfo in parameters)
			{
				if (parameterInfo.GetCustomAttributes<ImportAttribute>(inherit: false).FirstOrDefault() != null || parameterInfo.GetCustomAttributes<ImportManyAttribute>(inherit: false).FirstOrDefault() != null)
				{
					CompositionTrace.Registration_ParameterImportConventionOverridden(parameterInfo, constructorInfo);
					continue;
				}
				ImportConventionBuilder importConventionBuilder = new ImportConventionBuilder();
				configureConstructorImports?.Invoke(parameterInfo, importConventionBuilder);
				List<Attribute> attributes = null;
				importConventionBuilder.BuildAttributes(parameterInfo.ParameterType, ref attributes);
				configuredMembers.Add(Tuple.Create((object)parameterInfo, attributes));
			}
		}

		internal void BuildOnImportsSatisfiedNotification(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers)
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			if (_methodImportsSatisfiedNotifications == null)
			{
				return;
			}
			foreach (MethodInfo runtimeMethod2 in type.GetRuntimeMethods())
			{
				if (!(runtimeMethod2.ReturnParameter.ParameterType == typeof(void)) || runtimeMethod2.GetParameters().Length != 0)
				{
					continue;
				}
				MethodInfo runtimeMethod = runtimeMethod2.DeclaringType.GetRuntimeMethod(runtimeMethod2.Name, _emptyTypeArray);
				if (!(runtimeMethod != null))
				{
					continue;
				}
				bool flag = false;
				bool flag2 = false;
				foreach (Predicate<MethodInfo> methodImportsSatisfiedNotification in _methodImportsSatisfiedNotifications)
				{
					if (methodImportsSatisfiedNotification(runtimeMethod))
					{
						if (!flag)
						{
							flag2 = ((MemberInfo)runtimeMethod2).GetCustomAttributes<OnImportsSatisfiedAttribute>(inherit: false).FirstOrDefault() != null;
							flag = true;
						}
						if (flag2)
						{
							CompositionTrace.Registration_OnSatisfiedImportNotificationOverridden(type, runtimeMethod2);
							break;
						}
						if (s_onImportsSatisfiedAttributeList == null)
						{
							s_onImportsSatisfiedAttributeList = new List<Attribute> { (Attribute)new OnImportsSatisfiedAttribute() };
						}
						configuredMembers.Add(new Tuple<object, List<Attribute>>(runtimeMethod2, s_onImportsSatisfiedAttributeList));
					}
				}
			}
		}

		internal void BuildPropertyAttributes(Type type, ref List<Tuple<object, List<Attribute>>> configuredMembers)
		{
			if (_propertyImports.Count == 0 && _propertyExports.Count == 0)
			{
				return;
			}
			foreach (PropertyInfo runtimeProperty in type.GetRuntimeProperties())
			{
				List<Attribute> attributes = null;
				int num = 0;
				bool flag = false;
				bool flag2 = false;
				PropertyInfo propertyInfo = null;
				foreach (Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ImportConventionBuilder>> propertyImport in _propertyImports)
				{
					if ((object)propertyInfo == null)
					{
						propertyInfo = runtimeProperty.DeclaringType.GetRuntimeProperty(runtimeProperty.Name);
					}
					if (propertyImport.Item1 != null && propertyImport.Item1(propertyInfo))
					{
						ImportConventionBuilder importConventionBuilder = new ImportConventionBuilder();
						propertyImport.Item2?.Invoke(runtimeProperty, importConventionBuilder);
						if (!flag)
						{
							flag2 = ((MemberInfo)runtimeProperty).GetCustomAttributes<ImportAttribute>(inherit: false).FirstOrDefault() != null || ((MemberInfo)runtimeProperty).GetCustomAttributes<ImportManyAttribute>(inherit: false).FirstOrDefault() != null;
							flag = true;
						}
						if (flag2)
						{
							CompositionTrace.Registration_MemberImportConventionOverridden(type, runtimeProperty);
							break;
						}
						importConventionBuilder.BuildAttributes(runtimeProperty.PropertyType, ref attributes);
						num++;
					}
					if (num > 1)
					{
						CompositionTrace.Registration_MemberImportConventionMatchedTwice(type, runtimeProperty);
					}
				}
				flag = false;
				flag2 = false;
				foreach (Tuple<Predicate<PropertyInfo>, Action<PropertyInfo, ExportConventionBuilder>, Type> propertyExport in _propertyExports)
				{
					if ((object)propertyInfo == null)
					{
						propertyInfo = runtimeProperty.DeclaringType.GetRuntimeProperty(runtimeProperty.Name);
					}
					if (propertyExport.Item1 != null && propertyExport.Item1(propertyInfo))
					{
						ExportConventionBuilder exportConventionBuilder = new ExportConventionBuilder();
						if (propertyExport.Item3 != null)
						{
							exportConventionBuilder.AsContractType(propertyExport.Item3);
						}
						propertyExport.Item2?.Invoke(runtimeProperty, exportConventionBuilder);
						if (!flag)
						{
							flag2 = ((MemberInfo)runtimeProperty).GetCustomAttributes<ExportAttribute>(inherit: false).FirstOrDefault() != null || MemberHasExportMetadata(runtimeProperty);
							flag = true;
						}
						if (flag2)
						{
							CompositionTrace.Registration_MemberExportConventionOverridden(type, runtimeProperty);
							break;
						}
						exportConventionBuilder.BuildAttributes(runtimeProperty.PropertyType, ref attributes);
					}
				}
				if (attributes != null)
				{
					if (configuredMembers == null)
					{
						configuredMembers = new List<Tuple<object, List<Attribute>>>();
					}
					configuredMembers.Add(Tuple.Create((object)runtimeProperty, attributes));
				}
			}
		}

		private static IEnumerable<ConstructorInfo> FindLongestConstructors(ConstructorInfo[] constructors)
		{
			ConstructorInfo constructorInfo = null;
			int argumentsCount = 0;
			int num = 0;
			foreach (ConstructorInfo constructorInfo2 in constructors)
			{
				int num2 = constructorInfo2.GetParameters().Length;
				if (num2 != 0)
				{
					if (num2 > argumentsCount)
					{
						constructorInfo = constructorInfo2;
						argumentsCount = num2;
						num = 1;
					}
					else if (num2 == argumentsCount)
					{
						num++;
					}
				}
			}
			if (num > 1)
			{
				foreach (ConstructorInfo constructorInfo3 in constructors)
				{
					if (constructorInfo3.GetParameters().Length == argumentsCount)
					{
						yield return constructorInfo3;
					}
				}
			}
			else if (num == 1)
			{
				yield return constructorInfo;
			}
		}
	}
	public class PartConventionBuilder<T> : PartConventionBuilder
	{
		private sealed class MethodExpressionAdapter
		{
			private readonly MethodInfo _methodInfo;

			public MethodExpressionAdapter(Expression<Action<T>> methodSelector)
			{
				_methodInfo = SelectMethods(methodSelector);
			}

			public bool VerifyMethodInfo(MethodInfo mi)
			{
				return mi == _methodInfo;
			}

			private static MethodInfo SelectMethods(Expression<Action<T>> methodSelector)
			{
				if (methodSelector == null)
				{
					throw new ArgumentNullException("methodSelector");
				}
				Expression body = Reduce(methodSelector).Body;
				if (body.NodeType == ExpressionType.Call)
				{
					MethodInfo method = ((MethodCallExpression)body).Method;
					if (method != null)
					{
						return method;
					}
				}
				throw new ArgumentException(System.SR.Format(System.SR.Argument_ExpressionMustBeVoidMethodWithNoArguments, "methodSelector"), "methodSelector");
			}

			private static Expression<Func<T, object>> Reduce(Expression<Func<T, object>> expr)
			{
				while (expr.CanReduce)
				{
					expr = (Expression<Func<T, object>>)expr.Reduce();
				}
				return expr;
			}

			private static Expression<Action<T>> Reduce(Expression<Action<T>> expr)
			{
				while (expr.CanReduce)
				{
					expr = (Expression<Action<T>>)expr.Reduce();
				}
				return expr;
			}
		}

		private sealed class PropertyExpressionAdapter
		{
			private readonly PropertyInfo _propertyInfo;

			private readonly Action<ImportConventionBuilder> _configureImport;

			private readonly Action<ExportConventionBuilder> _configureExport;

			public PropertyExpressionAdapter(Expression<Func<T, object>> propertySelector, Action<ImportConventionBuilder> configureImport = null, Action<ExportConventionBuilder> configureExport = null)
			{
				_propertyInfo = SelectProperties(propertySelector);
				_configureImport = configureImport;
				_configureExport = configureExport;
			}

			public bool VerifyPropertyInfo(PropertyInfo pi)
			{
				return pi == _propertyInfo;
			}

			public void ConfigureImport(PropertyInfo _, ImportConventionBuilder importBuilder)
			{
				_configureImport?.Invoke(importBuilder);
			}

			public void ConfigureExport(PropertyInfo _, ExportConventionBuilder exportBuilder)
			{
				_configureExport?.Invoke(exportBuilder);
			}

			private static PropertyInfo SelectProperties(Expression<Func<T, object>> propertySelector)
			{
				if (propertySelector == null)
				{
					throw new ArgumentNullException("propertySelector");
				}
				Expression body = Reduce(propertySelector).Body;
				if (body.NodeType == ExpressionType.MemberAccess)
				{
					PropertyInfo propertyInfo = ((MemberExpression)body).Member as PropertyInfo;
					if (propertyInfo != null)
					{
						return propertyInfo;
					}
				}
				throw new ArgumentException(System.SR.Format(System.SR.Argument_ExpressionMustBePropertyMember, "propertySelector"), "propertySelector");
			}

			private static Expression<Func<T, object>> Reduce(Expression<Func<T, object>> expr)
			{
				while (expr.CanReduce)
				{
					expr = (Expression<Func<T, object>>)expr.Reduce();
				}
				return expr;
			}
		}

		private sealed class ConstructorExpressionAdapter
		{
			private ConstructorInfo _constructorInfo;

			private Dictionary<ParameterInfo, Action<ImportConventionBuilder>> _importBuilders;

			public ConstructorExpressionAdapter(Expression<Func<ParameterImportConventionBuilder, T>> selectConstructor)
			{
				ParseSelectConstructor(selectConstructor);
			}

			public ConstructorInfo SelectConstructor(IEnumerable<ConstructorInfo> _)
			{
				return _constructorInfo;
			}

			public void ConfigureConstructorImports(ParameterInfo parameterInfo, ImportConventionBuilder importBuilder)
			{
				if (_importBuilders != null && _importBuilders.TryGetValue(parameterInfo, out var value))
				{
					value(importBuilder);
				}
			}

			private void ParseSelectConstructor(Expression<Func<ParameterImportConventionBuilder, T>> constructorSelector)
			{
				if (constructorSelector == null)
				{
					throw new ArgumentNullException("constructorSelector");
				}
				Expression body = Reduce(constructorSelector).Body;
				if (body.NodeType != ExpressionType.New)
				{
					throw new ArgumentException(System.SR.Format(System.SR.Argument_ExpressionMustBeNew, "constructorSelector"), "constructorSelector");
				}
				NewExpression newExpression = (NewExpression)body;
				_constructorInfo = newExpression.Constructor;
				int num = 0;
				ParameterInfo[] parameters = _constructorInfo.GetParameters();
				foreach (Expression argument in newExpression.Arguments)
				{
					if (argument.NodeType != ExpressionType.Call)
					{
						continue;
					}
					MethodCallExpression methodCallExpression = (MethodCallExpression)argument;
					if (methodCallExpression.Arguments.Count != 1)
					{
						continue;
					}
					Expression expression = methodCallExpression.Arguments[0];
					if (expression.NodeType == ExpressionType.Lambda)
					{
						Delegate @delegate = ((LambdaExpression)expression).Compile();
						if (_importBuilders == null)
						{
							_importBuilders = new Dictionary<ParameterInfo, Action<ImportConventionBuilder>>();
						}
						_importBuilders.Add(parameters[num], (Action<ImportConventionBuilder>)@delegate);
						num++;
					}
				}
			}

			private static Expression<Func<ParameterImportConventionBuilder, T>> Reduce(Expression<Func<ParameterImportConventionBuilder, T>> expr)
			{
				while (expr.CanReduce)
				{
					expr.Reduce();
				}
				return expr;
			}
		}

		internal PartConventionBuilder(Predicate<Type> selectType)
			: base(selectType)
		{
		}

		public PartConventionBuilder<T> SelectConstructor(Expression<Func<ParameterImportConventionBuilder, T>> constructorSelector)
		{
			if (constructorSelector == null)
			{
				throw new ArgumentNullException("constructorSelector");
			}
			ConstructorExpressionAdapter @object = new ConstructorExpressionAdapter(constructorSelector);
			SelectConstructor(@object.SelectConstructor, @object.ConfigureConstructorImports);
			return this;
		}

		public PartConventionBuilder<T> ExportProperty(Expression<Func<T, object>> propertySelector)
		{
			return ExportProperty(propertySelector, null);
		}

		public PartConventionBuilder<T> ExportProperty(Expression<Func<T, object>> propertySelector, Action<ExportConventionBuilder> exportConfiguration)
		{
			if (propertySelector == null)
			{
				throw new ArgumentNullException("propertySelector");
			}
			PropertyExpressionAdapter @object = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration);
			ExportProperties(@object.VerifyPropertyInfo, @object.ConfigureExport);
			return this;
		}

		public PartConventionBuilder<T> ExportProperty<TContract>(Expression<Func<T, object>> propertySelector)
		{
			return ExportProperty<TContract>(propertySelector, null);
		}

		public PartConventionBuilder<T> ExportProperty<TContract>(Expression<Func<T, object>> propertySelector, Action<ExportConventionBuilder> exportConfiguration)
		{
			if (propertySelector == null)
			{
				throw new ArgumentNullException("propertySelector");
			}
			PropertyExpressionAdapter @object = new PropertyExpressionAdapter(propertySelector, null, exportConfiguration);
			ExportProperties<TContract>(@object.VerifyPropertyInfo, @object.ConfigureExport);
			return this;
		}

		public PartConventionBuilder<T> ImportProperty(Expression<Func<T, object>> propertySelector)
		{
			return ImportProperty(propertySelector, null);
		}

		public PartConventionBuilder<T> ImportProperty(Expression<Func<T, object>> propertySelector, Action<ImportConventionBuilder> importConfiguration)
		{
			if (propertySelector == null)
			{
				throw new ArgumentNullException("propertySelector");
			}
			PropertyExpressionAdapter @object = new PropertyExpressionAdapter(propertySelector, importConfiguration);
			ImportProperties(@object.VerifyPropertyInfo, @object.ConfigureImport);
			return this;
		}

		public PartConventionBuilder<T> ImportProperty<TContract>(Expression<Func<T, object>> propertySelector)
		{
			return ImportProperty<TContract>(propertySelector, null);
		}

		public PartConventionBuilder<T> ImportProperty<TContract>(Expression<Func<T, object>> propertySelector, Action<ImportConventionBuilder> importConfiguration)
		{
			if (propertySelector == null)
			{
				throw new ArgumentNullException("propertySelector");
			}
			PropertyExpressionAdapter @object = new PropertyExpressionAdapter(propertySelector, importConfiguration);
			ImportProperties<TContract>(@object.VerifyPropertyInfo, @object.ConfigureImport);
			return this;
		}

		public PartConventionBuilder<T> NotifyImportsSatisfied(Expression<Action<T>> methodSelector)
		{
			if (methodSelector == null)
			{
				throw new ArgumentNullException("methodSelector");
			}
			MethodExpressionAdapter @object = new MethodExpressionAdapter(methodSelector);
			NotifyImportsSatisfied(@object.VerifyMethodInfo);
			return this;
		}
	}
}

BepInEx/core/System.Composition.Hosting.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Composition.Hosting.Core;
using System.Composition.Hosting.Providers.CurrentScope;
using System.Composition.Hosting.Providers.ExportFactory;
using System.Composition.Hosting.Providers.ImportMany;
using System.Composition.Hosting.Providers.Lazy;
using System.Composition.Hosting.Providers.Metadata;
using System.Composition.Hosting.Util;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
using System.Threading;
using FxResources.System.Composition.Hosting;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Composition.Hosting")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides Managed Extensibility Framework (MEF) types that are useful to developers of extensible applications, or hosts.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Composition.Hosting")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.System.Composition.Hosting
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Dependency_ExportNotFound => GetResourceString("Dependency_ExportNotFound");

		internal static string Dependency_QuoteParameter => GetResourceString("Dependency_QuoteParameter");

		internal static string Dependency_TooManyExports => GetResourceString("Dependency_TooManyExports");

		internal static string Dependency_ToStringFormat => GetResourceString("Dependency_ToStringFormat");

		internal static string ExportDescriptor_ToStringFormat => GetResourceString("ExportDescriptor_ToStringFormat");

		internal static string Formatter_None => GetResourceString("Formatter_None");

		internal static string NotImplemented_MetadataCycles => GetResourceString("NotImplemented_MetadataCycles");

		internal static string CardinalityMismatch_TooManyExports => GetResourceString("CardinalityMismatch_TooManyExports");

		internal static string Diagnostic_ThrowingException => GetResourceString("Diagnostic_ThrowingException");

		internal static string ExportDescriptor_DependencyErrorContract => GetResourceString("ExportDescriptor_DependencyErrorContract");

		internal static string ExportDescriptor_DependencyErrorLine => GetResourceString("ExportDescriptor_DependencyErrorLine");

		internal static string ExportDescriptor_UnsupportedCycle => GetResourceString("ExportDescriptor_UnsupportedCycle");

		internal static string Component_NotCreatableOutsideSharingBoundary => GetResourceString("Component_NotCreatableOutsideSharingBoundary");

		internal static string MetadataViewProvider_InvalidViewImplementation => GetResourceString("MetadataViewProvider_InvalidViewImplementation");

		internal static string MetadataViewProvider_MissingMetadata => GetResourceString("MetadataViewProvider_MissingMetadata");

		internal static string Formatter_ListSeparatorWithSpace => GetResourceString("Formatter_ListSeparatorWithSpace");

		internal static string Sharing_Lock_Taken => GetResourceString("Sharing_Lock_Taken");

		internal static string Dependencies_Should_Be_Requested_Earlier => GetResourceString("Dependencies_Should_Be_Requested_Earlier");

		internal static string Key_Already_Exist => GetResourceString("Key_Already_Exist");

		internal static string Providers_Remain_To_Be_Queried => GetResourceString("Providers_Remain_To_Be_Queried");

		internal static string Diagnostic_InternalExceptionMessage => GetResourceString("Diagnostic_InternalExceptionMessage");

		internal static string Update_already_executed => GetResourceString("Update_already_executed");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Composition.Hosting
{
	public sealed class CompositionHost : CompositionContext, IDisposable
	{
		private static readonly string[] s_noBoundaries = Array.Empty<string>();

		private readonly LifetimeContext _rootLifetimeContext;

		private CompositionHost(LifetimeContext rootLifetimeContext)
		{
			_rootLifetimeContext = rootLifetimeContext;
		}

		public static CompositionHost CreateCompositionHost(params ExportDescriptorProvider[] providers)
		{
			return CreateCompositionHost((IEnumerable<ExportDescriptorProvider>)providers);
		}

		public static CompositionHost CreateCompositionHost(IEnumerable<ExportDescriptorProvider> providers)
		{
			if (providers == null)
			{
				throw new ArgumentNullException("providers");
			}
			return new CompositionHost(new LifetimeContext(new ExportDescriptorRegistry(new ExportDescriptorProvider[6]
			{
				new LazyExportDescriptorProvider(),
				new ExportFactoryExportDescriptorProvider(),
				new ImportManyExportDescriptorProvider(),
				new LazyWithMetadataExportDescriptorProvider(),
				new CurrentScopeExportDescriptorProvider(),
				new ExportFactoryWithMetadataExportDescriptorProvider()
			}.Concat(providers).ToArray()), s_noBoundaries));
		}

		public override bool TryGetExport(CompositionContract contract, out object export)
		{
			return ((CompositionContext)_rootLifetimeContext).TryGetExport(contract, ref export);
		}

		public void Dispose()
		{
			_rootLifetimeContext.Dispose();
		}
	}
}
namespace System.Composition.Hosting.Util
{
	internal static class Formatters
	{
		public static string ReadableList(IEnumerable<string> items)
		{
			if (items == null)
			{
				throw new ArgumentNullException("items");
			}
			string text = string.Join(System.SR.Formatter_ListSeparatorWithSpace, items.OrderBy((string t) => t));
			if (string.IsNullOrEmpty(text))
			{
				return System.SR.Formatter_None;
			}
			return text;
		}

		public static string Format(Type type)
		{
			if ((object)type == null)
			{
				throw new ArgumentNullException("type");
			}
			if (type.IsConstructedGenericType)
			{
				return FormatClosedGeneric(type);
			}
			return type.Name;
		}

		private static string FormatClosedGeneric(Type closedGenericType)
		{
			if ((object)closedGenericType == null)
			{
				throw new ArgumentNullException("closedGenericType");
			}
			if (!closedGenericType.IsConstructedGenericType)
			{
				throw new Exception(System.SR.Diagnostic_InternalExceptionMessage);
			}
			string text = closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`'));
			IEnumerable<string> values = closedGenericType.GenericTypeArguments.Select(Format);
			return text + "<" + string.Join(", ", values) + ">";
		}
	}
	internal static class MethodInfoExtensions
	{
		public static T CreateStaticDelegate<T>(this MethodInfo methodInfo)
		{
			return (T)(object)methodInfo.CreateDelegate(typeof(T));
		}
	}
	internal sealed class SmallSparseInitonlyArray
	{
		private sealed class Element
		{
			public int Index;

			public object Value;
		}

		private const int ElementsCapacity = 128;

		private const int ElementIndexMask = 127;

		private const int LocalOffsetMax = 3;

		private Element[] _elements;

		private SmallSparseInitonlyArray _overflow;

		public void Add(int index, object value)
		{
			if (_elements == null)
			{
				_elements = new Element[128];
			}
			Element element = new Element
			{
				Index = index,
				Value = value
			};
			int num = index & 0x7F;
			Element element2 = _elements[num];
			if (element2 == null)
			{
				_elements[num] = element;
				return;
			}
			if (element2.Index == index)
			{
				throw new ArgumentException(System.SR.Format(System.SR.Key_Already_Exist, index), "index");
			}
			for (int i = 1; i <= 3; i++)
			{
				int num2 = (index + i) & 0x7F;
				element2 = _elements[num2];
				if (element2 == null)
				{
					_elements[num2] = element;
					return;
				}
				if (element2.Index == index)
				{
					throw new ArgumentException(System.SR.Format(System.SR.Key_Already_Exist, index), "index");
				}
			}
			if (_overflow == null)
			{
				_overflow = new SmallSparseInitonlyArray();
			}
			_overflow.Add(index, value);
		}

		public bool TryGetValue(int index, out object value)
		{
			if (_elements == null)
			{
				value = null;
				return false;
			}
			int num = index & 0x7F;
			Element element = _elements[num];
			if (element != null && element.Index == index)
			{
				value = element.Value;
				return true;
			}
			for (int i = 1; i <= 3; i++)
			{
				element = _elements[(index + i) & 0x7F];
				if (element == null)
				{
					value = null;
					return false;
				}
				if (element.Index == index)
				{
					value = element.Value;
					return true;
				}
			}
			if (_overflow != null)
			{
				return _overflow.TryGetValue(index, out value);
			}
			value = null;
			return false;
		}
	}
}
namespace System.Composition.Hosting.Providers
{
	internal static class Constants
	{
		public const string SharingBoundaryImportMetadataConstraintName = "SharingBoundaryNames";

		public const string ImportManyImportMetadataConstraintName = "IsImportMany";
	}
}
namespace System.Composition.Hosting.Providers.Metadata
{
	internal static class MetadataViewProvider
	{
		private static readonly MethodInfo s_getMetadataValueMethod = typeof(MetadataViewProvider).GetTypeInfo().GetDeclaredMethod("GetMetadataValue");

		public static Func<IDictionary<string, object>, TMetadata> GetMetadataViewProvider<TMetadata>()
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_028e: Unknown result type (might be due to invalid IL or missing references)
			if (typeof(TMetadata) == typeof(IDictionary<string, object>))
			{
				return (IDictionary<string, object> m) => (TMetadata)m;
			}
			if (!typeof(TMetadata).GetTypeInfo().IsClass)
			{
				throw new CompositionFailedException(System.SR.Format(System.SR.MetadataViewProvider_InvalidViewImplementation, typeof(TMetadata).Name));
			}
			TypeInfo typeInfo = typeof(TMetadata).GetTypeInfo();
			ConstructorInfo constructorInfo = typeInfo.DeclaredConstructors.SingleOrDefault(delegate(ConstructorInfo ci)
			{
				ParameterInfo[] parameters = ci.GetParameters();
				return ci.IsPublic && parameters.Length == 1 && parameters[0].ParameterType == typeof(IDictionary<string, object>);
			});
			if (constructorInfo != null)
			{
				ParameterExpression parameterExpression = Expression.Parameter(typeof(IDictionary<string, object>), "metadata");
				return Expression.Lambda<Func<IDictionary<string, object>, TMetadata>>(Expression.New(constructorInfo, parameterExpression), new ParameterExpression[1] { parameterExpression }).Compile();
			}
			ConstructorInfo constructorInfo2 = typeInfo.DeclaredConstructors.SingleOrDefault((ConstructorInfo ci) => ci.IsPublic && ci.GetParameters().Length == 0);
			if (constructorInfo2 != null)
			{
				ParameterExpression parameterExpression2 = Expression.Parameter(typeof(IDictionary<string, object>), "metadata");
				ParameterExpression parameterExpression3 = Expression.Variable(typeof(TMetadata), "result");
				List<Expression> list = new List<Expression>();
				list.Add(Expression.Assign(parameterExpression3, Expression.New(constructorInfo2)));
				foreach (PropertyInfo item2 in typeof(TMetadata).GetTypeInfo().DeclaredProperties.Where((PropertyInfo prop) => prop.GetMethod != null && prop.GetMethod.IsPublic && !prop.GetMethod.IsStatic && prop.SetMethod != null && prop.SetMethod.IsPublic && !prop.SetMethod.IsStatic))
				{
					ConstantExpression arg = Expression.Constant(item2.GetCustomAttribute<DefaultValueAttribute>(inherit: false), typeof(DefaultValueAttribute));
					ConstantExpression arg2 = Expression.Constant(item2.Name, typeof(string));
					MethodInfo method = s_getMetadataValueMethod.MakeGenericMethod(item2.PropertyType);
					BinaryExpression item = Expression.Assign(Expression.Property(parameterExpression3, item2), Expression.Call(null, method, parameterExpression2, arg2, arg));
					list.Add(item);
				}
				list.Add(parameterExpression3);
				return Expression.Lambda<Func<IDictionary<string, object>, TMetadata>>(Expression.Block(new ParameterExpression[1] { parameterExpression3 }, list), new ParameterExpression[1] { parameterExpression2 }).Compile();
			}
			throw new CompositionFailedException(System.SR.Format(System.SR.MetadataViewProvider_InvalidViewImplementation, typeof(TMetadata).Name));
		}

		private static TValue GetMetadataValue<TValue>(IDictionary<string, object> metadata, string name, DefaultValueAttribute defaultValue)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			if (metadata.TryGetValue(name, out var value))
			{
				return (TValue)value;
			}
			if (defaultValue != null)
			{
				return (TValue)defaultValue.Value;
			}
			throw new CompositionFailedException(System.SR.Format(System.SR.MetadataViewProvider_MissingMetadata, name));
		}
	}
}
namespace System.Composition.Hosting.Providers.Lazy
{
	internal sealed class LazyExportDescriptorProvider : ExportDescriptorProvider
	{
		private static readonly MethodInfo s_getLazyDefinitionsMethod = typeof(LazyExportDescriptorProvider).GetTypeInfo().GetDeclaredMethod("GetLazyDefinitions");

		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract exportKey, DependencyAccessor definitionAccessor)
		{
			if (!exportKey.ContractType.IsConstructedGenericType || exportKey.ContractType.GetGenericTypeDefinition() != typeof(Lazy<>))
			{
				return ExportDescriptorProvider.NoExportDescriptors;
			}
			return (ExportDescriptorPromise[])s_getLazyDefinitionsMethod.MakeGenericMethod(exportKey.ContractType.GenericTypeArguments[0]).CreateStaticDelegate<Func<CompositionContract, DependencyAccessor, object>>()(exportKey, definitionAccessor);
		}

		private static ExportDescriptorPromise[] GetLazyDefinitions<TValue>(CompositionContract lazyContract, DependencyAccessor definitionAccessor)
		{
			return (from d in definitionAccessor.ResolveDependencies("value", lazyContract.ChangeType(typeof(TValue)), isPrerequisite: false)
				select new ExportDescriptorPromise(lazyContract, Formatters.Format(typeof(Lazy<TValue>)), isShared: false, () => new CompositionDependency[1] { d }, delegate
				{
					ExportDescriptor descriptor = d.Target.GetDescriptor();
					CompositeActivator da = descriptor.Activator;
					return ExportDescriptor.Create((LifetimeContext c, CompositionOperation o) => new Lazy<TValue>(() => (TValue)CompositionOperation.Run(c, da)), descriptor.Metadata);
				})).ToArray();
		}
	}
	internal sealed class LazyWithMetadataExportDescriptorProvider : ExportDescriptorProvider
	{
		private static readonly MethodInfo s_getLazyDefinitionsMethod = typeof(LazyWithMetadataExportDescriptorProvider).GetTypeInfo().GetDeclaredMethod("GetLazyDefinitions");

		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract exportKey, DependencyAccessor definitionAccessor)
		{
			if (!exportKey.ContractType.IsConstructedGenericType || exportKey.ContractType.GetGenericTypeDefinition() != typeof(Lazy<, >))
			{
				return ExportDescriptorProvider.NoExportDescriptors;
			}
			Type[] genericTypeArguments = exportKey.ContractType.GenericTypeArguments;
			return (ExportDescriptorPromise[])s_getLazyDefinitionsMethod.MakeGenericMethod(genericTypeArguments[0], genericTypeArguments[1]).CreateStaticDelegate<Func<CompositionContract, DependencyAccessor, object>>()(exportKey, definitionAccessor);
		}

		private static ExportDescriptorPromise[] GetLazyDefinitions<TValue, TMetadata>(CompositionContract lazyContract, DependencyAccessor definitionAccessor)
		{
			Func<IDictionary<string, object>, TMetadata> metadataProvider = MetadataViewProvider.GetMetadataViewProvider<TMetadata>();
			return (from d in definitionAccessor.ResolveDependencies("value", lazyContract.ChangeType(typeof(TValue)), isPrerequisite: false)
				select new ExportDescriptorPromise(lazyContract, Formatters.Format(typeof(Lazy<TValue, TMetadata>)), isShared: false, () => new CompositionDependency[1] { d }, delegate
				{
					ExportDescriptor dsc = d.Target.GetDescriptor();
					CompositeActivator da = dsc.Activator;
					return ExportDescriptor.Create((LifetimeContext c, CompositionOperation o) => new Lazy<TValue, TMetadata>(() => (TValue)CompositionOperation.Run(c, da), metadataProvider(dsc.Metadata)), dsc.Metadata);
				})).ToArray();
		}
	}
}
namespace System.Composition.Hosting.Providers.ImportMany
{
	internal sealed class ImportManyExportDescriptorProvider : ExportDescriptorProvider
	{
		private static readonly MethodInfo s_getImportManyDefinitionMethod = typeof(ImportManyExportDescriptorProvider).GetTypeInfo().GetDeclaredMethod("GetImportManyDescriptor");

		private static readonly Type[] s_supportedContractTypes = new Type[3]
		{
			typeof(IList<>),
			typeof(ICollection<>),
			typeof(IEnumerable<>)
		};

		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor definitionAccessor)
		{
			if (!contract.ContractType.IsArray && (!contract.ContractType.IsConstructedGenericType || !s_supportedContractTypes.Contains(contract.ContractType.GetGenericTypeDefinition())))
			{
				return ExportDescriptorProvider.NoExportDescriptors;
			}
			bool flag = default(bool);
			CompositionContract val = default(CompositionContract);
			if (!contract.TryUnwrapMetadataConstraint<bool>("IsImportMany", ref flag, ref val))
			{
				return ExportDescriptorProvider.NoExportDescriptors;
			}
			Type type = (contract.ContractType.IsArray ? contract.ContractType.GetElementType() : contract.ContractType.GenericTypeArguments[0]);
			CompositionContract arg = val.ChangeType(type);
			Func<CompositionContract, CompositionContract, DependencyAccessor, object> func = s_getImportManyDefinitionMethod.MakeGenericMethod(type).CreateStaticDelegate<Func<CompositionContract, CompositionContract, DependencyAccessor, object>>();
			return new ExportDescriptorPromise[1] { (ExportDescriptorPromise)func(contract, arg, definitionAccessor) };
		}

		private static ExportDescriptorPromise GetImportManyDescriptor<TElement>(CompositionContract importManyContract, CompositionContract elementContract, DependencyAccessor definitionAccessor)
		{
			return new ExportDescriptorPromise(importManyContract, typeof(TElement[]).Name, isShared: false, () => definitionAccessor.ResolveDependencies("item", elementContract, isPrerequisite: true), delegate(IEnumerable<CompositionDependency> d)
			{
				ExportDescriptor[] dependentDescriptors = d.Select((CompositionDependency el) => el.Target.GetDescriptor()).ToArray();
				return ExportDescriptor.Create((LifetimeContext c, CompositionOperation o) => dependentDescriptors.Select((ExportDescriptor e) => (TElement)e.Activator(c, o)).ToArray(), ExportDescriptorProvider.NoMetadata);
			});
		}
	}
}
namespace System.Composition.Hosting.Providers.ExportFactory
{
	internal sealed class ExportFactoryExportDescriptorProvider : ExportDescriptorProvider
	{
		private static readonly MethodInfo s_getExportFactoryDefinitionsMethod = typeof(ExportFactoryExportDescriptorProvider).GetTypeInfo().GetDeclaredMethod("GetExportFactoryDescriptors");

		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract exportKey, DependencyAccessor definitionAccessor)
		{
			if (!exportKey.ContractType.IsConstructedGenericType || exportKey.ContractType.GetGenericTypeDefinition() != typeof(ExportFactory<>))
			{
				return ExportDescriptorProvider.NoExportDescriptors;
			}
			return (ExportDescriptorPromise[])s_getExportFactoryDefinitionsMethod.MakeGenericMethod(exportKey.ContractType.GenericTypeArguments[0]).CreateStaticDelegate<Func<CompositionContract, DependencyAccessor, object>>()(exportKey, definitionAccessor);
		}

		private static ExportDescriptorPromise[] GetExportFactoryDescriptors<TProduct>(CompositionContract exportFactoryContract, DependencyAccessor definitionAccessor)
		{
			CompositionContract contract = exportFactoryContract.ChangeType(typeof(TProduct));
			string[] boundaries = Array.Empty<string>();
			IEnumerable<string> enumerable = default(IEnumerable<string>);
			CompositionContract val = default(CompositionContract);
			if (exportFactoryContract.TryUnwrapMetadataConstraint<IEnumerable<string>>("SharingBoundaryNames", ref enumerable, ref val))
			{
				contract = val.ChangeType(typeof(TProduct));
				boundaries = (enumerable ?? Array.Empty<string>()).ToArray();
			}
			return (from d in definitionAccessor.ResolveDependencies("product", contract, isPrerequisite: false)
				select new ExportDescriptorPromise(exportFactoryContract, Formatters.Format(typeof(ExportFactory<TProduct>)), isShared: false, () => new CompositionDependency[1] { d }, delegate
				{
					ExportDescriptor descriptor = d.Target.GetDescriptor();
					CompositeActivator da = descriptor.Activator;
					return ExportDescriptor.Create((LifetimeContext c, CompositionOperation o) => new ExportFactory<TProduct>((Func<Tuple<TProduct, Action>>)delegate
					{
						LifetimeContext lifetimeContext = new LifetimeContext(c, boundaries);
						return Tuple.Create<TProduct, Action>((TProduct)CompositionOperation.Run(lifetimeContext, da), lifetimeContext.Dispose);
					}), descriptor.Metadata);
				})).ToArray();
		}
	}
	internal sealed class ExportFactoryWithMetadataExportDescriptorProvider : ExportDescriptorProvider
	{
		private static readonly MethodInfo s_getLazyDefinitionsMethod = typeof(ExportFactoryWithMetadataExportDescriptorProvider).GetTypeInfo().GetDeclaredMethod("GetExportFactoryDescriptors");

		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor definitionAccessor)
		{
			if (!contract.ContractType.IsConstructedGenericType || contract.ContractType.GetGenericTypeDefinition() != typeof(ExportFactory<, >))
			{
				return ExportDescriptorProvider.NoExportDescriptors;
			}
			Type[] genericTypeArguments = contract.ContractType.GenericTypeArguments;
			return (ExportDescriptorPromise[])s_getLazyDefinitionsMethod.MakeGenericMethod(genericTypeArguments[0], genericTypeArguments[1]).CreateStaticDelegate<Func<CompositionContract, DependencyAccessor, object>>()(contract, definitionAccessor);
		}

		private static ExportDescriptorPromise[] GetExportFactoryDescriptors<TProduct, TMetadata>(CompositionContract exportFactoryContract, DependencyAccessor definitionAccessor)
		{
			CompositionContract contract = exportFactoryContract.ChangeType(typeof(TProduct));
			string[] boundaries = Array.Empty<string>();
			IEnumerable<string> enumerable = default(IEnumerable<string>);
			CompositionContract val = default(CompositionContract);
			if (exportFactoryContract.TryUnwrapMetadataConstraint<IEnumerable<string>>("SharingBoundaryNames", ref enumerable, ref val))
			{
				contract = val.ChangeType(typeof(TProduct));
				boundaries = (enumerable ?? Array.Empty<string>()).ToArray();
			}
			Func<IDictionary<string, object>, TMetadata> metadataProvider = MetadataViewProvider.GetMetadataViewProvider<TMetadata>();
			return (from d in definitionAccessor.ResolveDependencies("product", contract, isPrerequisite: false)
				select new ExportDescriptorPromise(exportFactoryContract, typeof(ExportFactory<TProduct, TMetadata>).Name, isShared: false, () => new CompositionDependency[1] { d }, delegate
				{
					ExportDescriptor dsc = d.Target.GetDescriptor();
					return ExportDescriptor.Create((LifetimeContext c, CompositionOperation o) => new ExportFactory<TProduct, TMetadata>((Func<Tuple<TProduct, Action>>)delegate
					{
						LifetimeContext lifetimeContext = new LifetimeContext(c, boundaries);
						return Tuple.Create<TProduct, Action>((TProduct)CompositionOperation.Run(lifetimeContext, dsc.Activator), lifetimeContext.Dispose);
					}, metadataProvider(dsc.Metadata)), dsc.Metadata);
				})).ToArray();
		}
	}
}
namespace System.Composition.Hosting.Providers.CurrentScope
{
	internal sealed class CurrentScopeExportDescriptorProvider : ExportDescriptorProvider
	{
		private static readonly CompositionContract s_currentScopeContract = new CompositionContract(typeof(CompositionContext));

		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor definitionAccessor)
		{
			if (!((object)contract).Equals((object?)s_currentScopeContract))
			{
				return ExportDescriptorProvider.NoExportDescriptors;
			}
			return new ExportDescriptorPromise[1]
			{
				new ExportDescriptorPromise(contract, "CompositionContext", isShared: true, ExportDescriptorProvider.NoDependencies, (IEnumerable<CompositionDependency> _) => ExportDescriptor.Create((LifetimeContext c, CompositionOperation o) => c, ExportDescriptorProvider.NoMetadata))
			};
		}
	}
}
namespace System.Composition.Hosting.Core
{
	public delegate object CompositeActivator(LifetimeContext context, CompositionOperation operation);
	public class CompositionDependency
	{
		private readonly ExportDescriptorPromise _target;

		private readonly bool _isPrerequisite;

		private readonly object _site;

		private readonly CompositionContract _contract;

		private readonly ExportDescriptorPromise[] _oversuppliedTargets;

		public ExportDescriptorPromise Target => _target;

		public bool IsPrerequisite => _isPrerequisite;

		public object Site => _site;

		public CompositionContract Contract => _contract;

		internal bool IsError => _target == null;

		public static CompositionDependency Satisfied(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site)
		{
			if (contract == null)
			{
				throw new ArgumentNullException("contract");
			}
			if (target == null)
			{
				throw new ArgumentNullException("target");
			}
			if (site == null)
			{
				throw new ArgumentNullException("site");
			}
			return new CompositionDependency(contract, target, isPrerequisite, site);
		}

		public static CompositionDependency Missing(CompositionContract contract, object site)
		{
			if (contract == null)
			{
				throw new ArgumentNullException("contract");
			}
			if (site == null)
			{
				throw new ArgumentNullException("site");
			}
			return new CompositionDependency(contract, site);
		}

		public static CompositionDependency Oversupplied(CompositionContract contract, IEnumerable<ExportDescriptorPromise> targets, object site)
		{
			if (contract == null)
			{
				throw new ArgumentNullException("contract");
			}
			if (targets == null)
			{
				throw new ArgumentNullException("targets");
			}
			if (site == null)
			{
				throw new ArgumentNullException("site");
			}
			return new CompositionDependency(contract, targets, site);
		}

		private CompositionDependency(CompositionContract contract, ExportDescriptorPromise target, bool isPrerequisite, object site)
		{
			_target = target;
			_isPrerequisite = isPrerequisite;
			_site = site;
			_contract = contract;
		}

		private CompositionDependency(CompositionContract contract, object site)
		{
			_contract = contract;
			_site = site;
		}

		private CompositionDependency(CompositionContract contract, IEnumerable<ExportDescriptorPromise> targets, object site)
		{
			_oversuppliedTargets = targets.ToArray();
			_site = site;
			_contract = contract;
		}

		public override string ToString()
		{
			if (IsError)
			{
				return Site.ToString();
			}
			return System.SR.Format(System.SR.Dependency_ToStringFormat, Site, Target.Contract, Target.Origin);
		}

		internal void DescribeError(StringBuilder message)
		{
			if (_oversuppliedTargets != null)
			{
				string arg = Formatters.ReadableList(_oversuppliedTargets.Select((ExportDescriptorPromise t) => System.SR.Format(System.SR.Dependency_QuoteParameter, t.Origin)));
				message.AppendFormat(System.SR.Dependency_TooManyExports, Contract, arg);
			}
			else
			{
				message.AppendFormat(System.SR.Dependency_ExportNotFound, Contract);
			}
		}
	}
	public sealed class CompositionOperation : IDisposable
	{
		private List<Action> _nonPrerequisiteActions;

		private List<Action> _postCompositionActions;

		private object _sharingLock;

		private CompositionOperation()
		{
		}

		public static object Run(LifetimeContext outermostLifetimeContext, CompositeActivator compositionRootActivator)
		{
			if (outermostLifetimeContext == null)
			{
				throw new ArgumentNullException("outermostLifetimeContext");
			}
			if (compositionRootActivator == null)
			{
				throw new ArgumentNullException("compositionRootActivator");
			}
			using CompositionOperation compositionOperation = new CompositionOperation();
			object result = compositionRootActivator(outermostLifetimeContext, compositionOperation);
			compositionOperation.Complete();
			return result;
		}

		public void AddNonPrerequisiteAction(Action action)
		{
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			if (_nonPrerequisiteActions == null)
			{
				_nonPrerequisiteActions = new List<Action>();
			}
			_nonPrerequisiteActions.Add(action);
		}

		public void AddPostCompositionAction(Action action)
		{
			if (action == null)
			{
				throw new ArgumentNullException("action");
			}
			if (_postCompositionActions == null)
			{
				_postCompositionActions = new List<Action>();
			}
			_postCompositionActions.Add(action);
		}

		internal void EnterSharingLock(object sharingLock)
		{
			if (_sharingLock == null)
			{
				_sharingLock = sharingLock;
				Monitor.Enter(sharingLock);
			}
			if (_sharingLock != sharingLock)
			{
				throw new Exception(System.SR.Sharing_Lock_Taken);
			}
		}

		private void Complete()
		{
			while (_nonPrerequisiteActions != null)
			{
				RunAndClearActions();
			}
			if (_postCompositionActions == null)
			{
				return;
			}
			foreach (Action postCompositionAction in _postCompositionActions)
			{
				postCompositionAction();
			}
			_postCompositionActions = null;
		}

		private void RunAndClearActions()
		{
			List<Action> nonPrerequisiteActions = _nonPrerequisiteActions;
			_nonPrerequisiteActions = null;
			foreach (Action item in nonPrerequisiteActions)
			{
				item();
			}
		}

		public void Dispose()
		{
			if (_sharingLock != null)
			{
				Monitor.Exit(_sharingLock);
			}
		}
	}
	internal sealed class CycleBreakingExportDescriptor : ExportDescriptor
	{
		private readonly Lazy<ExportDescriptor> _exportDescriptor;

		public override CompositeActivator Activator
		{
			get
			{
				if (!_exportDescriptor.IsValueCreated)
				{
					return Activate;
				}
				return _exportDescriptor.Value.Activator;
			}
		}

		public override IDictionary<string, object> Metadata
		{
			get
			{
				if (!_exportDescriptor.IsValueCreated)
				{
					return new CycleBreakingMetadataDictionary(_exportDescriptor);
				}
				return _exportDescriptor.Value.Metadata;
			}
		}

		public CycleBreakingExportDescriptor(Lazy<ExportDescriptor> exportDescriptor)
		{
			_exportDescriptor = exportDescriptor;
		}

		private object Activate(LifetimeContext context, CompositionOperation operation)
		{
			if (!_exportDescriptor.IsValueCreated)
			{
				throw new NotImplementedException(System.SR.NotImplemented_MetadataCycles);
			}
			return _exportDescriptor.Value.Activator(context, operation);
		}
	}
	internal sealed class CycleBreakingMetadataDictionary : IDictionary<string, object>, ICollection<KeyValuePair<string, object>>, IEnumerable<KeyValuePair<string, object>>, IEnumerable
	{
		private readonly Lazy<ExportDescriptor> _exportDescriptor;

		private IDictionary<string, object> ActualMetadata
		{
			get
			{
				if (!_exportDescriptor.IsValueCreated)
				{
					throw new NotImplementedException(System.SR.NotImplemented_MetadataCycles);
				}
				return _exportDescriptor.Value.Metadata;
			}
		}

		public ICollection<string> Keys => ActualMetadata.Keys;

		public ICollection<object> Values => ActualMetadata.Values;

		public object this[string key]
		{
			get
			{
				return ActualMetadata[key];
			}
			set
			{
				ActualMetadata[key] = value;
			}
		}

		public int Count => ActualMetadata.Count;

		public bool IsReadOnly => ActualMetadata.IsReadOnly;

		public CycleBreakingMetadataDictionary(Lazy<ExportDescriptor> exportDescriptor)
		{
			_exportDescriptor = exportDescriptor;
		}

		public void Add(string key, object value)
		{
			ActualMetadata.Add(key, value);
		}

		public bool ContainsKey(string key)
		{
			return ActualMetadata.ContainsKey(key);
		}

		public bool Remove(string key)
		{
			return ActualMetadata.Remove(key);
		}

		public bool TryGetValue(string key, out object value)
		{
			return ActualMetadata.TryGetValue(key, out value);
		}

		public void Add(KeyValuePair<string, object> item)
		{
			ActualMetadata.Add(item);
		}

		public void Clear()
		{
			ActualMetadata.Clear();
		}

		public bool Contains(KeyValuePair<string, object> item)
		{
			return ActualMetadata.Contains(item);
		}

		public void CopyTo(KeyValuePair<string, object>[] array, int arrayIndex)
		{
			ActualMetadata.CopyTo(array, arrayIndex);
		}

		public bool Remove(KeyValuePair<string, object> item)
		{
			return ActualMetadata.Remove(item);
		}

		public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
		{
			return ActualMetadata.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IEnumerable)ActualMetadata).GetEnumerator();
		}
	}
	public abstract class DependencyAccessor
	{
		protected abstract IEnumerable<ExportDescriptorPromise> GetPromises(CompositionContract exportKey);

		public IEnumerable<CompositionDependency> ResolveDependencies(object site, CompositionContract contract, bool isPrerequisite)
		{
			ExportDescriptorPromise[] array = GetPromises(contract).ToArray();
			CompositionDependency[] array2 = new CompositionDependency[array.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array2[i] = CompositionDependency.Satisfied(contract, array[i], isPrerequisite, site);
			}
			return array2;
		}

		public CompositionDependency ResolveRequiredDependency(object site, CompositionContract contract, bool isPrerequisite)
		{
			if (!TryResolveOptionalDependency(site, contract, isPrerequisite, out var dependency))
			{
				return CompositionDependency.Missing(contract, site);
			}
			return dependency;
		}

		public bool TryResolveOptionalDependency(object site, CompositionContract contract, bool isPrerequisite, out CompositionDependency dependency)
		{
			ExportDescriptorPromise[] array = GetPromises(contract).ToArray();
			if (array.Length == 0)
			{
				dependency = null;
				return false;
			}
			if (array.Length != 1)
			{
				dependency = CompositionDependency.Oversupplied(contract, array, site);
				return true;
			}
			dependency = CompositionDependency.Satisfied(contract, array[0], isPrerequisite, site);
			return true;
		}
	}
	internal sealed class DirectExportDescriptor : ExportDescriptor
	{
		private readonly CompositeActivator _activator;

		private readonly IDictionary<string, object> _metadata;

		public override CompositeActivator Activator => _activator;

		public override IDictionary<string, object> Metadata => _metadata;

		public DirectExportDescriptor(CompositeActivator activator, IDictionary<string, object> metadata)
		{
			if (activator == null)
			{
				throw new ArgumentNullException("activator");
			}
			if (metadata == null)
			{
				throw new ArgumentNullException("metadata");
			}
			_activator = activator;
			_metadata = metadata;
		}
	}
	public abstract class ExportDescriptor
	{
		public abstract CompositeActivator Activator { get; }

		public abstract IDictionary<string, object> Metadata { get; }

		public static ExportDescriptor Create(CompositeActivator activator, IDictionary<string, object> metadata)
		{
			return new DirectExportDescriptor(activator, metadata);
		}
	}
	public class ExportDescriptorPromise
	{
		private readonly string _origin;

		private readonly bool _isShared;

		private readonly Lazy<ReadOnlyCollection<CompositionDependency>> _dependencies;

		private readonly Lazy<ExportDescriptor> _descriptor;

		private readonly CompositionContract _contract;

		private bool _creating;

		public string Origin => _origin;

		public bool IsShared => _isShared;

		public ReadOnlyCollection<CompositionDependency> Dependencies => _dependencies.Value;

		public CompositionContract Contract => _contract;

		public ExportDescriptorPromise(CompositionContract contract, string origin, bool isShared, Func<IEnumerable<CompositionDependency>> dependencies, Func<IEnumerable<CompositionDependency>, ExportDescriptor> getDescriptor)
		{
			ExportDescriptorPromise exportDescriptorPromise = this;
			_contract = contract;
			_origin = origin;
			_isShared = isShared;
			_dependencies = new Lazy<ReadOnlyCollection<CompositionDependency>>(() => new ReadOnlyCollection<CompositionDependency>(dependencies().ToList()), isThreadSafe: false);
			_descriptor = new Lazy<ExportDescriptor>(() => getDescriptor(exportDescriptorPromise._dependencies.Value), isThreadSafe: false);
		}

		public ExportDescriptor GetDescriptor()
		{
			if (_creating && !_descriptor.IsValueCreated)
			{
				return new CycleBreakingExportDescriptor(_descriptor);
			}
			_creating = true;
			try
			{
				return _descriptor.Value ?? throw new ArgumentNullException("descriptor");
			}
			finally
			{
				_creating = false;
			}
		}

		public override string ToString()
		{
			return System.SR.Format(System.SR.ExportDescriptor_ToStringFormat, Contract, Origin);
		}
	}
	public abstract class ExportDescriptorProvider
	{
		protected static readonly IEnumerable<ExportDescriptorPromise> NoExportDescriptors = Enumerable.Empty<ExportDescriptorPromise>();

		protected static readonly IDictionary<string, object> NoMetadata = new ReadOnlyDictionary<string, object>(new Dictionary<string, object>());

		protected static readonly Func<IEnumerable<CompositionDependency>> NoDependencies = Enumerable.Empty<CompositionDependency>;

		public abstract IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor);
	}
	internal sealed class ExportDescriptorRegistry
	{
		private readonly object _thisLock = new object();

		private readonly ExportDescriptorProvider[] _exportDescriptorProviders;

		private volatile Dictionary<CompositionContract, ExportDescriptor[]> _partDefinitions = new Dictionary<CompositionContract, ExportDescriptor[]>();

		public ExportDescriptorRegistry(ExportDescriptorProvider[] exportDescriptorProviders)
		{
			_exportDescriptorProviders = exportDescriptorProviders;
		}

		public bool TryGetSingleForExport(CompositionContract exportKey, out ExportDescriptor defaultForExport)
		{
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			if (!_partDefinitions.TryGetValue(exportKey, out var value))
			{
				lock (_thisLock)
				{
					if (!_partDefinitions.ContainsKey(exportKey))
					{
						Dictionary<CompositionContract, ExportDescriptor[]> partDefinitions = new Dictionary<CompositionContract, ExportDescriptor[]>(_partDefinitions);
						new ExportDescriptorRegistryUpdate(partDefinitions, _exportDescriptorProviders).Execute(exportKey);
						_partDefinitions = partDefinitions;
					}
				}
				value = _partDefinitions[exportKey];
			}
			if (value.Length == 0)
			{
				defaultForExport = null;
				return false;
			}
			if (value.Length != 1)
			{
				throw new CompositionFailedException(System.SR.Format(System.SR.CardinalityMismatch_TooManyExports, exportKey));
			}
			defaultForExport = value[0];
			return true;
		}
	}
	internal sealed class ExportDescriptorRegistryUpdate : DependencyAccessor
	{
		private readonly IDictionary<CompositionContract, ExportDescriptor[]> _partDefinitions;

		private readonly ExportDescriptorProvider[] _exportDescriptorProviders;

		private readonly Dictionary<CompositionContract, UpdateResult> _updateResults = new Dictionary<CompositionContract, UpdateResult>();

		private static readonly CompositionDependency[] s_noDependenciesValue = Array.Empty<CompositionDependency>();

		private static readonly Func<CompositionDependency[]> s_noDependencies = () => s_noDependenciesValue;

		private bool _updateFinished;

		public ExportDescriptorRegistryUpdate(IDictionary<CompositionContract, ExportDescriptor[]> partDefinitions, ExportDescriptorProvider[] exportDescriptorProviders)
		{
			_partDefinitions = partDefinitions;
			_exportDescriptorProviders = exportDescriptorProviders;
		}

		public void Execute(CompositionContract contract)
		{
			if (_updateFinished)
			{
				throw new InvalidOperationException(System.SR.Update_already_executed);
			}
			if (TryResolveOptionalDependency("initial request", contract, isPrerequisite: true, out var dependency))
			{
				HashSet<ExportDescriptorPromise> @checked = new HashSet<ExportDescriptorPromise>();
				Stack<CompositionDependency> checking = new Stack<CompositionDependency>();
				CheckTarget(dependency, @checked, checking);
			}
			_updateFinished = true;
			foreach (KeyValuePair<CompositionContract, UpdateResult> updateResult in _updateResults)
			{
				CompositionContract key = updateResult.Key;
				ExportDescriptor[] value = (from cb in updateResult.Value.GetResults()
					select cb.GetDescriptor()).ToArray();
				_partDefinitions.Add(key, value);
			}
		}

		private void CheckTarget(CompositionDependency dependency, HashSet<ExportDescriptorPromise> @checked, Stack<CompositionDependency> checking)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (dependency.IsError)
			{
				StringBuilder stringBuilder = new StringBuilder();
				dependency.DescribeError(stringBuilder);
				stringBuilder.AppendLine();
				stringBuilder.Append((object?)DescribeCompositionStack(dependency, checking));
				throw new CompositionFailedException(stringBuilder.ToString());
			}
			if (@checked.Contains(dependency.Target))
			{
				return;
			}
			@checked.Add(dependency.Target);
			checking.Push(dependency);
			foreach (CompositionDependency dependency2 in dependency.Target.Dependencies)
			{
				CheckDependency(dependency2, @checked, checking);
			}
			checking.Pop();
		}

		private void CheckDependency(CompositionDependency dependency, HashSet<ExportDescriptorPromise> @checked, Stack<CompositionDependency> checking)
		{
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			if (@checked.Contains(dependency.Target))
			{
				bool flag = false;
				bool flag2 = !dependency.IsPrerequisite;
				foreach (CompositionDependency item in checking)
				{
					if (item.Target.IsShared)
					{
						flag = true;
					}
					if (flag && flag2)
					{
						break;
					}
					if (item.Target.Equals(dependency.Target))
					{
						StringBuilder stringBuilder = new StringBuilder();
						stringBuilder.AppendFormat(System.SR.ExportDescriptor_UnsupportedCycle, dependency.Target.Origin);
						stringBuilder.AppendLine();
						stringBuilder.Append((object?)DescribeCompositionStack(dependency, checking));
						throw new CompositionFailedException(stringBuilder.ToString());
					}
					if (!item.IsPrerequisite)
					{
						flag2 = true;
					}
				}
			}
			CheckTarget(dependency, @checked, checking);
		}

		private static StringBuilder DescribeCompositionStack(CompositionDependency import, Stack<CompositionDependency> dependencies)
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (dependencies.Count == 0 || dependencies.Peek() == null)
			{
				return stringBuilder;
			}
			foreach (CompositionDependency dependency in dependencies)
			{
				stringBuilder.AppendFormat(System.SR.ExportDescriptor_DependencyErrorLine, import.Site, dependency.Target.Origin);
				stringBuilder.AppendLine();
				import = dependency;
			}
			stringBuilder.AppendFormat(System.SR.ExportDescriptor_DependencyErrorContract, import.Contract);
			return stringBuilder;
		}

		protected override IEnumerable<ExportDescriptorPromise> GetPromises(CompositionContract contract)
		{
			if (_updateFinished)
			{
				throw new Exception(System.SR.Dependencies_Should_Be_Requested_Earlier);
			}
			if (_partDefinitions.TryGetValue(contract, out var value))
			{
				return value.Select((ExportDescriptor d) => new ExportDescriptorPromise(contract, "Preexisting", isShared: false, s_noDependencies, (IEnumerable<CompositionDependency> _) => d)).ToArray();
			}
			if (!_updateResults.TryGetValue(contract, out var value2))
			{
				value2 = new UpdateResult(_exportDescriptorProviders);
				_updateResults.Add(contract, value2);
			}
			ExportDescriptorProvider provider;
			while (value2.TryDequeueNextProvider(out provider))
			{
				foreach (ExportDescriptorPromise exportDescriptor in provider.GetExportDescriptors(contract, this))
				{
					value2.AddPromise(exportDescriptor);
				}
			}
			return value2.GetResults();
		}
	}
	public sealed class LifetimeContext : CompositionContext, IDisposable
	{
		private readonly LifetimeContext _root;

		private readonly LifetimeContext _parent;

		private readonly object _sharingLock = new object();

		private SmallSparseInitonlyArray _sharedPartInstances;

		private SmallSparseInitonlyArray _instancesUndergoingInitialization;

		private readonly object _boundPartLock = new object();

		private List<IDisposable> _boundPartInstances = new List<IDisposable>(0);

		private readonly string[] _sharingBoundaries;

		private readonly ExportDescriptorRegistry _partRegistry;

		private static int s_nextSharingId = -1;

		public static int AllocateSharingId()
		{
			return Interlocked.Increment(ref s_nextSharingId);
		}

		internal LifetimeContext(ExportDescriptorRegistry partRegistry, string[] sharingBoundaries)
		{
			_root = this;
			_sharingBoundaries = sharingBoundaries;
			_partRegistry = partRegistry;
		}

		internal LifetimeContext(LifetimeContext parent, string[] sharingBoundaries)
		{
			_parent = parent;
			_root = parent._root;
			_sharingBoundaries = sharingBoundaries;
			_partRegistry = parent._partRegistry;
		}

		public LifetimeContext FindContextWithin(string sharingBoundary)
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			if (sharingBoundary == null)
			{
				return _root;
			}
			for (LifetimeContext lifetimeContext = this; lifetimeContext != null; lifetimeContext = lifetimeContext._parent)
			{
				string[] sharingBoundaries = lifetimeContext._sharingBoundaries;
				for (int i = 0; i < sharingBoundaries.Length; i++)
				{
					if (sharingBoundaries[i] == sharingBoundary)
					{
						return lifetimeContext;
					}
				}
			}
			throw new CompositionFailedException(System.SR.Format(System.SR.Component_NotCreatableOutsideSharingBoundary, sharingBoundary));
		}

		public void Dispose()
		{
			IEnumerable<IDisposable> enumerable = null;
			lock (_boundPartLock)
			{
				if (_boundPartInstances != null)
				{
					enumerable = _boundPartInstances;
					_boundPartInstances = null;
				}
			}
			if (enumerable == null)
			{
				return;
			}
			foreach (IDisposable item in enumerable)
			{
				item.Dispose();
			}
		}

		public void AddBoundInstance(IDisposable instance)
		{
			lock (_boundPartLock)
			{
				if (_boundPartInstances == null)
				{
					throw new ObjectDisposedException(((object)this).ToString());
				}
				_boundPartInstances.Add(instance);
			}
		}

		public object GetOrCreate(int sharingId, CompositionOperation operation, CompositeActivator creator)
		{
			if (_sharedPartInstances != null && _sharedPartInstances.TryGetValue(sharingId, out var result))
			{
				return result;
			}
			operation.EnterSharingLock(_sharingLock);
			if (_sharedPartInstances == null)
			{
				_sharedPartInstances = new SmallSparseInitonlyArray();
				_instancesUndergoingInitialization = new SmallSparseInitonlyArray();
			}
			else if (_sharedPartInstances.TryGetValue(sharingId, out result))
			{
				return result;
			}
			if (_instancesUndergoingInitialization.TryGetValue(sharingId, out result))
			{
				return result;
			}
			result = creator(this, operation);
			_instancesUndergoingInitialization.Add(sharingId, result);
			operation.AddPostCompositionAction(delegate
			{
				_sharedPartInstances.Add(sharingId, result);
			});
			return result;
		}

		public override bool TryGetExport(CompositionContract contract, out object export)
		{
			if (!_partRegistry.TryGetSingleForExport(contract, out var defaultForExport))
			{
				export = null;
				return false;
			}
			export = CompositionOperation.Run(this, defaultForExport.Activator);
			return true;
		}

		public override string ToString()
		{
			if (_parent == null)
			{
				return "Root Lifetime Context";
			}
			if (_sharingBoundaries.Length == 0)
			{
				return "Non-sharing Lifetime Context";
			}
			return "Boundary for " + string.Join(", ", _sharingBoundaries);
		}
	}
	internal sealed class UpdateResult
	{
		private static readonly ExportDescriptorPromise[] s_noPromises = Array.Empty<ExportDescriptorPromise>();

		private readonly Queue<ExportDescriptorProvider> _remainingProviders;

		private readonly List<ExportDescriptorPromise> _providedDescriptors = new List<ExportDescriptorPromise>();

		private ExportDescriptorPromise[] _results;

		public UpdateResult(IEnumerable<ExportDescriptorProvider> providers)
		{
			_remainingProviders = new Queue<ExportDescriptorProvider>(providers);
		}

		public bool TryDequeueNextProvider(out ExportDescriptorProvider provider)
		{
			if (_remainingProviders.Count == 0)
			{
				provider = null;
				return false;
			}
			provider = _remainingProviders.Dequeue();
			return true;
		}

		public void AddPromise(ExportDescriptorPromise promise)
		{
			_results = null;
			_providedDescriptors.Add(promise);
		}

		public ExportDescriptorPromise[] GetResults()
		{
			if (_results == null)
			{
				if (_remainingProviders.Count != 0)
				{
					throw new Exception(System.SR.Providers_Remain_To_Be_Queried);
				}
				if (_providedDescriptors.Count == 0)
				{
					_results = s_noPromises;
				}
				_results = _providedDescriptors.ToArray();
			}
			return _results;
		}
	}
}

BepInEx/core/System.Composition.Runtime.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Composition.Hosting;
using System.Composition.Hosting.Core;
using System.Composition.Runtime.Util;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using FxResources.System.Composition.Runtime;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Composition.Runtime")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Contains runtime components of the Managed Extensibility Framework (MEF).")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Composition.Runtime")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.System.Composition.Runtime
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string CompositionContext_NoExportFoundForContract => GetResourceString("CompositionContext_NoExportFoundForContract");

		internal static string CompositionFailedDefaultExceptionMessage => GetResourceString("CompositionFailedDefaultExceptionMessage");

		internal static string Formatter_ListSeparatorWithSpace => GetResourceString("Formatter_ListSeparatorWithSpace");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Composition
{
	public abstract class CompositionContext
	{
		private const string ImportManyImportMetadataConstraintName = "IsImportMany";

		public abstract bool TryGetExport(CompositionContract contract, out object export);

		public TExport GetExport<TExport>()
		{
			return GetExport<TExport>(null);
		}

		public TExport GetExport<TExport>(string contractName)
		{
			return (TExport)GetExport(typeof(TExport), contractName);
		}

		public bool TryGetExport(Type exportType, out object export)
		{
			return TryGetExport(exportType, null, out export);
		}

		public bool TryGetExport(Type exportType, string contractName, out object export)
		{
			if (TryGetExport(new CompositionContract(exportType, contractName), out export))
			{
				return true;
			}
			export = null;
			return false;
		}

		public bool TryGetExport<TExport>(out TExport export)
		{
			return TryGetExport((string)null, out export);
		}

		public bool TryGetExport<TExport>(string contractName, out TExport export)
		{
			if (!TryGetExport(typeof(TExport), contractName, out var export2))
			{
				export = default(TExport);
				return false;
			}
			export = (TExport)export2;
			return true;
		}

		public object GetExport(Type exportType)
		{
			return GetExport(exportType, null);
		}

		public object GetExport(Type exportType, string contractName)
		{
			return GetExport(new CompositionContract(exportType, contractName));
		}

		public object GetExport(CompositionContract contract)
		{
			if (TryGetExport(contract, out var export))
			{
				return export;
			}
			throw new CompositionFailedException(System.SR.Format(System.SR.CompositionContext_NoExportFoundForContract, contract));
		}

		public IEnumerable<object> GetExports(Type exportType)
		{
			return GetExports(exportType, null);
		}

		public IEnumerable<object> GetExports(Type exportType, string contractName)
		{
			CompositionContract contract = new CompositionContract(exportType.MakeArrayType(), contractName, new Dictionary<string, object> { { "IsImportMany", true } });
			return (IEnumerable<object>)GetExport(contract);
		}

		public IEnumerable<TExport> GetExports<TExport>()
		{
			return GetExports<TExport>(null);
		}

		public IEnumerable<TExport> GetExports<TExport>(string contractName)
		{
			return (IEnumerable<TExport>)GetExports(typeof(TExport), contractName);
		}
	}
	public class ExportFactory<T>
	{
		private readonly Func<Tuple<T, Action>> _exportLifetimeContextCreator;

		public ExportFactory(Func<Tuple<T, Action>> exportCreator)
		{
			_exportLifetimeContextCreator = exportCreator ?? throw new ArgumentNullException("exportCreator");
		}

		public Export<T> CreateExport()
		{
			Tuple<T, Action> tuple = _exportLifetimeContextCreator();
			return new Export<T>(tuple.Item1, tuple.Item2);
		}
	}
	public class ExportFactory<T, TMetadata> : ExportFactory<T>
	{
		public TMetadata Metadata { get; }

		public ExportFactory(Func<Tuple<T, Action>> exportCreator, TMetadata metadata)
			: base(exportCreator)
		{
			Metadata = metadata;
		}
	}
	public sealed class Export<T> : IDisposable
	{
		private readonly Action _disposeAction;

		public T Value { get; }

		public Export(T value, Action disposeAction)
		{
			Value = value;
			_disposeAction = disposeAction;
		}

		public void Dispose()
		{
			_disposeAction?.Invoke();
		}
	}
}
namespace System.Composition.Runtime.Util
{
	internal static class Formatters
	{
		public static string Format(object value)
		{
			if (value != null)
			{
				if (!(value is string))
				{
					return value.ToString();
				}
				return $"\"{value}\"";
			}
			throw new ArgumentNullException("value");
		}

		public static string Format(Type type)
		{
			if ((object)type != null)
			{
				if (!type.IsConstructedGenericType)
				{
					return type.Name;
				}
				return FormatClosedGeneric(type);
			}
			throw new ArgumentNullException("type");
		}

		private static string FormatClosedGeneric(Type closedGenericType)
		{
			return closedGenericType.Name.Substring(0, closedGenericType.Name.IndexOf('`')) + "<" + string.Join(values: closedGenericType.GenericTypeArguments.Select(Format), separator: System.SR.Formatter_ListSeparatorWithSpace) + ">";
		}
	}
}
namespace System.Composition.Hosting
{
	public class CompositionFailedException : Exception
	{
		public CompositionFailedException()
			: base(System.SR.CompositionFailedDefaultExceptionMessage)
		{
		}

		public CompositionFailedException(string message)
			: base(message ?? System.SR.CompositionFailedDefaultExceptionMessage)
		{
		}

		public CompositionFailedException(string message, Exception innerException)
			: base(message ?? System.SR.CompositionFailedDefaultExceptionMessage, innerException)
		{
		}
	}
}
namespace System.Composition.Hosting.Core
{
	public sealed class CompositionContract
	{
		private readonly Type _contractType;

		private readonly string _contractName;

		private readonly IDictionary<string, object> _metadataConstraints;

		public Type ContractType => _contractType;

		public string ContractName => _contractName;

		public IEnumerable<KeyValuePair<string, object>> MetadataConstraints => _metadataConstraints;

		public CompositionContract(Type contractType)
			: this(contractType, null)
		{
		}

		public CompositionContract(Type contractType, string contractName)
			: this(contractType, contractName, null)
		{
		}

		public CompositionContract(Type contractType, string contractName, IDictionary<string, object> metadataConstraints)
		{
			if (contractType == null)
			{
				throw new ArgumentNullException("contractType");
			}
			if (metadataConstraints != null && metadataConstraints.Count == 0)
			{
				throw new ArgumentOutOfRangeException("metadataConstraints");
			}
			_contractType = contractType;
			_contractName = contractName;
			_metadataConstraints = metadataConstraints;
		}

		public override bool Equals(object obj)
		{
			if (obj is CompositionContract compositionContract && compositionContract._contractType.Equals(_contractType) && ((_contractName == null) ? (compositionContract._contractName == null) : _contractName.Equals(compositionContract._contractName)))
			{
				return ConstraintEqual(_metadataConstraints, compositionContract._metadataConstraints);
			}
			return false;
		}

		public override int GetHashCode()
		{
			int num = _contractType.GetHashCode();
			if (_contractName != null)
			{
				num ^= _contractName.GetHashCode();
			}
			if (_metadataConstraints != null)
			{
				num ^= ConstraintHashCode(_metadataConstraints);
			}
			return num;
		}

		public override string ToString()
		{
			string text = Formatters.Format(_contractType);
			if (_contractName != null)
			{
				text = text + " " + Formatters.Format(_contractName);
			}
			if (_metadataConstraints != null)
			{
				text += string.Format(" {{ {0} }}", string.Join(System.SR.Formatter_ListSeparatorWithSpace, _metadataConstraints.Select((KeyValuePair<string, object> kv) => kv.Key + " = " + Formatters.Format(kv.Value))));
			}
			return text;
		}

		public CompositionContract ChangeType(Type newContractType)
		{
			if (newContractType == null)
			{
				throw new ArgumentNullException("newContractType");
			}
			return new CompositionContract(newContractType, _contractName, _metadataConstraints);
		}

		public bool TryUnwrapMetadataConstraint<T>(string constraintName, out T constraintValue, out CompositionContract remainingContract)
		{
			if (constraintName == null)
			{
				throw new ArgumentNullException("constraintName");
			}
			constraintValue = default(T);
			remainingContract = null;
			if (_metadataConstraints == null)
			{
				return false;
			}
			if (!_metadataConstraints.TryGetValue(constraintName, out var value))
			{
				return false;
			}
			if (!(value is T))
			{
				return false;
			}
			constraintValue = (T)value;
			if (_metadataConstraints.Count == 1)
			{
				remainingContract = new CompositionContract(_contractType, _contractName);
			}
			else
			{
				Dictionary<string, object> dictionary = new Dictionary<string, object>(_metadataConstraints);
				dictionary.Remove(constraintName);
				remainingContract = new CompositionContract(_contractType, _contractName, dictionary);
			}
			return true;
		}

		internal static bool ConstraintEqual(IDictionary<string, object> first, IDictionary<string, object> second)
		{
			if (first == second)
			{
				return true;
			}
			if (first == null || second == null)
			{
				return false;
			}
			if (first.Count != second.Count)
			{
				return false;
			}
			foreach (KeyValuePair<string, object> item in first)
			{
				if (!second.TryGetValue(item.Key, out var value))
				{
					return false;
				}
				if (item.Value == null)
				{
					return value == null;
				}
				if (value == null)
				{
					return false;
				}
				if (item.Value is IEnumerable enumerable && !(enumerable is string))
				{
					if (!(value is IEnumerable source) || !enumerable.Cast<object>().SequenceEqual(source.Cast<object>()))
					{
						return false;
					}
				}
				else if (!item.Value.Equals(value))
				{
					return false;
				}
			}
			return true;
		}

		private static int ConstraintHashCode(IDictionary<string, object> metadata)
		{
			int num = -1;
			foreach (KeyValuePair<string, object> metadatum in metadata)
			{
				num ^= metadatum.Key.GetHashCode();
				if (metadatum.Value == null)
				{
					continue;
				}
				if (metadatum.Value is string text)
				{
					num ^= text.GetHashCode();
				}
				else if (metadatum.Value is IEnumerable enumerable)
				{
					foreach (object item in enumerable)
					{
						if (item != null)
						{
							num ^= item.GetHashCode();
						}
					}
				}
				else
				{
					num ^= metadatum.Value.GetHashCode();
				}
			}
			return num;
		}
	}
}

BepInEx/core/System.Composition.TypedParts.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Composition.Convention;
using System.Composition.Debugging;
using System.Composition.Hosting;
using System.Composition.Hosting.Core;
using System.Composition.TypedParts;
using System.Composition.TypedParts.ActivationFeatures;
using System.Composition.TypedParts.Discovery;
using System.Composition.TypedParts.Util;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using FxResources.System.Composition.TypedParts;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Composition.TypedParts")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides container configuration and some extension methods for the Managed Extensibility Framework (MEF).")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Composition.TypedParts")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("9.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.System.Composition.TypedParts
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string CompositionContextExtensions_MissingDependency => GetResourceString("CompositionContextExtensions_MissingDependency");

		internal static string ContainerConfiguration_DefaultConventionSet => GetResourceString("ContainerConfiguration_DefaultConventionSet");

		internal static string ContractHelpers_TooManyImports => GetResourceString("ContractHelpers_TooManyImports");

		internal static string DiscoveredPart_MultipleImportingConstructorsFound => GetResourceString("DiscoveredPart_MultipleImportingConstructorsFound");

		internal static string DiscoveredPart_NoImportingConstructorsFound => GetResourceString("DiscoveredPart_NoImportingConstructorsFound");

		internal static string OnImportsSatisfiedFeature_AttributeError => GetResourceString("OnImportsSatisfiedFeature_AttributeError");

		internal static string TypeInspector_ArgumentMismatch => GetResourceString("TypeInspector_ArgumentMismatch");

		internal static string TypeInspector_ContractNotAssignable => GetResourceString("TypeInspector_ContractNotAssignable");

		internal static string TypeInspector_ExportedContractTypeNotAssignable => GetResourceString("TypeInspector_ExportedContractTypeNotAssignable");

		internal static string TypeInspector_ExportNotCompatible => GetResourceString("TypeInspector_ExportNotCompatible");

		internal static string TypeInspector_NoExportNonGenericContract => GetResourceString("TypeInspector_NoExportNonGenericContract");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Numerics.Hashing
{
	internal static class HashHelpers
	{
		public static int Combine(int h1, int h2)
		{
			return (((h1 << 5) | (h1 >>> 27)) + h1) ^ h2;
		}
	}
}
namespace System.Composition
{
	public static class CompositionContextExtensions
	{
		private static readonly DirectAttributeContext s_directAttributeContext = new DirectAttributeContext();

		public static void SatisfyImports(this CompositionContext compositionContext, object objectWithLooseImports)
		{
			compositionContext.SatisfyImportsInternal(objectWithLooseImports, (AttributedModelProvider)(object)s_directAttributeContext);
		}

		public static void SatisfyImports(this CompositionContext compositionContext, object objectWithLooseImports, AttributedModelProvider conventions)
		{
			compositionContext.SatisfyImportsInternal(objectWithLooseImports, conventions);
		}

		private static void SatisfyImportsInternal(this CompositionContext exportProvider, object objectWithLooseImports, AttributedModelProvider conventions)
		{
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			if (exportProvider == null)
			{
				throw new ArgumentNullException("exportProvider");
			}
			if (objectWithLooseImports == null)
			{
				throw new ArgumentNullException("objectWithLooseImports");
			}
			if (conventions == null)
			{
				throw new ArgumentNullException("conventions");
			}
			object value = default(object);
			foreach (PropertyInfo runtimeProperty in objectWithLooseImports.GetType().GetRuntimeProperties())
			{
				PropertyImportSite site = new PropertyImportSite(runtimeProperty);
				Type propertyType = runtimeProperty.PropertyType;
				object[] declaredAttributes = conventions.GetDeclaredAttributes(runtimeProperty.DeclaringType, runtimeProperty);
				if (ContractHelpers.TryGetExplicitImportInfo(propertyType, declaredAttributes, site, out var importInfo))
				{
					if (exportProvider.TryGetExport(importInfo.Contract, ref value))
					{
						runtimeProperty.SetValue(objectWithLooseImports, value);
					}
					else if (!importInfo.AllowDefault)
					{
						throw new CompositionFailedException(System.SR.Format(System.SR.CompositionContextExtensions_MissingDependency, runtimeProperty.Name, objectWithLooseImports));
					}
				}
			}
			foreach (MethodInfo item in from m in objectWithLooseImports.GetType().GetRuntimeMethods()
				where m.CustomAttributes.Any((CustomAttributeData ca) => ca.AttributeType == typeof(OnImportsSatisfiedAttribute))
				select m)
			{
				item.Invoke(objectWithLooseImports, null);
			}
		}
	}
}
namespace System.Composition.TypedParts
{
	internal static class ContractHelpers
	{
		private const string ImportManyImportMetadataConstraintName = "IsImportMany";

		public static bool TryGetExplicitImportInfo(Type memberType, object[] attributes, object site, out ImportInfo importInfo)
		{
			if (attributes.Any((object a) => a is ImportAttribute || a is ImportManyAttribute))
			{
				importInfo = GetImportInfo(memberType, attributes, site);
				return true;
			}
			importInfo = null;
			return false;
		}

		public static ImportInfo GetImportInfo(Type memberType, object[] attributes, object site)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Expected O, but got Unknown
			//IL_0174: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0190: Expected O, but got Unknown
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			CompositionContract val = new CompositionContract(memberType);
			Dictionary<string, object> dictionary = null;
			bool allowDefault = false;
			int num = 0;
			foreach (object obj in attributes)
			{
				ImportAttribute val2 = (ImportAttribute)((obj is ImportAttribute) ? obj : null);
				if (val2 != null)
				{
					val = new CompositionContract(memberType, val2.ContractName);
					allowDefault = val2.AllowDefault;
					num++;
				}
				else
				{
					ImportManyAttribute val3 = (ImportManyAttribute)((obj is ImportManyAttribute) ? obj : null);
					if (val3 != null)
					{
						if (dictionary == null)
						{
							dictionary = new Dictionary<string, object>();
						}
						dictionary.Add("IsImportMany", true);
						val = new CompositionContract(memberType, val3.ContractName);
						num++;
					}
					else
					{
						ImportMetadataConstraintAttribute val4 = (ImportMetadataConstraintAttribute)((obj is ImportMetadataConstraintAttribute) ? obj : null);
						if (val4 != null)
						{
							if (dictionary == null)
							{
								dictionary = new Dictionary<string, object>();
							}
							dictionary.Add(val4.Name, val4.Value);
						}
					}
				}
				Type attrType = obj.GetType();
				if (((MemberInfo)attrType.GetTypeInfo()).GetCustomAttribute<MetadataAttributeAttribute>(inherit: true) == null)
				{
					continue;
				}
				foreach (PropertyInfo item in from p in attrType.GetRuntimeProperties()
					where p.GetMethod.IsPublic && p.DeclaringType == attrType && p.CanRead
					select p)
				{
					if (dictionary == null)
					{
						dictionary = new Dictionary<string, object>();
					}
					dictionary.Add(item.Name, item.GetValue(obj, null));
				}
			}
			if (num > 1)
			{
				throw new CompositionFailedException(System.SR.Format(System.SR.ContractHelpers_TooManyImports, site));
			}
			if (dictionary != null)
			{
				val = new CompositionContract(val.ContractType, val.ContractName, (IDictionary<string, object>)dictionary);
			}
			return new ImportInfo(val, allowDefault);
		}

		public static bool IsShared(IDictionary<string, object> partMetadata)
		{
			return partMetadata.ContainsKey("SharingBoundary");
		}
	}
	internal sealed class ImportInfo
	{
		private readonly CompositionContract _exportKey;

		private readonly bool _allowDefault;

		public bool AllowDefault => _allowDefault;

		public CompositionContract Contract => _exportKey;

		public ImportInfo(CompositionContract exportKey, bool allowDefault)
		{
			_exportKey = exportKey;
			_allowDefault = allowDefault;
		}
	}
	internal sealed class TypedPartExportDescriptorProvider : ExportDescriptorProvider
	{
		private readonly Dictionary<CompositionContract, ICollection<DiscoveredExport>> _discoveredParts = new Dictionary<CompositionContract, ICollection<DiscoveredExport>>();

		public TypedPartExportDescriptorProvider(IEnumerable<Type> types, AttributedModelProvider attributeContext)
		{
			ActivationFeature[] activationFeatures = CreateActivationFeatures(attributeContext);
			TypeInspector typeInspector = new TypeInspector(attributeContext, activationFeatures);
			foreach (Type type in types)
			{
				if (typeInspector.InspectTypeForPart(type.GetTypeInfo(), out var part))
				{
					AddDiscoveredPart(part);
				}
			}
		}

		private void AddDiscoveredPart(DiscoveredPart part)
		{
			foreach (DiscoveredExport discoveredExport in part.DiscoveredExports)
			{
				AddDiscoveredExport(discoveredExport);
			}
		}

		private void AddDiscoveredExport(DiscoveredExport export, CompositionContract contract = null)
		{
			CompositionContract key = contract ?? export.Contract;
			if (!_discoveredParts.TryGetValue(key, out var value))
			{
				value = new List<DiscoveredExport>();
				_discoveredParts.Add(key, value);
			}
			value.Add(export);
		}

		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor definitionAccessor)
		{
			DiscoverGenericParts(contract);
			DiscoverConstrainedParts(contract);
			if (!_discoveredParts.TryGetValue(contract, out var value))
			{
				return ExportDescriptorProvider.NoExportDescriptors;
			}
			if (!value.Any((DiscoveredExport x) => x.Metadata.Any()))
			{
				_discoveredParts.Remove(contract);
			}
			return value.Select((DiscoveredExport de) => de.GetExportDescriptorPromise(contract, definitionAccessor)).ToArray();
		}

		private void DiscoverConstrainedParts(CompositionContract contract)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c0: Expected O, but got Unknown
			if (contract.MetadataConstraints == null)
			{
				return;
			}
			CompositionContract val = new CompositionContract(contract.ContractType, contract.ContractName);
			DiscoverGenericParts(val);
			if (!_discoveredParts.TryGetValue(val, out var value))
			{
				return;
			}
			foreach (DiscoveredExport export in value)
			{
				Dictionary<string, object> dictionary = contract.MetadataConstraints.Where((KeyValuePair<string, object> c) => export.Metadata.ContainsKey(c.Key)).ToDictionary((KeyValuePair<string, object> c) => c.Key, (KeyValuePair<string, object> c) => export.Metadata[c.Key]);
				if (dictionary.Count != 0 && ((object)new CompositionContract(val.ContractType, val.ContractName, (IDictionary<string, object>)dictionary)).Equals((object?)contract))
				{
					AddDiscoveredExport(export, contract);
				}
			}
		}

		private void DiscoverGenericParts(CompositionContract contract)
		{
			if (!contract.ContractType.IsConstructedGenericType)
			{
				return;
			}
			Type genericTypeDefinition = contract.ContractType.GetGenericTypeDefinition();
			CompositionContract key = contract.ChangeType(genericTypeDefinition);
			if (!_discoveredParts.TryGetValue(key, out var value))
			{
				return;
			}
			Type[] genericTypeArguments = contract.ContractType.GenericTypeArguments;
			foreach (DiscoveredExport item in value)
			{
				if (item.Part.TryCloseGenericPart(genericTypeArguments, out var closed))
				{
					AddDiscoveredPart(closed);
				}
			}
		}

		private static ActivationFeature[] CreateActivationFeatures(AttributedModelProvider attributeContext)
		{
			return new ActivationFeature[4]
			{
				new DisposalFeature(),
				new PropertyInjectionFeature(attributeContext),
				new OnImportsSatisfiedFeature(attributeContext),
				new LifetimeFeature()
			};
		}

		internal static ActivationFeature[] DebugGetActivationFeatures(AttributedModelProvider attributeContext)
		{
			return CreateActivationFeatures(attributeContext);
		}
	}
}
namespace System.Composition.TypedParts.Util
{
	internal sealed class DirectAttributeContext : AttributedModelProvider
	{
		public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, MemberInfo member)
		{
			if (reflectedType == null)
			{
				throw new ArgumentNullException("reflectedType");
			}
			if (member == null)
			{
				throw new ArgumentNullException("member");
			}
			if (!(member is TypeInfo) && member.DeclaringType != reflectedType)
			{
				return Array.Empty<Attribute>();
			}
			return Attribute.GetCustomAttributes(member, inherit: false);
		}

		public override IEnumerable<Attribute> GetCustomAttributes(Type reflectedType, ParameterInfo parameter)
		{
			if (parameter == null)
			{
				throw new ArgumentNullException("parameter");
			}
			if (reflectedType == null)
			{
				throw new ArgumentNullException("reflectedType");
			}
			return Attribute.GetCustomAttributes(parameter, inherit: false);
		}
	}
}
namespace System.Composition.TypedParts.Discovery
{
	[DebuggerDisplay("{Contract}")]
	internal abstract class DiscoveredExport
	{
		private readonly CompositionContract _exportKey;

		private readonly IDictionary<string, object> _metadata;

		private DiscoveredPart _part;

		public CompositionContract Contract => _exportKey;

		public IDictionary<string, object> Metadata => _metadata;

		public DiscoveredPart Part
		{
			get
			{
				return _part;
			}
			set
			{
				_part = value;
			}
		}

		public DiscoveredExport(CompositionContract exportKey, IDictionary<string, object> metadata)
		{
			_exportKey = exportKey;
			_metadata = metadata;
		}

		public ExportDescriptorPromise GetExportDescriptorPromise(CompositionContract contract, DependencyAccessor definitionAccessor)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004e: Expected O, but got Unknown
			return new ExportDescriptorPromise(contract, Part.PartType.Name, Part.IsShared, (Func<IEnumerable<CompositionDependency>>)(() => Part.GetDependencies(definitionAccessor)), (Func<IEnumerable<CompositionDependency>, ExportDescriptor>)delegate(IEnumerable<CompositionDependency> deps)
			{
				CompositeActivator activator = Part.GetActivator(deps);
				return GetExportDescriptor(activator);
			});
		}

		protected abstract ExportDescriptor GetExportDescriptor(CompositeActivator partActivator);

		public abstract DiscoveredExport CloseGenericExport(TypeInfo closedPartType, Type[] genericArguments);
	}
	internal sealed class DiscoveredInstanceExport : DiscoveredExport
	{
		public DiscoveredInstanceExport(CompositionContract contract, IDictionary<string, object> metadata)
			: base(contract, metadata)
		{
		}

		protected override ExportDescriptor GetExportDescriptor(CompositeActivator partActivator)
		{
			return ExportDescriptor.Create(partActivator, base.Metadata);
		}

		public override DiscoveredExport CloseGenericExport(TypeInfo closedPartType, Type[] genericArguments)
		{
			Type type = base.Contract.ContractType.MakeGenericType(genericArguments);
			return new DiscoveredInstanceExport(base.Contract.ChangeType(type), base.Metadata);
		}
	}
	[DebuggerDisplay("{PartType.Name}")]
	[DebuggerTypeProxy(typeof(DiscoveredPartDebuggerProxy))]
	internal sealed class DiscoveredPart
	{
		private sealed class ParameterInfoComparer : IEqualityComparer<ParameterInfo>
		{
			public static readonly ParameterInfoComparer Instance = new ParameterInfoComparer();

			public int GetHashCode(ParameterInfo obj)
			{
				return HashHelpers.Combine(obj.Position.GetHashCode(), obj.Member.GetHashCode());
			}

			public bool Equals(ParameterInfo x, ParameterInfo y)
			{
				if (x == y)
				{
					return true;
				}
				if (x == null || y == null)
				{
					return false;
				}
				if (x.Position != y.Position)
				{
					return false;
				}
				if (x.Member != y.Member)
				{
					return false;
				}
				return true;
			}
		}

		private readonly TypeInfo _partType;

		private readonly AttributedModelProvider _attributeContext;

		private readonly List<DiscoveredExport> _exports = new List<DiscoveredExport>();

		private readonly ActivationFeature[] _activationFeatures;

		private readonly Lazy<IDictionary<string, object>> _partMetadata;

		private readonly List<Type[]> _appliedArguments = new List<Type[]>();

		private ConstructorInfo _constructor;

		private CompositeActivator _partActivator;

		private static readonly IDictionary<string, object> s_noMetadata = new Dictionary<string, object>();

		private static readonly MethodInfo s_activatorInvoke = typeof(CompositeActivator).GetTypeInfo().GetDeclaredMethod("Invoke");

		public TypeInfo PartType => _partType;

		public bool IsShared => ContractHelpers.IsShared(_partMetadata.Value);

		public IEnumerable<DiscoveredExport> DiscoveredExports => _exports;

		private DiscoveredPart(TypeInfo partType, AttributedModelProvider attributeContext, ActivationFeature[] activationFeatures, Lazy<IDictionary<string, object>> partMetadata)
		{
			_partType = partType;
			_attributeContext = attributeContext;
			_activationFeatures = activationFeatures;
			_partMetadata = partMetadata;
		}

		public DiscoveredPart(TypeInfo partType, AttributedModelProvider attributeContext, ActivationFeature[] activationFeatures)
		{
			DiscoveredPart discoveredPart = this;
			_partType = partType;
			_attributeContext = attributeContext;
			_activationFeatures = activationFeatures;
			_partMetadata = new Lazy<IDictionary<string, object>>(() => discoveredPart.GetPartMetadata(partType));
		}

		public void AddDiscoveredExport(DiscoveredExport export)
		{
			_exports.Add(export);
			export.Part = this;
		}

		public CompositionDependency[] GetDependencies(DependencyAccessor definitionAccessor)
		{
			return (from a in GetPartActivatorDependencies(definitionAccessor).Concat(_activationFeatures.SelectMany((ActivationFeature feature) => feature.GetDependencies(_partType, definitionAccessor)))
				where a != null
				select a).ToArray();
		}

		private IEnumerable<CompositionDependency> GetPartActivatorDependencies(DependencyAccessor definitionAccessor)
		{
			Type partTypeAsType = _partType.AsType();
			if (_constructor == null)
			{
				foreach (ConstructorInfo item in _partType.DeclaredConstructors.Where((ConstructorInfo ci) => ci.IsPublic && !ci.IsStatic))
				{
					if (_attributeContext.GetDeclaredAttribute<ImportingConstructorAttribute>(partTypeAsType, (MemberInfo)item) != null)
					{
						if (_constructor != null)
						{
							throw new CompositionFailedException(System.SR.Format(System.SR.DiscoveredPart_MultipleImportingConstructorsFound, _partType));
						}
						_constructor = item;
					}
				}
				if (_constructor == null && _partType.IsGenericType)
				{
					_constructor = GetConstructorInfoFromGenericType(_partType);
				}
				if ((object)_constructor == null)
				{
					_constructor = _partType.DeclaredConstructors.FirstOrDefault((ConstructorInfo ci) => ci.IsPublic && !ci.IsStatic && ci.GetParameters().Length == 0);
				}
				if (_constructor == null)
				{
					throw new CompositionFailedException(System.SR.Format(System.SR.DiscoveredPart_NoImportingConstructorsFound, _partType));
				}
			}
			ParameterInfo[] cps = _constructor.GetParameters();
			int i = 0;
			CompositionDependency val = default(CompositionDependency);
			while (i < cps.Length)
			{
				ParameterInfo parameterInfo = cps[i];
				ParameterImportSite parameterImportSite = new ParameterImportSite(parameterInfo);
				Type parameterType = parameterInfo.ParameterType;
				object[] declaredAttributes = _attributeContext.GetDeclaredAttributes(partTypeAsType, parameterInfo);
				ImportInfo importInfo = ContractHelpers.GetImportInfo(parameterType, declaredAttributes, parameterImportSite);
				if (!importInfo.AllowDefault)
				{
					yield return definitionAccessor.ResolveRequiredDependency((object)parameterImportSite, importInfo.Contract, true);
				}
				else if (definitionAccessor.TryResolveOptionalDependency((object)parameterImportSite, importInfo.Contract, true, ref val))
				{
					yield return val;
				}
				int num = i + 1;
				i = num;
			}
		}

		private ConstructorInfo GetConstructorInfoFromGenericType(TypeInfo type)
		{
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			Type genericTypeDefinition = type.GetGenericTypeDefinition();
			TypeInfo typeInfo = genericTypeDefinition.GetTypeInfo();
			int num = typeInfo.DeclaredConstructors.Count();
			ConstructorInfo constructorInfo = null;
			for (int i = 0; i < num; i++)
			{
				ConstructorInfo constructorInfo2 = typeInfo.DeclaredConstructors.ElementAt(i);
				if (constructorInfo2.IsPublic && !constructorInfo2.IsStatic && _attributeContext.GetDeclaredAttribute<ImportingConstructorAttribute>(genericTypeDefinition, (MemberInfo)constructorInfo2) != null)
				{
					if (constructorInfo != null)
					{
						throw new CompositionFailedException(System.SR.Format(System.SR.DiscoveredPart_MultipleImportingConstructorsFound, type));
					}
					constructorInfo = type.DeclaredConstructors.ElementAt(i);
				}
			}
			return constructorInfo;
		}

		public CompositeActivator GetActivator(IEnumerable<CompositionDependency> dependencies)
		{
			if (_partActivator != null)
			{
				return _partActivator;
			}
			ParameterExpression parameterExpression = Expression.Parameter(typeof(LifetimeContext), "cc");
			ParameterExpression parameterExpression2 = Expression.Parameter(typeof(CompositionOperation), "op");
			ParameterInfo[] parameters = _constructor.GetParameters();
			Expression[] array = new Expression[parameters.Length];
			Dictionary<ParameterInfo, CompositionDependency> dictionary = dependencies.Where((CompositionDependency dep) => dep.Site is ParameterImportSite).ToDictionary((CompositionDependency d) => ((ParameterImportSite)d.Site).Parameter, ParameterInfoComparer.Instance);
			for (int i = 0; i < parameters.Length; i++)
			{
				ParameterInfo parameterInfo = parameters[i];
				if (dictionary.TryGetValue(parameterInfo, out var value))
				{
					CompositeActivator activator = value.Target.GetDescriptor().Activator;
					array[i] = Expression.Convert(Expression.Call(Expression.Constant(activator), s_activatorInvoke, parameterExpression, parameterExpression2), parameterInfo.ParameterType);
				}
				else
				{
					array[i] = Expression.Default(parameterInfo.ParameterType);
				}
			}
			CompositeActivator val = Expression.Lambda<CompositeActivator>(Expression.Convert(Expression.New(_constructor, array), typeof(object)), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile();
			ActivationFeature[] activationFeatures = _activationFeatures;
			for (int j = 0; j < activationFeatures.Length; j++)
			{
				val = activationFeatures[j].RewriteActivator(_partType, val, _partMetadata.Value, dependencies);
			}
			_partActivator = val;
			return _partActivator;
		}

		public IDictionary<string, object> GetPartMetadata(TypeInfo partType)
		{
			Dictionary<string, object> dictionary = new Dictionary<string, object>();
			Attribute[] declaredAttributes = _attributeContext.GetDeclaredAttributes(partType.AsType(), partType);
			foreach (Attribute obj in declaredAttributes)
			{
				PartMetadataAttribute val = (PartMetadataAttribute)(object)((obj is PartMetadataAttribute) ? obj : null);
				if (val != null)
				{
					dictionary.Add(val.Name, val.Value);
				}
			}
			if (dictionary.Count != 0)
			{
				return dictionary;
			}
			return s_noMetadata;
		}

		public bool TryCloseGenericPart(Type[] typeArguments, out DiscoveredPart closed)
		{
			for (int i = 0; i < _partType.GenericTypeParameters.Length; i++)
			{
				Type[] genericParameterConstraints = _partType.GenericTypeParameters[i].GetTypeInfo().GetGenericParameterConstraints();
				for (int j = 0; j < genericParameterConstraints.Length; j++)
				{
					if (!genericParameterConstraints[j].GetTypeInfo().IsAssignableFrom(typeArguments[i].GetTypeInfo()))
					{
						closed = null;
						return false;
					}
				}
			}
			if (_appliedArguments.Any((Type[] args) => args.SequenceEqual(typeArguments)))
			{
				closed = null;
				return false;
			}
			_appliedArguments.Add(typeArguments);
			TypeInfo typeInfo = _partType.MakeGenericType(typeArguments).GetTypeInfo();
			DiscoveredPart discoveredPart = new DiscoveredPart(typeInfo, _attributeContext, _activationFeatures, _partMetadata);
			foreach (DiscoveredExport export2 in _exports)
			{
				DiscoveredExport export = export2.CloseGenericExport(typeInfo, typeArguments);
				discoveredPart.AddDiscoveredExport(export);
			}
			closed = discoveredPart;
			return true;
		}
	}
	internal sealed class DiscoveredPropertyExport : DiscoveredExport
	{
		private static readonly MethodInfo s_activatorInvoke = typeof(CompositeActivator).GetRuntimeMethod("Invoke", new Type[2]
		{
			typeof(LifetimeContext),
			typeof(CompositionOperation)
		});

		private readonly PropertyInfo _property;

		public DiscoveredPropertyExport(CompositionContract contract, IDictionary<string, object> metadata, PropertyInfo property)
			: base(contract, metadata)
		{
			_property = property;
		}

		protected override ExportDescriptor GetExportDescriptor(CompositeActivator partActivator)
		{
			ParameterExpression[] array = new ParameterExpression[2]
			{
				Expression.Parameter(typeof(LifetimeContext)),
				Expression.Parameter(typeof(CompositionOperation))
			};
			ConstantExpression instance = Expression.Constant(partActivator);
			MethodInfo method = s_activatorInvoke;
			Expression[] arguments = array;
			return ExportDescriptor.Create(Expression.Lambda<CompositeActivator>(Expression.Property(Expression.Convert(Expression.Call(instance, method, arguments), _property.DeclaringType), _property), array).Compile(), base.Metadata);
		}

		public override DiscoveredExport CloseGenericExport(TypeInfo closedPartType, Type[] genericArguments)
		{
			Type type = base.Contract.ContractType.MakeGenericType(genericArguments);
			return new DiscoveredPropertyExport(base.Contract.ChangeType(type), property: closedPartType.AsType().GetRuntimeProperty(_property.Name), metadata: base.Metadata);
		}
	}
	internal sealed class ParameterImportSite
	{
		private readonly ParameterInfo _pi;

		public ParameterInfo Parameter => _pi;

		public ParameterImportSite(ParameterInfo pi)
		{
			_pi = pi;
		}

		public override string ToString()
		{
			return _pi.Name;
		}
	}
	internal sealed class TypeInspector
	{
		private static readonly IDictionary<string, object> s_noMetadata = new Dictionary<string, object>();

		private readonly ActivationFeature[] _activationFeatures;

		private readonly AttributedModelProvider _attributeContext;

		public TypeInspector(AttributedModelProvider attributeContext, ActivationFeature[] activationFeatures)
		{
			_attributeContext = attributeContext;
			_activationFeatures = activationFeatures;
		}

		public bool InspectTypeForPart(TypeInfo type, out DiscoveredPart part)
		{
			part = null;
			if (type.IsAbstract || !type.IsClass || _attributeContext.GetDeclaredAttribute<PartNotDiscoverableAttribute>(type.AsType(), (MemberInfo)type) != null)
			{
				return false;
			}
			foreach (DiscoveredExport item in DiscoverExports(type))
			{
				if (part == null)
				{
					part = new DiscoveredPart(type, _attributeContext, _activationFeatures);
				}
				part.AddDiscoveredExport(item);
			}
			return part != null;
		}

		private IEnumerable<DiscoveredExport> DiscoverExports(TypeInfo partType)
		{
			foreach (DiscoveredExport item in DiscoverInstanceExports(partType))
			{
				yield return item;
			}
			foreach (DiscoveredExport item2 in DiscoverPropertyExports(partType))
			{
				yield return item2;
			}
		}

		private IEnumerable<DiscoveredExport> DiscoverInstanceExports(TypeInfo partType)
		{
			Type partTypeAsType = partType.AsType();
			ExportAttribute[] declaredAttributes = _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, (MemberInfo)partType);
			foreach (ExportAttribute val in declaredAttributes)
			{
				IDictionary<string, object> dictionary = new Dictionary<string, object>();
				ReadMetadataAttribute((Attribute)(object)val, dictionary);
				object[] declaredAttributes2 = _attributeContext.GetDeclaredAttributes(partTypeAsType, partType);
				ReadLooseMetadata(declaredAttributes2, dictionary);
				Type type = val.ContractType ?? partTypeAsType;
				CheckInstanceExportCompatibility(partType, type.GetTypeInfo());
				CompositionContract contract = new CompositionContract(type, val.ContractName);
				if (dictionary.Count == 0)
				{
					dictionary = s_noMetadata;
				}
				yield return new DiscoveredInstanceExport(contract, dictionary);
			}
		}

		private IEnumerable<DiscoveredExport> DiscoverPropertyExports(TypeInfo partType)
		{
			Type partTypeAsType = partType.AsType();
			foreach (PropertyInfo property in from pi in partTypeAsType.GetRuntimeProperties()
				where pi.CanRead && pi.GetMethod.IsPublic && !pi.GetMethod.IsStatic
				select pi)
			{
				ExportAttribute[] declaredAttributes = _attributeContext.GetDeclaredAttributes<ExportAttribute>(partTypeAsType, (MemberInfo)property);
				foreach (ExportAttribute val in declaredAttributes)
				{
					IDictionary<string, object> dictionary = new Dictionary<string, object>();
					ReadMetadataAttribute((Attribute)(object)val, dictionary);
					object[] declaredAttributes2 = _attributeContext.GetDeclaredAttributes(partTypeAsType, property);
					ReadLooseMetadata(declaredAttributes2, dictionary);
					Type type = val.ContractType ?? property.PropertyType;
					CheckPropertyExportCompatibility(partType, property, type.GetTypeInfo());
					CompositionContract contract = new CompositionContract(val.ContractType ?? property.PropertyType, val.ContractName);
					if (dictionary.Count == 0)
					{
						dictionary = s_noMetadata;
					}
					yield return new DiscoveredPropertyExport(contract, dictionary, property);
				}
			}
		}

		private static void ReadLooseMetadata(object[] appliedAttributes, IDictionary<string, object> metadata)
		{
			foreach (object obj in appliedAttributes)
			{
				if (!(obj is ExportAttribute))
				{
					ExportMetadataAttribute val = (ExportMetadataAttribute)((obj is ExportMetadataAttribute) ? obj : null);
					if (val != null)
					{
						Type valueType = val.Value?.GetType() ?? typeof(object);
						AddMetadata(metadata, val.Name, valueType, val.Value);
					}
					else
					{
						ReadMetadataAttribute((Attribute)obj, metadata);
					}
				}
			}
		}

		private static void AddMetadata(IDictionary<string, object> metadata, string name, Type valueType, object value)
		{
			if (!metadata.TryGetValue(name, out var value2))
			{
				metadata.Add(name, value);
			}
			else if (value2 is Array array)
			{
				Array array2 = Array.CreateInstance(valueType, array.Length + 1);
				Array.Copy(array, array2, array.Length);
				array2.SetValue(value, array.Length);
				metadata[name] = array2;
			}
			else
			{
				Array array3 = Array.CreateInstance(valueType, 2);
				array3.SetValue(value2, 0);
				array3.SetValue(value, 1);
				metadata[name] = array3;
			}
		}

		private static void ReadMetadataAttribute(Attribute attribute, IDictionary<string, object> metadata)
		{
			Type attrType = attribute.GetType();
			if (((MemberInfo)attrType.GetTypeInfo()).GetCustomAttribute<MetadataAttributeAttribute>(inherit: true) == null)
			{
				return;
			}
			foreach (PropertyInfo item in from p in attrType.GetRuntimeProperties()
				where p.DeclaringType == attrType && p.CanRead
				select p)
			{
				AddMetadata(metadata, item.Name, item.PropertyType, item.GetValue(attribute, null));
			}
		}

		private static void CheckPropertyExportCompatibility(TypeInfo partType, PropertyInfo property, TypeInfo contractType)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			if (partType.IsGenericTypeDefinition)
			{
				CheckGenericContractCompatibility(partType, property.PropertyType.GetTypeInfo(), contractType);
			}
			else if (!contractType.IsAssignableFrom(property.PropertyType.GetTypeInfo()))
			{
				throw new CompositionFailedException(System.SR.Format(System.SR.TypeInspector_ExportedContractTypeNotAssignable, contractType.Name, property.Name, partType.Name));
			}
		}

		private static void CheckGenericContractCompatibility(TypeInfo partType, TypeInfo exportingMemberType, TypeInfo contractType)
		{
			//IL_001e: 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_0093: Unknown result type (might be due to invalid IL or missing references)
			if (!contractType.IsGenericTypeDefinition)
			{
				throw new CompositionFailedException(System.SR.Format(System.SR.TypeInspector_NoExportNonGenericContract, partType.Name, contractType.Name));
			}
			bool flag = false;
			foreach (TypeInfo assignableType in GetAssignableTypes(exportingMemberType))
			{
				if (assignableType == contractType || (assignableType.IsGenericType && assignableType.GetGenericTypeDefinition() == contractType.AsType()))
				{
					TypeInfo typeInfo = assignableType;
					if (!(typeInfo == partType) && !typeInfo.GenericTypeArguments.SequenceEqual(partType.GenericTypeParameters))
					{
						throw new CompositionFailedException(System.SR.Format(System.SR.TypeInspector_ArgumentMismatch, contractType.Name, partType.Name));
					}
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				throw new CompositionFailedException(System.SR.Format(System.SR.TypeInspector_ExportNotCompatible, exportingMemberType.Name, partType.Name, contractType.Name));
			}
		}

		private static IEnumerable<TypeInfo> GetAssignableTypes(TypeInfo exportingMemberType)
		{
			foreach (Type implementedInterface in exportingMemberType.ImplementedInterfaces)
			{
				yield return implementedInterface.GetTypeInfo();
			}
			TypeInfo b = exportingMemberType;
			while (b != null)
			{
				yield return b;
				b = b.BaseType?.GetTypeInfo();
			}
		}

		private static void CheckInstanceExportCompatibility(TypeInfo partType, TypeInfo contractType)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if (partType.IsGenericTypeDefinition)
			{
				CheckGenericContractCompatibility(partType, partType, contractType);
			}
			else if (!contractType.IsAssignableFrom(partType))
			{
				throw new CompositionFailedException(System.SR.Format(System.SR.TypeInspector_ContractNotAssignable, contractType.Name, partType.Name));
			}
		}
	}
}
namespace System.Composition.TypedParts.ActivationFeatures
{
	internal abstract class ActivationFeature
	{
		protected static readonly CompositionDependency[] NoDependencies = Array.Empty<CompositionDependency>();

		public abstract CompositeActivator RewriteActivator(TypeInfo partType, CompositeActivator activator, IDictionary<string, object> partMetadata, IEnumerable<CompositionDependency> dependencies);

		public virtual IEnumerable<CompositionDependency> GetDependencies(TypeInfo partType, DependencyAccessor definitionAccessor)
		{
			return NoDependencies;
		}
	}
	internal sealed class DisposalFeature : ActivationFeature
	{
		public override CompositeActivator RewriteActivator(TypeInfo partType, CompositeActivator activator, IDictionary<string, object> partMetadata, IEnumerable<CompositionDependency> dependencies)
		{
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Expected O, but got Unknown
			if (!typeof(IDisposable).GetTypeInfo().IsAssignableFrom(partType))
			{
				return activator;
			}
			return (CompositeActivator)delegate(LifetimeContext c, CompositionOperation o)
			{
				IDisposable disposable = (IDisposable)activator.Invoke(c, o);
				c.AddBoundInstance(disposable);
				return disposable;
			};
		}
	}
	internal sealed class LifetimeFeature : ActivationFeature
	{
		public const string SharingBoundaryPartMetadataName = "SharingBoundary";

		public override CompositeActivator RewriteActivator(TypeInfo partType, CompositeActivator activatorBody, IDictionary<string, object> partMetadata, IEnumerable<CompositionDependency> dependencies)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			if (!ContractHelpers.IsShared(partMetadata))
			{
				return activatorBody;
			}
			if (!partMetadata.TryGetValue("SharingBoundary", out var value))
			{
				value = null;
			}
			string sharingBoundary = (string)value;
			int sharingKey = LifetimeContext.AllocateSharingId();
			CompositeActivator val = default(CompositeActivator);
			return (CompositeActivator)delegate(LifetimeContext c, CompositionOperation o)
			{
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				//IL_003f: Expected O, but got Unknown
				//IL_0044: Expected O, but got Unknown
				LifetimeContext val2 = c.FindContextWithin(sharingBoundary);
				if (val2 == c)
				{
					return val2.GetOrCreate(sharingKey, o, activatorBody);
				}
				CompositeActivator obj = val;
				if (obj == null)
				{
					CompositeActivator val3 = (LifetimeContext c1, CompositionOperation o1) => c1.GetOrCreate(sharingKey, o1, activatorBody);
					CompositeActivator val4 = val3;
					val = val3;
					obj = val4;
				}
				return CompositionOperation.Run(val2, obj);
			};
		}
	}
	internal sealed class OnImportsSatisfiedFeature : ActivationFeature
	{
		private readonly AttributedModelProvider _attributeContext;

		public OnImportsSatisfiedFeature(AttributedModelProvider attributeContext)
		{
			if (attributeContext == null)
			{
				throw new ArgumentNullException("attributeContext");
			}
			_attributeContext = attributeContext;
		}

		public override CompositeActivator RewriteActivator(TypeInfo partType, CompositeActivator activator, IDictionary<string, object> partMetadata, IEnumerable<CompositionDependency> dependencies)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Expected O, but got Unknown
			CompositeActivator val = activator;
			foreach (MethodInfo item in from mi in partType.AsType().GetRuntimeMethods()
				where _attributeContext.GetDeclaredAttribute<OnImportsSatisfiedAttribute>(mi.DeclaringType, (MemberInfo)mi) != null
				select mi)
			{
				if (((!item.IsPublic && !item.IsAssembly) | item.IsStatic) || item.ReturnType != typeof(void) || item.IsGenericMethodDefinition || item.GetParameters().Length != 0)
				{
					throw new CompositionFailedException(System.SR.Format(System.SR.OnImportsSatisfiedFeature_AttributeError, partType, item.Name));
				}
				ParameterExpression parameterExpression = Expression.Parameter(typeof(object), "ois");
				Action<object> call = Expression.Lambda<Action<object>>(Expression.Call(Expression.Convert(parameterExpression, partType.AsType()), item), new ParameterExpression[1] { parameterExpression }).Compile();
				CompositeActivator prev = val;
				val = (CompositeActivator)delegate(LifetimeContext c, CompositionOperation o)
				{
					object psn = prev.Invoke(c, o);
					o.AddPostCompositionAction((Action)delegate
					{
						call(psn);
					});
					return psn;
				};
			}
			return val;
		}
	}
	internal sealed class PropertyImportSite
	{
		private readonly PropertyInfo _pi;

		public PropertyInfo Property => _pi;

		public PropertyImportSite(PropertyInfo pi)
		{
			_pi = pi;
		}

		public override string ToString()
		{
			return _pi.Name;
		}
	}
	internal sealed class PropertyInjectionFeature : ActivationFeature
	{
		private readonly AttributedModelProvider _attributeContext;

		private static readonly MethodInfo s_activatorInvokeMethod = typeof(CompositeActivator).GetTypeInfo().GetDeclaredMethod("Invoke");

		public PropertyInjectionFeature(AttributedModelProvider attributeContext)
		{
			_attributeContext = attributeContext;
		}

		public override IEnumerable<CompositionDependency> GetDependencies(TypeInfo partType, DependencyAccessor definitionAccessor)
		{
			var array = (from pi in partType.AsType().GetRuntimeProperties()
				where pi.CanWrite && pi.SetMethod.IsPublic && !pi.SetMethod.IsStatic
				let attrs = _attributeContext.GetDeclaredAttributes(pi.DeclaringType, pi).ToArray()
				let site = new PropertyImportSite(pi)
				where attrs.Any((Attribute a) => a is ImportAttribute || a is ImportManyAttribute)
				select new
				{
					Site = site,
					ImportInfo = ContractHelpers.GetImportInfo(pi.PropertyType, attrs, site)
				}).ToArray();
			if (array.Length == 0)
			{
				return ActivationFeature.NoDependencies;
			}
			List<CompositionDependency> list = new List<CompositionDependency>();
			var array2 = array;
			CompositionDependency item = default(CompositionDependency);
			foreach (var anon in array2)
			{
				if (!anon.ImportInfo.AllowDefault)
				{
					list.Add(definitionAccessor.ResolveRequiredDependency((object)anon.Site, anon.ImportInfo.Contract, false));
				}
				else if (definitionAccessor.TryResolveOptionalDependency((object)anon.Site, anon.ImportInfo.Contract, false, ref item))
				{
					list.Add(item);
				}
			}
			return list;
		}

		public override CompositeActivator RewriteActivator(TypeInfo partType, CompositeActivator activator, IDictionary<string, object> partMetadata, IEnumerable<CompositionDependency> dependencies)
		{
			//IL_0195: Unknown result type (might be due to invalid IL or missing references)
			//IL_019b: Expected O, but got Unknown
			Dictionary<PropertyInfo, CompositionDependency> dictionary = dependencies.Where((CompositionDependency dep) => dep.Site is PropertyImportSite).ToDictionary((CompositionDependency d) => ((PropertyImportSite)d.Site).Property);
			if (dictionary.Count == 0)
			{
				return activator;
			}
			ParameterExpression parameterExpression = Expression.Parameter(typeof(LifetimeContext));
			ParameterExpression parameterExpression2 = Expression.Parameter(typeof(CompositionOperation));
			ParameterExpression parameterExpression3 = Expression.Parameter(typeof(object));
			ParameterExpression parameterExpression4 = Expression.Variable(partType.AsType());
			List<Expression> list = new List<Expression>();
			BinaryExpression item = Expression.Assign(parameterExpression4, Expression.Convert(parameterExpression3, partType.AsType()));
			list.Add(item);
			foreach (KeyValuePair<PropertyInfo, CompositionDependency> item3 in dictionary)
			{
				PropertyInfo key = item3.Key;
				BinaryExpression item2 = Expression.Assign(Expression.MakeMemberAccess(parameterExpression4, key), Expression.Convert(Expression.Call(Expression.Constant(item3.Value.Target.GetDescriptor().Activator), s_activatorInvokeMethod, parameterExpression, parameterExpression2), key.PropertyType));
				list.Add(item2);
			}
			list.Add(parameterExpression3);
			BlockExpression body = Expression.Block(new ParameterExpression[1] { parameterExpression4 }, list);
			Func<object, LifetimeContext, CompositionOperation, object> setAction = Expression.Lambda<Func<object, LifetimeContext, CompositionOperation, object>>(body, new ParameterExpression[3] { parameterExpression3, parameterExpression, parameterExpression2 }).Compile();
			return (CompositeActivator)delegate(LifetimeContext c, CompositionOperation o)
			{
				object i = activator.Invoke(c, o);
				o.AddNonPrerequisiteAction((Action)delegate
				{
					setAction(i, c, o);
				});
				return i;
			};
		}
	}
}
namespace System.Composition.Hosting
{
	[DebuggerTypeProxy(typeof(ContainerConfigurationDebuggerProxy))]
	public class ContainerConfiguration
	{
		private AttributedModelProvider _defaultAttributeContext;

		private readonly List<ExportDescriptorProvider> _addedSources = new List<ExportDescriptorProvider>();

		private readonly List<Tuple<IEnumerable<Type>, AttributedModelProvider>> _types = new List<Tuple<IEnumerable<Type>, AttributedModelProvider>>();

		public CompositionHost CreateContainer()
		{
			List<ExportDescriptorProvider> list = _addedSources.ToList();
			foreach (Tuple<IEnumerable<Type>, AttributedModelProvider> type in _types)
			{
				AttributedModelProvider attributeContext = (AttributedModelProvider)(type.Item2 ?? ((object)_defaultAttributeContext) ?? ((object)new DirectAttributeContext()));
				list.Add((ExportDescriptorProvider)(object)new TypedPartExportDescriptorProvider(type.Item1, attributeContext));
			}
			return CompositionHost.CreateCompositionHost(list.ToArray());
		}

		public ContainerConfiguration WithProvider(ExportDescriptorProvider exportDescriptorProvider)
		{
			if (exportDescriptorProvider == null)
			{
				throw new ArgumentNullException("exportDescriptorProvider");
			}
			_addedSources.Add(exportDescriptorProvider);
			return this;
		}

		public ContainerConfiguration WithDefaultConventions(AttributedModelProvider conventions)
		{
			if (conventions == null)
			{
				throw new ArgumentNullException("conventions");
			}
			if (_defaultAttributeContext != null)
			{
				throw new InvalidOperationException(System.SR.ContainerConfiguration_DefaultConventionSet);
			}
			_defaultAttributeContext = conventions;
			return this;
		}

		public ContainerConfiguration WithPart(Type partType)
		{
			return WithPart(partType, null);
		}

		public ContainerConfiguration WithPart(Type partType, AttributedModelProvider conventions)
		{
			if (partType == null)
			{
				throw new ArgumentNullException("partType");
			}
			return WithParts(new Type[1] { partType }, conventions);
		}

		public ContainerConfiguration WithPart<TPart>()
		{
			return WithPart<TPart>(null);
		}

		public ContainerConfiguration WithPart<TPart>(AttributedModelProvider conventions)
		{
			return WithPart(typeof(TPart), conventions);
		}

		public ContainerConfiguration WithParts(params Type[] partTypes)
		{
			return WithParts((IEnumerable<Type>)partTypes);
		}

		public ContainerConfiguration WithParts(IEnumerable<Type> partTypes)
		{
			return WithParts(partTypes, null);
		}

		public ContainerConfiguration WithParts(IEnumerable<Type> partTypes, AttributedModelProvider conventions)
		{
			if (partTypes == null)
			{
				throw new ArgumentNullException("partTypes");
			}
			_types.Add(Tuple.Create<IEnumerable<Type>, AttributedModelProvider>(partTypes, conventions));
			return this;
		}

		public ContainerConfiguration WithAssembly(Assembly assembly)
		{
			return WithAssembly(assembly, null);
		}

		public ContainerConfiguration WithAssembly(Assembly assembly, AttributedModelProvider conventions)
		{
			return WithAssemblies(new Assembly[1] { assembly }, conventions);
		}

		public ContainerConfiguration WithAssemblies(IEnumerable<Assembly> assemblies)
		{
			return WithAssemblies(assemblies, null);
		}

		public ContainerConfiguration WithAssemblies(IEnumerable<Assembly> assemblies, AttributedModelProvider conventions)
		{
			if (assemblies == null)
			{
				throw new ArgumentNullException("assemblies");
			}
			return WithParts(assemblies.SelectMany((Assembly a) => a.DefinedTypes.Select((TypeInfo dt) => dt.AsType())), conventions);
		}

		public ContainerConfiguration WithExport<TExport>(TExport exportedInstance)
		{
			if (exportedInstance == null)
			{
				throw new ArgumentNullException("exportedInstance");
			}
			return WithExport(exportedInstance, null, null);
		}

		public ContainerConfiguration WithExport<TExport>(TExport exportedInstance, string contractName = null, IDictionary<string, object> metadata = null)
		{
			if (exportedInstance == null)
			{
				throw new ArgumentNullException("exportedInstance");
			}
			return WithExport(typeof(TExport), exportedInstance, contractName, metadata);
		}

		public ContainerConfiguration WithExport(Type contractType, object exportedInstance)
		{
			if ((object)contractType == null)
			{
				throw new ArgumentNullException("contractType");
			}
			if (exportedInstance == null)
			{
				throw new ArgumentNullException("exportedInstance");
			}
			return WithExport(contractType, exportedInstance, null, null);
		}

		public ContainerConfiguration WithExport(Type contractType, object exportedInstance, string contractName = null, IDictionary<string, object> metadata = null)
		{
			if ((object)contractType == null)
			{
				throw new ArgumentNullException("contractType");
			}
			if (exportedInstance == null)
			{
				throw new ArgumentNullException("exportedInstance");
			}
			return WithProvider((ExportDescriptorProvider)(object)new InstanceExportDescriptorProvider(exportedInstance, contractType, contractName, metadata));
		}

		internal ExportDescriptorProvider[] DebugGetAddedExportDescriptorProviders()
		{
			return _addedSources.ToArray();
		}

		internal Tuple<IEnumerable<Type>, AttributedModelProvider>[] DebugGetRegisteredTypes()
		{
			return _types.ToArray();
		}

		internal AttributedModelProvider DebugGetDefaultAttributeContext()
		{
			return _defaultAttributeContext;
		}
	}
	internal sealed class InstanceExportDescriptorProvider : SinglePartExportDescriptorProvider
	{
		private readonly object _exportedInstance;

		public InstanceExportDescriptorProvider(object exportedInstance, Type contractType, string contractName, IDictionary<string, object> metadata)
			: base(contractType, contractName, metadata)
		{
			_exportedInstance = exportedInstance;
		}

		public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
		{
			if (!IsSupportedContract(contract))
			{
				yield break;
			}
			yield return new ExportDescriptorPromise(contract, _exportedInstance.ToString(), true, ExportDescriptorProvider.NoDependencies, (Func<IEnumerable<CompositionDependency>, ExportDescriptor>)((IEnumerable<CompositionDependency> _) => ExportDescriptor.Create((CompositeActivator)((LifetimeContext c, CompositionOperation o) => _exportedInstance), base.Metadata)));
		}
	}
	internal abstract class SinglePartExportDescriptorProvider : ExportDescriptorProvider
	{
		private readonly Type _contractType;

		private readonly string _contractName;

		protected IDictionary<string, object> Metadata { get; }

		protected SinglePartExportDescriptorProvider(Type contractType, string contractName, IDictionary<string, object> metadata)
		{
			_contractType = contractType;
			_contractName = contractName;
			Metadata = metadata ?? new Dictionary<string, object>();
		}

		protected bool IsSupportedContract(CompositionContract contract)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			if (contract.ContractType != _contractType || contract.ContractName != _contractName)
			{
				return false;
			}
			if (contract.MetadataConstraints != null)
			{
				Dictionary<string, object> dictionary = contract.MetadataConstraints.Where((KeyValuePair<string, object> c) => Metadata.ContainsKey(c.Key)).ToDictionary((KeyValuePair<string, object> c) => c.Key, (KeyValuePair<string, object> c) => Metadata[c.Key]);
				CompositionContract obj = new CompositionContract(contract.ContractType, contract.ContractName, (IDictionary<string, object>)((dictionary.Count == 0) ? null : dictionary));
				if (!((object)contract).Equals((object?)obj))
				{
					return false;
				}
			}
			return true;
		}
	}
}
namespace System.Composition.Debugging
{
	internal sealed class ContainerConfigurationDebuggerProxy
	{
		private readonly ContainerConfiguration _configuration;

		private DiscoveredPart[] _discoveredParts;

		private Type[] _ignoredTypes;

		[DebuggerDisplay("Added Providers")]
		public ExportDescriptorProvider[] AddedExportDescriptorProviders => _configuration.DebugGetAddedExportDescriptorProviders();

		[DebuggerDisplay("Discovered Parts")]
		public DiscoveredPart[] DiscoveredParts
		{
			get
			{
				InitDiscovery();
				return _discoveredParts;
			}
		}

		[DebuggerDisplay("Ignored Types")]
		public Type[] IgnoredTypes
		{
			get
			{
				InitDiscovery();
				return _ignoredTypes;
			}
		}

		public ContainerConfigurationDebuggerProxy(ContainerConfiguration configuration)
		{
			_configuration = configuration;
		}

		private void InitDiscovery()
		{
			if (_discoveredParts != null)
			{
				return;
			}
			Tuple<IEnumerable<Type>, AttributedModelProvider>[] array = _configuration.DebugGetRegisteredTypes();
			AttributedModelProvider val = (AttributedModelProvider)(((object)_configuration.DebugGetDefaultAttributeContext()) ?? ((object)new DirectAttributeContext()));
			List<DiscoveredPart> list = new List<DiscoveredPart>();
			List<Type> list2 = new List<Type>();
			Tuple<IEnumerable<Type>, AttributedModelProvider>[] array2 = array;
			foreach (Tuple<IEnumerable<Type>, AttributedModelProvider> obj in array2)
			{
				AttributedModelProvider attributeContext = obj.Item2 ?? val;
				ActivationFeature[] activationFeatures = TypedPartExportDescriptorProvider.DebugGetActivationFeatures(attributeContext);
				TypeInspector typeInspector = new TypeInspector(attributeContext, activationFeatures);
				foreach (Type item in obj.Item1)
				{
					if (typeInspector.InspectTypeForPart(item.GetTypeInfo(), out var part))
					{
						list.Add(part);
					}
					else
					{
						list2.Add(item);
					}
				}
			}
			_discoveredParts = list.ToArray();
			_ignoredTypes = list2.ToArray();
		}
	}
	internal sealed class DiscoveredPartDebuggerProxy
	{
		private readonly DiscoveredPart _discoveredPart;

		public Type PartType => _discoveredPart.PartType.AsType();

		public DiscoveredExport[] Exports => _discoveredPart.DiscoveredExports.ToArray();

		public IDictionary<string, object> PartMetadata => _discoveredPart.GetPartMetadata(PartType.GetTypeInfo());

		public DiscoveredPartDebuggerProxy(DiscoveredPart discoveredPart)
		{
			_discoveredPart = discoveredPart;
		}
	}
}
namespace System.Composition.Convention
{
	internal static class AttributedModelProviderExtensions
	{
		public static TAttribute GetDeclaredAttribute<TAttribute>(this AttributedModelProvider convention, Type reflectedType, MemberInfo member) where TAttribute : Attribute
		{
			return convention.GetCustomAttributes(reflectedType, member).OfType<TAttribute>().SingleOrDefault();
		}

		public static Attribute[] GetDeclaredAttributes(this AttributedModelProvider convention, Type reflectedType, MemberInfo member)
		{
			return convention.GetCustomAttributes(reflectedType, member).ToArray();
		}

		public static TAttribute[] GetDeclaredAttributes<TAttribute>(this AttributedModelProvider convention, Type reflectedType, MemberInfo member) where TAttribute : Attribute
		{
			return convention.GetCustomAttributes(reflectedType, member).OfType<TAttribute>().ToArray();
		}

		public static TAttribute GetDeclaredAttribute<TAttribute>(this AttributedModelProvider convention, Type reflectedType, ParameterInfo parameter) where TAttribute : Attribute
		{
			return convention.GetCustomAttributes(reflectedType, parameter).OfType<TAttribute>().SingleOrDefault();
		}

		public static Attribute[] GetDeclaredAttributes(this AttributedModelProvider convention, Type reflectedType, ParameterInfo parameter)
		{
			return convention.GetCustomAttributes(reflectedType, parameter).OfType<Attribute>().ToArray();
		}

		public static TAttribute[] GetDeclaredAttributes<TAttribute>(this AttributedModelProvider convention, Type reflectedType, ParameterInfo parameter) where TAttribute : Attribute
		{
			return convention.GetCustomAttributes(reflectedType, parameter).OfType<TAttribute>().ToArray();
		}
	}
}

BepInEx/core/System.Configuration.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration.Internal;
using System.Configuration.Provider;
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.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using Unity;

[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Configuration.dll")]
[assembly: AssemblyDescription("System.Configuration.dll")]
[assembly: AssemblyDefaultAlias("System.Configuration.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: CLSCompliant(true)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyDelaySign(true)]
[assembly: InternalsVisibleTo("System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: AssemblyVersion("4.0.0.0")]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal sealed class Locale
{
	private Locale()
	{
	}

	public static string GetText(string msg)
	{
		return msg;
	}

	public static string GetText(string fmt, params object[] args)
	{
		return string.Format(fmt, args);
	}
}
internal class ConfigXmlTextReader : XmlTextReader, IConfigErrorInfo
{
	private readonly string fileName;

	public string Filename => fileName;

	public ConfigXmlTextReader(Stream s, string fileName)
		: base(s)
	{
		if (fileName == null)
		{
			throw new ArgumentNullException("fileName");
		}
		this.fileName = fileName;
	}

	public ConfigXmlTextReader(TextReader input, string fileName)
		: base(input)
	{
		if (fileName == null)
		{
			throw new ArgumentNullException("fileName");
		}
		this.fileName = fileName;
	}
}
namespace System
{
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoTODOAttribute : Attribute
	{
		private string comment;

		public string Comment => comment;

		public MonoTODOAttribute()
		{
		}

		public MonoTODOAttribute(string comment)
		{
			this.comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoDocumentationNoteAttribute : MonoTODOAttribute
	{
		public MonoDocumentationNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoExtensionAttribute : MonoTODOAttribute
	{
		public MonoExtensionAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoInternalNoteAttribute : MonoTODOAttribute
	{
		public MonoInternalNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoLimitationAttribute : MonoTODOAttribute
	{
		public MonoLimitationAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoNotSupportedAttribute : MonoTODOAttribute
	{
		public MonoNotSupportedAttribute(string comment)
			: base(comment)
		{
		}
	}
}
namespace System.Configuration
{
	public sealed class AppSettingsSection : ConfigurationSection
	{
		private static ConfigurationPropertyCollection _properties;

		private static readonly ConfigurationProperty _propFile;

		private static readonly ConfigurationProperty _propSettings;

		[ConfigurationProperty("file", DefaultValue = "")]
		public string File
		{
			get
			{
				return (string)base[_propFile];
			}
			set
			{
				base[_propFile] = value;
			}
		}

		[ConfigurationProperty("", Options = ConfigurationPropertyOptions.IsDefaultCollection)]
		public KeyValueConfigurationCollection Settings => (KeyValueConfigurationCollection)base[_propSettings];

		protected internal override ConfigurationPropertyCollection Properties => _properties;

		static AppSettingsSection()
		{
			_propFile = new ConfigurationProperty("file", typeof(string), "", new StringConverter(), null, ConfigurationPropertyOptions.None);
			_propSettings = new ConfigurationProperty("", typeof(KeyValueConfigurationCollection), null, null, null, ConfigurationPropertyOptions.IsDefaultCollection);
			_properties = new ConfigurationPropertyCollection();
			_properties.Add(_propFile);
			_properties.Add(_propSettings);
		}

		protected internal override bool IsModified()
		{
			return Settings.IsModified();
		}

		[MonoInternalNote("file path?  do we use a System.Configuration api for opening it?  do we keep it open?  do we open it writable?")]
		protected internal override void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
		{
			base.DeserializeElement(reader, serializeCollectionKey);
			if (!(File != ""))
			{
				return;
			}
			try
			{
				string text = File;
				if (!Path.IsPathRooted(text))
				{
					text = Path.Combine(Path.GetDirectoryName(base.Configuration.FilePath), text);
				}
				FileStream fileStream = System.IO.File.OpenRead(text);
				XmlReader reader2 = new ConfigXmlTextReader(fileStream, text);
				base.DeserializeElement(reader2, serializeCollectionKey);
				fileStream.Close();
			}
			catch
			{
			}
		}

		protected internal override void Reset(ConfigurationElement parentSection)
		{
			if (parentSection is AppSettingsSection appSettingsSection)
			{
				Settings.Reset(appSettingsSection.Settings);
			}
		}

		[MonoTODO]
		protected internal override string SerializeSection(ConfigurationElement parentElement, string name, ConfigurationSaveMode saveMode)
		{
			if (File == "")
			{
				return base.SerializeSection(parentElement, name, saveMode);
			}
			throw new NotImplementedException();
		}

		protected internal override object GetRuntimeObject()
		{
			KeyValueInternalCollection keyValueInternalCollection = new KeyValueInternalCollection();
			string[] allKeys = Settings.AllKeys;
			foreach (string key in allKeys)
			{
				KeyValueConfigurationElement keyValueConfigurationElement = Settings[key];
				keyValueInternalCollection.Add(keyValueConfigurationElement.Key, keyValueConfigurationElement.Value);
			}
			if (!ConfigurationManager.ConfigurationSystem.SupportsUserConfig)
			{
				keyValueInternalCollection.SetReadOnly();
			}
			return keyValueInternalCollection;
		}
	}
	public sealed class CallbackValidator : ConfigurationValidatorBase
	{
		private Type type;

		private ValidatorCallback callback;

		public CallbackValidator(Type type, ValidatorCallback callback)
		{
			this.type = type;
			this.callback = callback;
		}

		public override bool CanValidate(Type type)
		{
			return type == this.type;
		}

		public override void Validate(object value)
		{
			callback(value);
		}
	}
	[AttributeUsage(AttributeTargets.Property)]
	public sealed class CallbackValidatorAttribute : ConfigurationValidatorAttribute
	{
		private string callbackMethodName = "";

		private Type type;

		private ConfigurationValidatorBase instance;

		public string CallbackMethodName
		{
			get
			{
				return callbackMethodName;
			}
			set
			{
				callbackMethodName = value;
				instance = null;
			}
		}

		public Type Type
		{
			get
			{
				return type;
			}
			set
			{
				type = value;
				instance = null;
			}
		}

		public override ConfigurationValidatorBase ValidatorInstance => instance;
	}
	internal class ClientConfigurationSystem : IInternalConfigSystem
	{
		private Configuration cfg;

		private Configuration Configuration
		{
			get
			{
				if (cfg == null)
				{
					Assembly entryAssembly = Assembly.GetEntryAssembly();
					try
					{
						cfg = ConfigurationManager.OpenExeConfigurationInternal(ConfigurationUserLevel.None, entryAssembly, null);
					}
					catch (Exception inner)
					{
						throw new ConfigurationErrorsException("Error Initializing the configuration system.", inner);
					}
				}
				return cfg;
			}
		}

		bool IInternalConfigSystem.SupportsUserConfig => false;

		object IInternalConfigSystem.GetSection(string configKey)
		{
			return Configuration.GetSection(configKey)?.GetRuntimeObject();
		}

		void IInternalConfigSystem.RefreshConfig(string sectionName)
		{
		}
	}
	public sealed class CommaDelimitedStringCollection : StringCollection
	{
		private bool modified;

		private bool readOnly;

		private int originalStringHash;

		public bool IsModified
		{
			get
			{
				if (modified)
				{
					return true;
				}
				string text = ToString();
				if (text == null)
				{
					return false;
				}
				return text.GetHashCode() != originalStringHash;
			}
		}

		public new bool IsReadOnly => readOnly;

		public new string this[int index]
		{
			get
			{
				return base[index];
			}
			set
			{
				if (readOnly)
				{
					throw new ConfigurationErrorsException("The configuration is read only");
				}
				base[index] = value;
				modified = true;
			}
		}

		public new void Add(string value)
		{
			if (readOnly)
			{
				throw new ConfigurationErrorsException("The configuration is read only");
			}
			base.Add(value);
			modified = true;
		}

		public new void AddRange(string[] range)
		{
			if (readOnly)
			{
				throw new ConfigurationErrorsException("The configuration is read only");
			}
			base.AddRange(range);
			modified = true;
		}

		public new void Clear()
		{
			if (readOnly)
			{
				throw new ConfigurationErrorsException("The configuration is read only");
			}
			base.Clear();
			modified = true;
		}

		public CommaDelimitedStringCollection Clone()
		{
			CommaDelimitedStringCollection commaDelimitedStringCollection = new CommaDelimitedStringCollection();
			string[] array = new string[base.Count];
			CopyTo(array, 0);
			commaDelimitedStringCollection.AddRange(array);
			commaDelimitedStringCollection.originalStringHash = originalStringHash;
			return commaDelimitedStringCollection;
		}

		public new void Insert(int index, string value)
		{
			if (readOnly)
			{
				throw new ConfigurationErrorsException("The configuration is read only");
			}
			base.Insert(index, value);
			modified = true;
		}

		public new void Remove(string value)
		{
			if (readOnly)
			{
				throw new ConfigurationErrorsException("The configuration is read only");
			}
			base.Remove(value);
			modified = true;
		}

		public void SetReadOnly()
		{
			readOnly = true;
		}

		public override string ToString()
		{
			if (base.Count == 0)
			{
				return null;
			}
			string[] array = new string[base.Count];
			CopyTo(array, 0);
			return string.Join(",", array);
		}

		internal void UpdateStringHash()
		{
			string text = ToString();
			if (text == null)
			{
				originalStringHash = 0;
			}
			else
			{
				originalStringHash = text.GetHashCode();
			}
		}
	}
	public sealed class CommaDelimitedStringCollectionConverter : ConfigurationConverterBase
	{
		public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
		{
			CommaDelimitedStringCollection commaDelimitedStringCollection = new CommaDelimitedStringCollection();
			string[] array = ((string)data).Split(',');
			foreach (string text in array)
			{
				commaDelimitedStringCollection.Add(text.Trim());
			}
			commaDelimitedStringCollection.UpdateStringHash();
			return commaDelimitedStringCollection;
		}

		public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
		{
			if (value == null)
			{
				return null;
			}
			if (!typeof(StringCollection).IsAssignableFrom(value.GetType()))
			{
				throw new ArgumentException();
			}
			return value.ToString();
		}
	}
	internal class ConfigNameValueCollection : NameValueCollection
	{
		private bool modified;

		public bool IsModified => modified;

		public ConfigNameValueCollection()
		{
		}

		public ConfigNameValueCollection(ConfigNameValueCollection col)
			: base(col.Count, col)
		{
		}

		public void ResetModified()
		{
			modified = false;
		}

		public override void Set(string name, string value)
		{
			base.Set(name, value);
			modified = true;
		}
	}
	internal abstract class ConfigInfo
	{
		public string Name;

		public string TypeName;

		protected Type Type;

		private string streamName;

		public ConfigInfo Parent;

		public IInternalConfigHost ConfigHost;

		public string XPath
		{
			get
			{
				StringBuilder stringBuilder = new StringBuilder(Name);
				for (ConfigInfo parent = Parent; parent != null; parent = parent.Parent)
				{
					stringBuilder.Insert(0, parent.Name + "/");
				}
				return stringBuilder.ToString();
			}
		}

		public string StreamName
		{
			get
			{
				return streamName;
			}
			set
			{
				streamName = value;
			}
		}

		public virtual object CreateInstance()
		{
			if (Type == null)
			{
				Type = ConfigHost.GetConfigType(TypeName, throwOnError: true);
			}
			return Activator.CreateInstance(Type, nonPublic: true);
		}

		public abstract bool HasConfigContent(Configuration cfg);

		public abstract bool HasDataContent(Configuration cfg);

		protected void ThrowException(string text, XmlReader reader)
		{
			throw new ConfigurationErrorsException(text, reader);
		}

		public abstract void ReadConfig(Configuration cfg, string streamName, XmlReader reader);

		public abstract void WriteConfig(Configuration cfg, XmlWriter writer, ConfigurationSaveMode mode);

		public abstract void ReadData(Configuration config, XmlReader reader, bool overrideAllowed);

		public abstract void WriteData(Configuration config, XmlWriter writer, ConfigurationSaveMode mode);

		internal abstract void Merge(ConfigInfo data);

		internal abstract bool HasValues(Configuration config, ConfigurationSaveMode mode);

		internal abstract void ResetModified(Configuration config);
	}
	internal class ConfigurationXmlDocument : XmlDocument
	{
		public override XmlElement CreateElement(string prefix, string localName, string namespaceURI)
		{
			if (namespaceURI == "http://schemas.microsoft.com/.NetConfiguration/v2.0")
			{
				return base.CreateElement(string.Empty, localName, string.Empty);
			}
			return base.CreateElement(prefix, localName, namespaceURI);
		}
	}
	public sealed class Configuration
	{
		private Configuration parent;

		private Hashtable elementData;

		private string streamName;

		private ConfigurationSectionGroup rootSectionGroup;

		private ConfigurationLocationCollection locations;

		private SectionGroupInfo rootGroup;

		private IConfigSystem system;

		private bool hasFile;

		private string rootNamespace;

		private string configPath;

		private string locationConfigPath;

		private string locationSubPath;

		private ContextInformation evaluationContext;

		internal Configuration Parent
		{
			get
			{
				return parent;
			}
			set
			{
				parent = value;
			}
		}

		internal string FileName => streamName;

		internal IInternalConfigHost ConfigHost => system.Host;

		internal string LocationConfigPath => locationConfigPath;

		internal string ConfigPath => configPath;

		public AppSettingsSection AppSettings => (AppSettingsSection)GetSection("appSettings");

		public ConnectionStringsSection ConnectionStrings => (ConnectionStringsSection)GetSection("connectionStrings");

		public string FilePath
		{
			get
			{
				if (streamName == null && parent != null)
				{
					return parent.FilePath;
				}
				return streamName;
			}
		}

		public bool HasFile => hasFile;

		public ContextInformation EvaluationContext
		{
			get
			{
				if (evaluationContext == null)
				{
					object ctx = system.Host.CreateConfigurationContext(configPath, GetLocationSubPath());
					evaluationContext = new ContextInformation(this, ctx);
				}
				return evaluationContext;
			}
		}

		public ConfigurationLocationCollection Locations
		{
			get
			{
				if (locations == null)
				{
					locations = new ConfigurationLocationCollection();
				}
				return locations;
			}
		}

		public bool NamespaceDeclared
		{
			get
			{
				return rootNamespace != null;
			}
			set
			{
				rootNamespace = (value ? "http://schemas.microsoft.com/.NetConfiguration/v2.0" : null);
			}
		}

		public ConfigurationSectionGroup RootSectionGroup
		{
			get
			{
				if (rootSectionGroup == null)
				{
					rootSectionGroup = new ConfigurationSectionGroup();
					rootSectionGroup.Initialize(this, rootGroup);
				}
				return rootSectionGroup;
			}
		}

		public ConfigurationSectionGroupCollection SectionGroups => RootSectionGroup.SectionGroups;

		public ConfigurationSectionCollection Sections => RootSectionGroup.Sections;

		public Func<string, string> AssemblyStringTransformer
		{
			get
			{
				//IL_0007: Expected O, but got I4
				ThrowStub.ThrowNotSupportedException();
				return (Func<string, string>)0;
			}
			[ConfigurationPermission(SecurityAction.Demand, Unrestricted = true)]
			set
			{
				ThrowStub.ThrowNotSupportedException();
			}
		}

		public FrameworkName TargetFramework
		{
			get
			{
				ThrowStub.ThrowNotSupportedException();
				return null;
			}
			[ConfigurationPermission(SecurityAction.Demand, Unrestricted = true)]
			set
			{
				ThrowStub.ThrowNotSupportedException();
			}
		}

		public Func<string, string> TypeStringTransformer
		{
			get
			{
				//IL_0007: Expected O, but got I4
				ThrowStub.ThrowNotSupportedException();
				return (Func<string, string>)0;
			}
			[ConfigurationPermission(SecurityAction.Demand, Unrestricted = true)]
			set
			{
				ThrowStub.ThrowNotSupportedException();
			}
		}

		internal static event ConfigurationSaveEventHandler SaveStart;

		internal static event ConfigurationSaveEventHandler SaveEnd;

		internal Configuration(Configuration parent, string locationSubPath)
		{
			elementData = new Hashtable();
			base..ctor();
			this.parent = parent;
			system = parent.system;
			rootGroup = parent.rootGroup;
			this.locationSubPath = locationSubPath;
			configPath = parent.ConfigPath;
		}

		internal Configuration(InternalConfigurationSystem system, string locationSubPath)
		{
			elementData = new Hashtable();
			base..ctor();
			hasFile = true;
			this.system = system;
			system.InitForConfiguration(ref locationSubPath, out configPath, out locationConfigPath);
			Configuration configuration = null;
			if (locationSubPath != null)
			{
				configuration = new Configuration(system, locationSubPath);
				if (locationConfigPath != null)
				{
					configuration = configuration.FindLocationConfiguration(locationConfigPath, configuration);
				}
			}
			Init(system, configPath, configuration);
		}

		internal Configuration FindLocationConfiguration(string relativePath, Configuration defaultConfiguration)
		{
			Configuration configuration = defaultConfiguration;
			if (!string.IsNullOrEmpty(LocationConfigPath))
			{
				Configuration parentWithFile = GetParentWithFile();
				if (parentWithFile != null)
				{
					string configPathFromLocationSubPath = system.Host.GetConfigPathFromLocationSubPath(configPath, relativePath);
					configuration = parentWithFile.FindLocationConfiguration(configPathFromLocationSubPath, defaultConfiguration);
				}
			}
			string text = configPath.Substring(1) + "/";
			if (relativePath.StartsWith(text, StringComparison.Ordinal))
			{
				relativePath = relativePath.Substring(text.Length);
			}
			ConfigurationLocation configurationLocation = Locations.FindBest(relativePath);
			if (configurationLocation == null)
			{
				return configuration;
			}
			configurationLocation.SetParentConfiguration(configuration);
			return configurationLocation.OpenConfiguration();
		}

		internal void Init(IConfigSystem system, string configPath, Configuration parent)
		{
			this.system = system;
			this.configPath = configPath;
			streamName = system.Host.GetStreamName(configPath);
			this.parent = parent;
			if (parent != null)
			{
				rootGroup = parent.rootGroup;
			}
			else
			{
				rootGroup = new SectionGroupInfo();
				rootGroup.StreamName = streamName;
			}
			try
			{
				if (streamName != null)
				{
					Load();
				}
			}
			catch (XmlException ex)
			{
				throw new ConfigurationErrorsException(ex.Message, ex, streamName, 0);
			}
		}

		internal Configuration GetParentWithFile()
		{
			Configuration configuration = Parent;
			while (configuration != null && !configuration.HasFile)
			{
				configuration = configuration.Parent;
			}
			return configuration;
		}

		internal string GetLocationSubPath()
		{
			Configuration configuration = parent;
			string text = null;
			while (configuration != null)
			{
				text = configuration.locationSubPath;
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
				configuration = configuration.parent;
			}
			return text;
		}

		public ConfigurationSection GetSection(string sectionName)
		{
			string[] array = sectionName.Split('/');
			if (array.Length == 1)
			{
				return Sections[array[0]];
			}
			ConfigurationSectionGroup configurationSectionGroup = SectionGroups[array[0]];
			int num = 1;
			while (configurationSectionGroup != null && num < array.Length - 1)
			{
				configurationSectionGroup = configurationSectionGroup.SectionGroups[array[num]];
				num++;
			}
			return configurationSectionGroup?.Sections[array[^1]];
		}

		public ConfigurationSectionGroup GetSectionGroup(string sectionGroupName)
		{
			string[] array = sectionGroupName.Split('/');
			ConfigurationSectionGroup configurationSectionGroup = SectionGroups[array[0]];
			int num = 1;
			while (configurationSectionGroup != null && num < array.Length)
			{
				configurationSectionGroup = configurationSectionGroup.SectionGroups[array[num]];
				num++;
			}
			return configurationSectionGroup;
		}

		internal ConfigurationSection GetSectionInstance(SectionInfo config, bool createDefaultInstance)
		{
			object obj = elementData[config];
			ConfigurationSection configurationSection = obj as ConfigurationSection;
			if (configurationSection != null || !createDefaultInstance)
			{
				return configurationSection;
			}
			object obj2 = config.CreateInstance();
			configurationSection = obj2 as ConfigurationSection;
			if (configurationSection == null)
			{
				configurationSection = new DefaultSection
				{
					SectionHandler = (IConfigurationSectionHandler)((obj2 is IConfigurationSectionHandler) ? obj2 : null)
				};
			}
			configurationSection.Configuration = this;
			ConfigurationSection configurationSection2 = null;
			if (parent != null)
			{
				configurationSection2 = parent.GetSectionInstance(config, createDefaultInstance: true);
				configurationSection.SectionInformation.SetParentSection(configurationSection2);
			}
			configurationSection.SectionInformation.ConfigFilePath = FilePath;
			configurationSection.ConfigContext = system.Host.CreateDeprecatedConfigContext(configPath);
			string text2 = (configurationSection.RawXml = obj as string);
			configurationSection.Reset(configurationSection2);
			if (text2 != null)
			{
				XmlTextReader xmlTextReader = new ConfigXmlTextReader(new StringReader(text2), FilePath);
				configurationSection.DeserializeSection(xmlTextReader);
				xmlTextReader.Close();
				if (!string.IsNullOrEmpty(configurationSection.SectionInformation.ConfigSource) && !string.IsNullOrEmpty(FilePath))
				{
					configurationSection.DeserializeConfigSource(Path.GetDirectoryName(FilePath));
				}
			}
			elementData[config] = configurationSection;
			return configurationSection;
		}

		internal ConfigurationSectionGroup GetSectionGroupInstance(SectionGroupInfo group)
		{
			ConfigurationSectionGroup configurationSectionGroup = group.CreateInstance() as ConfigurationSectionGroup;
			configurationSectionGroup?.Initialize(this, group);
			return configurationSectionGroup;
		}

		internal void SetConfigurationSection(SectionInfo config, ConfigurationSection sec)
		{
			elementData[config] = sec;
		}

		internal void SetSectionXml(SectionInfo config, string data)
		{
			elementData[config] = data;
		}

		internal string GetSectionXml(SectionInfo config)
		{
			return elementData[config] as string;
		}

		internal void CreateSection(SectionGroupInfo group, string name, ConfigurationSection sec)
		{
			if (group.HasChild(name))
			{
				throw new ConfigurationErrorsException("Cannot add a ConfigurationSection. A section or section group already exists with the name '" + name + "'");
			}
			if (!HasFile && !sec.SectionInformation.AllowLocation)
			{
				throw new ConfigurationErrorsException("The configuration section <" + name + "> cannot be defined inside a <location> element.");
			}
			if (!system.Host.IsDefinitionAllowed(configPath, sec.SectionInformation.AllowDefinition, sec.SectionInformation.AllowExeDefinition))
			{
				object obj = ((sec.SectionInformation.AllowExeDefinition != ConfigurationAllowExeDefinition.MachineToApplication) ? ((object)sec.SectionInformation.AllowExeDefinition) : ((object)sec.SectionInformation.AllowDefinition));
				throw new ConfigurationErrorsException("The section <" + name + "> can't be defined in this configuration file (the allowed definition context is '" + obj?.ToString() + "').");
			}
			if (sec.SectionInformation.Type == null)
			{
				sec.SectionInformation.Type = system.Host.GetConfigTypeName(sec.GetType());
			}
			SectionInfo sectionInfo = new SectionInfo(name, sec.SectionInformation);
			sectionInfo.StreamName = streamName;
			sectionInfo.ConfigHost = system.Host;
			group.AddChild(sectionInfo);
			elementData[sectionInfo] = sec;
			sec.Configuration = this;
		}

		internal void CreateSectionGroup(SectionGroupInfo parentGroup, string name, ConfigurationSectionGroup sec)
		{
			if (parentGroup.HasChild(name))
			{
				throw new ConfigurationErrorsException("Cannot add a ConfigurationSectionGroup. A section or section group already exists with the name '" + name + "'");
			}
			if (sec.Type == null)
			{
				sec.Type = system.Host.GetConfigTypeName(sec.GetType());
			}
			sec.SetName(name);
			SectionGroupInfo sectionGroupInfo = new SectionGroupInfo(name, sec.Type);
			sectionGroupInfo.StreamName = streamName;
			sectionGroupInfo.ConfigHost = system.Host;
			parentGroup.AddChild(sectionGroupInfo);
			elementData[sectionGroupInfo] = sec;
			sec.Initialize(this, sectionGroupInfo);
		}

		internal void RemoveConfigInfo(ConfigInfo config)
		{
			elementData.Remove(config);
		}

		public void Save()
		{
			Save(ConfigurationSaveMode.Modified, forceSaveAll: false);
		}

		public void Save(ConfigurationSaveMode saveMode)
		{
			Save(saveMode, forceSaveAll: false);
		}

		public void Save(ConfigurationSaveMode saveMode, bool forceSaveAll)
		{
			if (!forceSaveAll && saveMode != ConfigurationSaveMode.Full && !HasValues(saveMode))
			{
				ResetModified();
				return;
			}
			ConfigurationSaveEventHandler saveStart = Configuration.SaveStart;
			ConfigurationSaveEventHandler saveEnd = Configuration.SaveEnd;
			object writeContext = null;
			Exception ex = null;
			Stream stream = system.Host.OpenStreamForWrite(streamName, null, ref writeContext);
			try
			{
				saveStart?.Invoke(this, new ConfigurationSaveEventArgs(streamName, start: true, null, writeContext));
				Save(stream, saveMode, forceSaveAll);
				system.Host.WriteCompleted(streamName, success: true, writeContext);
			}
			catch (Exception ex2)
			{
				ex = ex2;
				system.Host.WriteCompleted(streamName, success: false, writeContext);
				throw;
			}
			finally
			{
				stream.Close();
				saveEnd?.Invoke(this, new ConfigurationSaveEventArgs(streamName, start: false, ex, writeContext));
			}
		}

		public void SaveAs(string filename)
		{
			SaveAs(filename, ConfigurationSaveMode.Modified, forceSaveAll: false);
		}

		public void SaveAs(string filename, ConfigurationSaveMode saveMode)
		{
			SaveAs(filename, saveMode, forceSaveAll: false);
		}

		[MonoInternalNote("Detect if file has changed")]
		public void SaveAs(string filename, ConfigurationSaveMode saveMode, bool forceSaveAll)
		{
			if (!forceSaveAll && saveMode != ConfigurationSaveMode.Full && !HasValues(saveMode))
			{
				ResetModified();
				return;
			}
			string directoryName = Path.GetDirectoryName(Path.GetFullPath(filename));
			if (!Directory.Exists(directoryName))
			{
				Directory.CreateDirectory(directoryName);
			}
			Save(new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write), saveMode, forceSaveAll);
		}

		private void Save(Stream stream, ConfigurationSaveMode mode, bool forceUpdateAll)
		{
			XmlTextWriter xmlTextWriter = new XmlTextWriter(new StreamWriter(stream));
			xmlTextWriter.Formatting = Formatting.Indented;
			try
			{
				xmlTextWriter.WriteStartDocument();
				if (rootNamespace != null)
				{
					xmlTextWriter.WriteStartElement("configuration", rootNamespace);
				}
				else
				{
					xmlTextWriter.WriteStartElement("configuration");
				}
				if (rootGroup.HasConfigContent(this))
				{
					rootGroup.WriteConfig(this, xmlTextWriter, mode);
				}
				foreach (ConfigurationLocation location in Locations)
				{
					if (location.OpenedConfiguration == null)
					{
						xmlTextWriter.WriteRaw("\n");
						xmlTextWriter.WriteRaw(location.XmlContent);
						continue;
					}
					xmlTextWriter.WriteStartElement("location");
					xmlTextWriter.WriteAttributeString("path", location.Path);
					if (!location.AllowOverride)
					{
						xmlTextWriter.WriteAttributeString("allowOverride", "false");
					}
					location.OpenedConfiguration.SaveData(xmlTextWriter, mode, forceUpdateAll);
					xmlTextWriter.WriteEndElement();
				}
				SaveData(xmlTextWriter, mode, forceUpdateAll);
				xmlTextWriter.WriteEndElement();
				ResetModified();
			}
			finally
			{
				xmlTextWriter.Flush();
				xmlTextWriter.Close();
			}
		}

		private void SaveData(XmlTextWriter tw, ConfigurationSaveMode mode, bool forceUpdateAll)
		{
			rootGroup.WriteRootData(tw, this, mode);
		}

		private bool HasValues(ConfigurationSaveMode mode)
		{
			foreach (ConfigurationLocation location in Locations)
			{
				if (location.OpenedConfiguration != null && location.OpenedConfiguration.HasValues(mode))
				{
					return true;
				}
			}
			return rootGroup.HasValues(this, mode);
		}

		private void ResetModified()
		{
			foreach (ConfigurationLocation location in Locations)
			{
				if (location.OpenedConfiguration != null)
				{
					location.OpenedConfiguration.ResetModified();
				}
			}
			rootGroup.ResetModified(this);
		}

		private bool Load()
		{
			if (string.IsNullOrEmpty(streamName))
			{
				return true;
			}
			Stream stream = null;
			try
			{
				stream = system.Host.OpenStreamForRead(streamName);
				if (stream == null)
				{
					return false;
				}
			}
			catch
			{
				return false;
			}
			using (XmlTextReader reader = new ConfigXmlTextReader(stream, streamName))
			{
				ReadConfigFile(reader, streamName);
			}
			ResetModified();
			return true;
		}

		private void ReadConfigFile(XmlReader reader, string fileName)
		{
			reader.MoveToContent();
			if (reader.NodeType != XmlNodeType.Element || reader.Name != "configuration")
			{
				ThrowException("Configuration file does not have a valid root element", reader);
			}
			if (reader.HasAttributes)
			{
				while (reader.MoveToNextAttribute())
				{
					if (reader.LocalName == "xmlns")
					{
						rootNamespace = reader.Value;
					}
					else
					{
						ThrowException($"Unrecognized attribute '{reader.LocalName}' in root element", reader);
					}
				}
			}
			reader.MoveToElement();
			if (reader.IsEmptyElement)
			{
				reader.Skip();
				return;
			}
			reader.ReadStartElement();
			reader.MoveToContent();
			if (reader.LocalName == "configSections")
			{
				if (reader.HasAttributes)
				{
					ThrowException("Unrecognized attribute in <configSections>.", reader);
				}
				rootGroup.ReadConfig(this, fileName, reader);
			}
			rootGroup.ReadRootData(reader, this, overrideAllowed: true);
		}

		internal void ReadData(XmlReader reader, bool allowOverride)
		{
			rootGroup.ReadData(this, reader, allowOverride);
		}

		private void ThrowException(string text, XmlReader reader)
		{
			throw new ConfigurationErrorsException(text, streamName, (reader as IXmlLineInfo)?.LineNumber ?? 0);
		}

		internal Configuration()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	public enum ConfigurationAllowDefinition
	{
		MachineOnly = 0,
		MachineToWebRoot = 100,
		MachineToApplication = 200,
		Everywhere = 300
	}
	public enum ConfigurationAllowExeDefinition
	{
		MachineOnly = 0,
		MachineToApplication = 100,
		MachineToLocalUser = 300,
		MachineToRoamingUser = 200
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property)]
	public sealed class ConfigurationCollectionAttribute : Attribute
	{
		private string addItemName = "add";

		private string clearItemsName = "clear";

		private string removeItemName = "remove";

		private ConfigurationElementCollectionType collectionType;

		private Type itemType;

		public string AddItemName
		{
			get
			{
				return addItemName;
			}
			set
			{
				addItemName = value;
			}
		}

		public string ClearItemsName
		{
			get
			{
				return clearItemsName;
			}
			set
			{
				clearItemsName = value;
			}
		}

		public string RemoveItemName
		{
			get
			{
				return removeItemName;
			}
			set
			{
				removeItemName = value;
			}
		}

		public ConfigurationElementCollectionType CollectionType
		{
			get
			{
				return collectionType;
			}
			set
			{
				collectionType = value;
			}
		}

		[MonoInternalNote("Do something with this in ConfigurationElementCollection")]
		public Type ItemType => itemType;

		public ConfigurationCollectionAttribute(Type itemType)
		{
			this.itemType = itemType;
		}
	}
	public abstract class ConfigurationConverterBase : TypeConverter
	{
		public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type type)
		{
			if (type == typeof(string))
			{
				return true;
			}
			return base.CanConvertFrom(ctx, type);
		}

		public override bool CanConvertTo(ITypeDescriptorContext ctx, Type type)
		{
			if (type == typeof(string))
			{
				return true;
			}
			return base.CanConvertTo(ctx, type);
		}
	}
	public abstract class ConfigurationElement
	{
		private class SaveContext
		{
			public readonly ConfigurationElement Element;

			public readonly ConfigurationElement Parent;

			public readonly ConfigurationSaveMode Mode;

			public SaveContext(ConfigurationElement element, ConfigurationElement parent, ConfigurationSaveMode mode)
			{
				Element = element;
				Parent = parent;
				Mode = mode;
			}

			public bool HasValues()
			{
				if (Mode == ConfigurationSaveMode.Full)
				{
					return true;
				}
				return Element.HasValues(Parent, Mode);
			}

			public bool HasValue(PropertyInformation prop)
			{
				if (Mode == ConfigurationSaveMode.Full)
				{
					return true;
				}
				return Element.HasValue(Parent, prop, Mode);
			}
		}

		private string rawXml;

		private bool modified;

		private ElementMap map;

		private ConfigurationPropertyCollection keyProps;

		private ConfigurationElementCollection defaultCollection;

		private bool readOnly;

		private ElementInformation elementInfo;

		private ConfigurationElementProperty elementProperty;

		private Configuration _configuration;

		private bool elementPresent;

		private ConfigurationLockCollection lockAllAttributesExcept;

		private ConfigurationLockCollection lockAllElementsExcept;

		private ConfigurationLockCollection lockAttributes;

		private ConfigurationLockCollection lockElements;

		private bool lockItem;

		private SaveContext saveContext;

		internal Configuration Configuration
		{
			get
			{
				return _configuration;
			}
			set
			{
				_configuration = value;
			}
		}

		public ElementInformation ElementInformation
		{
			get
			{
				if (elementInfo == null)
				{
					elementInfo = new ElementInformation(this, null);
				}
				return elementInfo;
			}
		}

		internal string RawXml
		{
			get
			{
				return rawXml;
			}
			set
			{
				if (rawXml == null || value != null)
				{
					rawXml = value;
				}
			}
		}

		protected internal virtual ConfigurationElementProperty ElementProperty
		{
			get
			{
				if (elementProperty == null)
				{
					elementProperty = new ConfigurationElementProperty(ElementInformation.Validator);
				}
				return elementProperty;
			}
		}

		protected ContextInformation EvaluationContext
		{
			get
			{
				if (Configuration != null)
				{
					return Configuration.EvaluationContext;
				}
				throw new ConfigurationErrorsException("This element is not currently associated with any context.");
			}
		}

		public ConfigurationLockCollection LockAllAttributesExcept
		{
			get
			{
				if (lockAllAttributesExcept == null)
				{
					lockAllAttributesExcept = new ConfigurationLockCollection(this, ConfigurationLockType.Attribute | ConfigurationLockType.Exclude);
				}
				return lockAllAttributesExcept;
			}
		}

		public ConfigurationLockCollection LockAllElementsExcept
		{
			get
			{
				if (lockAllElementsExcept == null)
				{
					lockAllElementsExcept = new ConfigurationLockCollection(this, ConfigurationLockType.Element | ConfigurationLockType.Exclude);
				}
				return lockAllElementsExcept;
			}
		}

		public ConfigurationLockCollection LockAttributes
		{
			get
			{
				if (lockAttributes == null)
				{
					lockAttributes = new ConfigurationLockCollection(this, ConfigurationLockType.Attribute);
				}
				return lockAttributes;
			}
		}

		public ConfigurationLockCollection LockElements
		{
			get
			{
				if (lockElements == null)
				{
					lockElements = new ConfigurationLockCollection(this, ConfigurationLockType.Element);
				}
				return lockElements;
			}
		}

		public bool LockItem
		{
			get
			{
				return lockItem;
			}
			set
			{
				lockItem = value;
			}
		}

		protected internal object this[ConfigurationProperty prop]
		{
			get
			{
				return this[prop.Name];
			}
			set
			{
				this[prop.Name] = value;
			}
		}

		protected internal object this[string propertyName]
		{
			get
			{
				return (ElementInformation.Properties[propertyName] ?? throw new InvalidOperationException("Property '" + propertyName + "' not found in configuration element")).Value;
			}
			set
			{
				PropertyInformation propertyInformation = ElementInformation.Properties[propertyName];
				if (propertyInformation == null)
				{
					throw new InvalidOperationException("Property '" + propertyName + "' not found in configuration element");
				}
				SetPropertyValue(propertyInformation.Property, value, ignoreLocks: false);
				propertyInformation.Value = value;
				modified = true;
			}
		}

		protected internal virtual ConfigurationPropertyCollection Properties
		{
			get
			{
				if (map == null)
				{
					map = ElementMap.GetMap(GetType());
				}
				return map.Properties;
			}
		}

		internal bool IsElementPresent => elementPresent;

		public Configuration CurrentConfiguration
		{
			get
			{
				ThrowStub.ThrowNotSupportedException();
				return null;
			}
		}

		protected bool HasContext
		{
			get
			{
				ThrowStub.ThrowNotSupportedException();
				return default(bool);
			}
		}

		internal virtual void InitFromProperty(PropertyInformation propertyInfo)
		{
			elementInfo = new ElementInformation(this, propertyInfo);
			Init();
		}

		protected internal virtual void Init()
		{
		}

		[MonoTODO]
		protected virtual void ListErrors(IList errorList)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		protected void SetPropertyValue(ConfigurationProperty prop, object value, bool ignoreLocks)
		{
			try
			{
				if (value != null)
				{
					prop.Validate(value);
				}
			}
			catch (Exception inner)
			{
				throw new ConfigurationErrorsException($"The value for the property '{prop.Name}' on type {ElementInformation.Type} is not valid.", inner);
			}
		}

		internal ConfigurationPropertyCollection GetKeyProperties()
		{
			if (keyProps != null)
			{
				return keyProps;
			}
			ConfigurationPropertyCollection configurationPropertyCollection = new ConfigurationPropertyCollection();
			foreach (ConfigurationProperty property in Properties)
			{
				if (property.IsKey)
				{
					configurationPropertyCollection.Add(property);
				}
			}
			return keyProps = configurationPropertyCollection;
		}

		internal ConfigurationElementCollection GetDefaultCollection()
		{
			if (defaultCollection != null)
			{
				return defaultCollection;
			}
			ConfigurationProperty configurationProperty = null;
			foreach (ConfigurationProperty property in Properties)
			{
				if (property.IsDefaultCollection)
				{
					configurationProperty = property;
					break;
				}
			}
			if (configurationProperty != null)
			{
				defaultCollection = this[configurationProperty] as ConfigurationElementCollection;
			}
			return defaultCollection;
		}

		public override bool Equals(object compareTo)
		{
			if (!(compareTo is ConfigurationElement configurationElement))
			{
				return false;
			}
			if (GetType() != configurationElement.GetType())
			{
				return false;
			}
			foreach (ConfigurationProperty property in Properties)
			{
				if (!object.Equals(this[property], configurationElement[property]))
				{
					return false;
				}
			}
			return true;
		}

		public override int GetHashCode()
		{
			int num = 0;
			foreach (ConfigurationProperty property in Properties)
			{
				object obj = this[property];
				if (obj != null)
				{
					num += obj.GetHashCode();
				}
			}
			return num;
		}

		internal virtual bool HasLocalModifications()
		{
			foreach (PropertyInformation property in ElementInformation.Properties)
			{
				if (property.ValueOrigin == PropertyValueOrigin.SetHere && property.IsModified)
				{
					return true;
				}
			}
			return false;
		}

		protected internal virtual void DeserializeElement(XmlReader reader, bool serializeCollectionKey)
		{
			Hashtable hashtable = new Hashtable();
			reader.MoveToContent();
			elementPresent = true;
			while (reader.MoveToNextAttribute())
			{
				PropertyInformation propertyInformation = ElementInformation.Properties[reader.LocalName];
				if (propertyInformation == null || (serializeCollectionKey && !propertyInformation.IsKey))
				{
					if (reader.LocalName == "lockAllAttributesExcept")
					{
						LockAllAttributesExcept.SetFromList(reader.Value);
					}
					else if (reader.LocalName == "lockAllElementsExcept")
					{
						LockAllElementsExcept.SetFromList(reader.Value);
					}
					else if (reader.LocalName == "lockAttributes")
					{
						LockAttributes.SetFromList(reader.Value);
					}
					else if (reader.LocalName == "lockElements")
					{
						LockElements.SetFromList(reader.Value);
					}
					else if (reader.LocalName == "lockItem")
					{
						LockItem = reader.Value.ToLowerInvariant() == "true";
					}
					else if (!(reader.LocalName == "xmlns") && (!(this is ConfigurationSection) || !(reader.LocalName == "configSource")) && !OnDeserializeUnrecognizedAttribute(reader.LocalName, reader.Value))
					{
						throw new ConfigurationErrorsException("Unrecognized attribute '" + reader.LocalName + "'.", reader);
					}
					continue;
				}
				if (hashtable.ContainsKey(propertyInformation))
				{
					throw new ConfigurationErrorsException("The attribute '" + propertyInformation.Name + "' may only appear once in this element.", reader);
				}
				string text = null;
				try
				{
					text = reader.Value;
					ValidateValue(propertyInformation.Property, text);
					propertyInformation.SetStringValue(text);
				}
				catch (ConfigurationErrorsException)
				{
					throw;
				}
				catch (ConfigurationException)
				{
					throw;
				}
				catch (Exception ex2)
				{
					throw new ConfigurationErrorsException($"The value for the property '{propertyInformation.Name}' is not valid. The error is: {ex2.Message}", reader);
				}
				hashtable[propertyInformation] = propertyInformation.Name;
				if (reader is ConfigXmlTextReader configXmlTextReader)
				{
					propertyInformation.Source = configXmlTextReader.Filename;
					propertyInformation.LineNumber = configXmlTextReader.LineNumber;
				}
			}
			reader.MoveToElement();
			if (reader.IsEmptyElement)
			{
				reader.Skip();
			}
			else
			{
				int depth = reader.Depth;
				reader.ReadStartElement();
				reader.MoveToContent();
				do
				{
					if (reader.NodeType != XmlNodeType.Element)
					{
						reader.Skip();
						continue;
					}
					PropertyInformation propertyInformation2 = ElementInformation.Properties[reader.LocalName];
					if (propertyInformation2 == null || (serializeCollectionKey && !propertyInformation2.IsKey))
					{
						if (OnDeserializeUnrecognizedElement(reader.LocalName, reader))
						{
							continue;
						}
						if (propertyInformation2 == null)
						{
							ConfigurationElementCollection configurationElementCollection = GetDefaultCollection();
							if (configurationElementCollection != null && configurationElementCollection.OnDeserializeUnrecognizedElement(reader.LocalName, reader))
							{
								continue;
							}
						}
						throw new ConfigurationErrorsException("Unrecognized element '" + reader.LocalName + "'.", reader);
					}
					if (!propertyInformation2.IsElement)
					{
						throw new ConfigurationErrorsException("Property '" + propertyInformation2.Name + "' is not a ConfigurationElement.");
					}
					if (hashtable.Contains(propertyInformation2))
					{
						throw new ConfigurationErrorsException("The element <" + propertyInformation2.Name + "> may only appear once in this section.", reader);
					}
					((ConfigurationElement)propertyInformation2.Value).DeserializeElement(reader, serializeCollectionKey);
					hashtable[propertyInformation2] = propertyInformation2.Name;
					if (depth == reader.Depth)
					{
						reader.Read();
					}
				}
				while (depth < reader.Depth);
			}
			modified = false;
			foreach (PropertyInformation property in ElementInformation.Properties)
			{
				if (!string.IsNullOrEmpty(property.Name) && property.IsRequired && !hashtable.ContainsKey(property) && ElementInformation.Properties[property.Name] == null)
				{
					object obj = OnRequiredPropertyNotFound(property.Name);
					if (!object.Equals(obj, property.DefaultValue))
					{
						property.Value = obj;
						property.IsModified = false;
					}
				}
			}
			PostDeserialize();
		}

		protected virtual bool OnDeserializeUnrecognizedAttribute(string name, string value)
		{
			return false;
		}

		protected virtual bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader)
		{
			return false;
		}

		protected virtual object OnRequiredPropertyNotFound(string name)
		{
			throw new ConfigurationErrorsException("Required attribute '" + name + "' not found.");
		}

		protected virtual void PreSerialize(XmlWriter writer)
		{
		}

		protected virtual void PostDeserialize()
		{
		}

		protected internal virtual void InitializeDefault()
		{
		}

		protected internal virtual bool IsModified()
		{
			if (modified)
			{
				return true;
			}
			foreach (PropertyInformation property in ElementInformation.Properties)
			{
				if (property.IsElement && property.Value is ConfigurationElement configurationElement && configurationElement.IsModified())
				{
					modified = true;
					break;
				}
			}
			return modified;
		}

		protected internal virtual void SetReadOnly()
		{
			readOnly = true;
		}

		public virtual bool IsReadOnly()
		{
			return readOnly;
		}

		protected internal virtual void Reset(ConfigurationElement parentElement)
		{
			elementPresent = false;
			if (parentElement != null)
			{
				ElementInformation.Reset(parentElement.ElementInformation);
			}
			else
			{
				InitializeDefault();
			}
		}

		protected internal virtual void ResetModified()
		{
			modified = false;
			foreach (PropertyInformation property in ElementInformation.Properties)
			{
				property.IsModified = false;
				if (property.Value is ConfigurationElement configurationElement)
				{
					configurationElement.ResetModified();
				}
			}
		}

		protected internal virtual bool SerializeElement(XmlWriter writer, bool serializeCollectionKey)
		{
			PreSerialize(writer);
			if (serializeCollectionKey)
			{
				ConfigurationPropertyCollection keyProperties = GetKeyProperties();
				foreach (ConfigurationProperty item in keyProperties)
				{
					writer.WriteAttributeString(item.Name, item.ConvertToString(this[item.Name]));
				}
				return keyProperties.Count > 0;
			}
			bool flag = false;
			foreach (PropertyInformation property in ElementInformation.Properties)
			{
				if (!property.IsElement)
				{
					if (saveContext == null)
					{
						throw new InvalidOperationException();
					}
					if (saveContext.HasValue(property))
					{
						writer.WriteAttributeString(property.Name, property.GetStringValue());
						flag = true;
					}
				}
			}
			foreach (PropertyInformation property2 in ElementInformation.Properties)
			{
				if (property2.IsElement)
				{
					ConfigurationElement configurationElement = (ConfigurationElement)property2.Value;
					if (configurationElement != null)
					{
						flag = configurationElement.SerializeToXmlElement(writer, property2.Name) || flag;
					}
				}
			}
			return flag;
		}

		protected internal virtual bool SerializeToXmlElement(XmlWriter writer, string elementName)
		{
			if (saveContext == null)
			{
				throw new InvalidOperationException();
			}
			if (!saveContext.HasValues())
			{
				return false;
			}
			if (elementName != null && elementName != "")
			{
				writer.WriteStartElement(elementName);
			}
			bool result = SerializeElement(writer, serializeCollectionKey: false);
			if (elementName != null && elementName != "")
			{
				writer.WriteEndElement();
			}
			return result;
		}

		protected internal virtual void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
		{
			if (parentElement != null && sourceElement.GetType() != parentElement.GetType())
			{
				throw new ConfigurationErrorsException("Can't unmerge two elements of different type");
			}
			bool flag = saveMode == ConfigurationSaveMode.Minimal || saveMode == ConfigurationSaveMode.Modified;
			foreach (PropertyInformation property in sourceElement.ElementInformation.Properties)
			{
				if (property.ValueOrigin == PropertyValueOrigin.Default)
				{
					continue;
				}
				PropertyInformation propertyInformation2 = ElementInformation.Properties[property.Name];
				object value = property.Value;
				if (parentElement == null || !parentElement.HasValue(property.Name))
				{
					propertyInformation2.Value = value;
				}
				else
				{
					if (value == null)
					{
						continue;
					}
					object obj = parentElement[property.Name];
					if (!property.IsElement)
					{
						if (!object.Equals(value, obj) || saveMode == ConfigurationSaveMode.Full || (saveMode == ConfigurationSaveMode.Modified && property.ValueOrigin == PropertyValueOrigin.SetHere))
						{
							propertyInformation2.Value = value;
						}
						continue;
					}
					ConfigurationElement configurationElement = (ConfigurationElement)value;
					if (!flag || configurationElement.IsModified())
					{
						if (obj == null)
						{
							propertyInformation2.Value = value;
							continue;
						}
						ConfigurationElement parentElement2 = (ConfigurationElement)obj;
						((ConfigurationElement)propertyInformation2.Value).Unmerge(configurationElement, parentElement2, saveMode);
					}
				}
			}
		}

		internal bool HasValue(string propName)
		{
			PropertyInformation propertyInformation = ElementInformation.Properties[propName];
			if (propertyInformation != null)
			{
				return propertyInformation.ValueOrigin != PropertyValueOrigin.Default;
			}
			return false;
		}

		internal bool IsReadFromConfig(string propName)
		{
			PropertyInformation propertyInformation = ElementInformation.Properties[propName];
			if (propertyInformation != null)
			{
				return propertyInformation.ValueOrigin == PropertyValueOrigin.SetHere;
			}
			return false;
		}

		private void ValidateValue(ConfigurationProperty p, string value)
		{
			ConfigurationValidatorBase validator;
			if (p != null && (validator = p.Validator) != null)
			{
				if (!validator.CanValidate(p.Type))
				{
					throw new ConfigurationErrorsException($"Validator does not support type {p.Type}");
				}
				validator.Validate(p.ConvertFromString(value));
			}
		}

		internal bool HasValue(ConfigurationElement parent, PropertyInformation prop, ConfigurationSaveMode mode)
		{
			if (prop.ValueOrigin == PropertyValueOrigin.Default)
			{
				return false;
			}
			if (mode == ConfigurationSaveMode.Modified && prop.ValueOrigin == PropertyValueOrigin.SetHere && prop.IsModified)
			{
				return true;
			}
			object obj = ((parent != null && parent.HasValue(prop.Name)) ? parent[prop.Name] : prop.DefaultValue);
			if (!prop.IsElement)
			{
				return !object.Equals(prop.Value, obj);
			}
			ConfigurationElement obj2 = (ConfigurationElement)prop.Value;
			ConfigurationElement parent2 = (ConfigurationElement)obj;
			return obj2.HasValues(parent2, mode);
		}

		internal virtual bool HasValues(ConfigurationElement parent, ConfigurationSaveMode mode)
		{
			if (mode == ConfigurationSaveMode.Full)
			{
				return true;
			}
			if (modified && mode == ConfigurationSaveMode.Modified)
			{
				return true;
			}
			foreach (PropertyInformation property in ElementInformation.Properties)
			{
				if (HasValue(parent, property, mode))
				{
					return true;
				}
			}
			return false;
		}

		internal virtual void PrepareSave(ConfigurationElement parent, ConfigurationSaveMode mode)
		{
			saveContext = new SaveContext(this, parent, mode);
			foreach (PropertyInformation property in ElementInformation.Properties)
			{
				if (property.IsElement)
				{
					ConfigurationElement configurationElement = (ConfigurationElement)property.Value;
					if (parent == null || !parent.HasValue(property.Name))
					{
						configurationElement.PrepareSave(null, mode);
						continue;
					}
					ConfigurationElement parent2 = (ConfigurationElement)parent[property.Name];
					configurationElement.PrepareSave(parent2, mode);
				}
			}
		}

		protected virtual string GetTransformedAssemblyString(string assemblyName)
		{
			ThrowStub.ThrowNotSupportedException();
			return null;
		}

		protected virtual string GetTransformedTypeString(string typeName)
		{
			ThrowStub.ThrowNotSupportedException();
			return null;
		}
	}
	internal class ElementMap
	{
		private static readonly Hashtable elementMaps = Hashtable.Synchronized(new Hashtable());

		private readonly ConfigurationPropertyCollection properties;

		private readonly ConfigurationCollectionAttribute collectionAttribute;

		public ConfigurationCollectionAttribute CollectionAttribute => collectionAttribute;

		public bool HasProperties => properties.Count > 0;

		public ConfigurationPropertyCollection Properties => properties;

		public static ElementMap GetMap(Type t)
		{
			if (elementMaps[t] is ElementMap result)
			{
				return result;
			}
			ElementMap elementMap = new ElementMap(t);
			elementMaps[t] = elementMap;
			return elementMap;
		}

		public ElementMap(Type t)
		{
			properties = new ConfigurationPropertyCollection();
			collectionAttribute = Attribute.GetCustomAttribute(t, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
			PropertyInfo[] array = t.GetProperties(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in array)
			{
				if (Attribute.GetCustomAttribute(propertyInfo, typeof(ConfigurationPropertyAttribute)) is ConfigurationPropertyAttribute configurationPropertyAttribute)
				{
					string name = ((configurationPropertyAttribute.Name != null) ? configurationPropertyAttribute.Name : propertyInfo.Name);
					ConfigurationValidatorBase validator = ((Attribute.GetCustomAttribute(propertyInfo, typeof(ConfigurationValidatorAttribute)) is ConfigurationValidatorAttribute configurationValidatorAttribute) ? configurationValidatorAttribute.ValidatorInstance : null);
					TypeConverterAttribute typeConverterAttribute = (TypeConverterAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(TypeConverterAttribute));
					ConfigurationProperty property = new ConfigurationProperty(typeConverter: (typeConverterAttribute != null) ? ((TypeConverter)Activator.CreateInstance(Type.GetType(typeConverterAttribute.ConverterTypeName), nonPublic: true)) : null, name: name, type: propertyInfo.PropertyType, defaultValue: configurationPropertyAttribute.DefaultValue, validator: validator, options: configurationPropertyAttribute.Options)
					{
						CollectionAttribute = (Attribute.GetCustomAttribute(propertyInfo, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute)
					};
					properties.Add(property);
				}
			}
		}
	}
	[DebuggerDisplay("Count = {Count}")]
	public abstract class ConfigurationElementCollection : ConfigurationElement, ICollection, IEnumerable
	{
		private sealed class ConfigurationRemoveElement : ConfigurationElement
		{
			private readonly ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();

			private readonly ConfigurationElement _origElement;

			private readonly ConfigurationElementCollection _origCollection;

			internal object KeyValue
			{
				get
				{
					foreach (ConfigurationProperty property in Properties)
					{
						_origElement[property] = base[property];
					}
					return _origCollection.GetElementKey(_origElement);
				}
			}

			protected internal override ConfigurationPropertyCollection Properties => properties;

			internal ConfigurationRemoveElement(ConfigurationElement origElement, ConfigurationElementCollection origCollection)
			{
				_origElement = origElement;
				_origCollection = origCollection;
				foreach (ConfigurationProperty property in origElement.Properties)
				{
					if (property.IsKey)
					{
						properties.Add(property);
					}
				}
			}
		}

		private ArrayList list = new ArrayList();

		private ArrayList removed;

		private ArrayList inherited;

		private bool emitClear;

		private bool modified;

		private IComparer comparer;

		private int inheritedLimitIndex;

		private string addElementName = "add";

		private string clearElementName = "clear";

		private string removeElementName = "remove";

		public virtual ConfigurationElementCollectionType CollectionType => ConfigurationElementCollectionType.AddRemoveClearMap;

		private bool IsBasic
		{
			get
			{
				if (CollectionType != 0)
				{
					return CollectionType == ConfigurationElementCollectionType.BasicMapAlternate;
				}
				return true;
			}
		}

		private bool IsAlternate
		{
			get
			{
				if (CollectionType != ConfigurationElementCollectionType.AddRemoveClearMapAlternate)
				{
					return CollectionType == ConfigurationElementCollectionType.BasicMapAlternate;
				}
				return true;
			}
		}

		public int Count => list.Count;

		protected virtual string ElementName => string.Empty;

		public bool EmitClear
		{
			get
			{
				return emitClear;
			}
			set
			{
				emitClear = value;
			}
		}

		public bool IsSynchronized => false;

		public object SyncRoot => this;

		protected virtual bool ThrowOnDuplicate
		{
			get
			{
				if (CollectionType != ConfigurationElementCollectionType.AddRemoveClearMap && CollectionType != ConfigurationElementCollectionType.AddRemoveClearMapAlternate)
				{
					return false;
				}
				return true;
			}
		}

		protected internal string AddElementName
		{
			get
			{
				return addElementName;
			}
			set
			{
				addElementName = value;
			}
		}

		protected internal string ClearElementName
		{
			get
			{
				return clearElementName;
			}
			set
			{
				clearElementName = value;
			}
		}

		protected internal string RemoveElementName
		{
			get
			{
				return removeElementName;
			}
			set
			{
				removeElementName = value;
			}
		}

		protected ConfigurationElementCollection()
		{
		}

		protected ConfigurationElementCollection(IComparer comparer)
		{
			this.comparer = comparer;
		}

		internal override void InitFromProperty(PropertyInformation propertyInfo)
		{
			ConfigurationCollectionAttribute configurationCollectionAttribute = propertyInfo.Property.CollectionAttribute;
			if (configurationCollectionAttribute == null)
			{
				configurationCollectionAttribute = Attribute.GetCustomAttribute(propertyInfo.Type, typeof(ConfigurationCollectionAttribute)) as ConfigurationCollectionAttribute;
			}
			if (configurationCollectionAttribute != null)
			{
				addElementName = configurationCollectionAttribute.AddItemName;
				clearElementName = configurationCollectionAttribute.ClearItemsName;
				removeElementName = configurationCollectionAttribute.RemoveItemName;
			}
			base.InitFromProperty(propertyInfo);
		}

		protected virtual void BaseAdd(ConfigurationElement element)
		{
			BaseAdd(element, ThrowOnDuplicate);
		}

		protected void BaseAdd(ConfigurationElement element, bool throwIfExists)
		{
			if (IsReadOnly())
			{
				throw new ConfigurationErrorsException("Collection is read only.");
			}
			if (IsAlternate)
			{
				list.Insert(inheritedLimitIndex, element);
				inheritedLimitIndex++;
			}
			else
			{
				int num = IndexOfKey(GetElementKey(element));
				if (num >= 0)
				{
					if (element.Equals(list[num]))
					{
						return;
					}
					if (throwIfExists)
					{
						throw new ConfigurationErrorsException("Duplicate element in collection");
					}
					list.RemoveAt(num);
				}
				list.Add(element);
			}
			modified = true;
		}

		protected virtual void BaseAdd(int index, ConfigurationElement element)
		{
			if (ThrowOnDuplicate && BaseIndexOf(element) != -1)
			{
				throw new ConfigurationErrorsException("Duplicate element in collection");
			}
			if (IsReadOnly())
			{
				throw new ConfigurationErrorsException("Collection is read only.");
			}
			if (IsAlternate && index > inheritedLimitIndex)
			{
				throw new ConfigurationErrorsException("Can't insert new elements below the inherited elements.");
			}
			if (!IsAlternate && index <= inheritedLimitIndex)
			{
				throw new ConfigurationErrorsException("Can't insert new elements above the inherited elements.");
			}
			list.Insert(index, element);
			modified = true;
		}

		protected internal void BaseClear()
		{
			if (IsReadOnly())
			{
				throw new ConfigurationErrorsException("Collection is read only.");
			}
			list.Clear();
			modified = true;
		}

		protected internal ConfigurationElement BaseGet(int index)
		{
			return (ConfigurationElement)list[index];
		}

		protected internal ConfigurationElement BaseGet(object key)
		{
			int num = IndexOfKey(key);
			if (num != -1)
			{
				return (ConfigurationElement)list[num];
			}
			return null;
		}

		protected internal object[] BaseGetAllKeys()
		{
			object[] array = new object[list.Count];
			for (int i = 0; i < list.Count; i++)
			{
				array[i] = BaseGetKey(i);
			}
			return array;
		}

		protected internal object BaseGetKey(int index)
		{
			if (index < 0 || index >= list.Count)
			{
				throw new ConfigurationErrorsException($"Index {index} is out of range");
			}
			return GetElementKey((ConfigurationElement)list[index]).ToString();
		}

		protected int BaseIndexOf(ConfigurationElement element)
		{
			return list.IndexOf(element);
		}

		private int IndexOfKey(object key)
		{
			for (int i = 0; i < list.Count; i++)
			{
				if (CompareKeys(GetElementKey((ConfigurationElement)list[i]), key))
				{
					return i;
				}
			}
			return -1;
		}

		protected internal bool BaseIsRemoved(object key)
		{
			if (removed == null)
			{
				return false;
			}
			foreach (ConfigurationElement item in removed)
			{
				if (CompareKeys(GetElementKey(item), key))
				{
					return true;
				}
			}
			return false;
		}

		protected internal void BaseRemove(object key)
		{
			if (IsReadOnly())
			{
				throw new ConfigurationErrorsException("Collection is read only.");
			}
			int num = IndexOfKey(key);
			if (num != -1)
			{
				BaseRemoveAt(num);
				modified = true;
			}
		}

		protected internal void BaseRemoveAt(int index)
		{
			if (IsReadOnly())
			{
				throw new ConfigurationErrorsException("Collection is read only.");
			}
			ConfigurationElement configurationElement = (ConfigurationElement)list[index];
			if (!IsElementRemovable(configurationElement))
			{
				throw new ConfigurationErrorsException("Element can't be removed from element collection.");
			}
			if (inherited != null && inherited.Contains(configurationElement))
			{
				throw new ConfigurationErrorsException("Inherited items can't be removed.");
			}
			list.RemoveAt(index);
			if (IsAlternate && inheritedLimitIndex > 0)
			{
				inheritedLimitIndex--;
			}
			modified = true;
		}

		private bool CompareKeys(object key1, object key2)
		{
			if (comparer != null)
			{
				return comparer.Compare(key1, key2) == 0;
			}
			return object.Equals(key1, key2);
		}

		public void CopyTo(ConfigurationElement[] array, int index)
		{
			list.CopyTo(array, index);
		}

		protected abstract ConfigurationElement CreateNewElement();

		protected virtual ConfigurationElement CreateNewElement(string elementName)
		{
			return CreateNewElement();
		}

		private ConfigurationElement CreateNewElementInternal(string elementName)
		{
			ConfigurationElement configurationElement = ((elementName != null) ? CreateNewElement(elementName) : CreateNewElement());
			configurationElement.Init();
			return configurationElement;
		}

		public override bool Equals(object compareTo)
		{
			if (!(compareTo is ConfigurationElementCollection configurationElementCollection))
			{
				return false;
			}
			if (GetType() != configurationElementCollection.GetType())
			{
				return false;
			}
			if (Count != configurationElementCollection.Count)
			{
				return false;
			}
			for (int i = 0; i < Count; i++)
			{
				if (!BaseGet(i).Equals(configurationElementCollection.BaseGet(i)))
				{
					return false;
				}
			}
			return true;
		}

		protected abstract object GetElementKey(ConfigurationElement element);

		public override int GetHashCode()
		{
			int num = 0;
			for (int i = 0; i < Count; i++)
			{
				num += BaseGet(i).GetHashCode();
			}
			return num;
		}

		void ICollection.CopyTo(Array arr, int index)
		{
			list.CopyTo(arr, index);
		}

		public IEnumerator GetEnumerator()
		{
			return list.GetEnumerator();
		}

		protected virtual bool IsElementName(string elementName)
		{
			return false;
		}

		protected virtual bool IsElementRemovable(ConfigurationElement element)
		{
			return !IsReadOnly();
		}

		protected internal override bool IsModified()
		{
			if (modified)
			{
				return true;
			}
			for (int i = 0; i < list.Count; i++)
			{
				if (((ConfigurationElement)list[i]).IsModified())
				{
					modified = true;
					break;
				}
			}
			return modified;
		}

		[MonoTODO]
		public override bool IsReadOnly()
		{
			return base.IsReadOnly();
		}

		internal override void PrepareSave(ConfigurationElement parentElement, ConfigurationSaveMode mode)
		{
			ConfigurationElementCollection configurationElementCollection = (ConfigurationElementCollection)parentElement;
			base.PrepareSave(parentElement, mode);
			for (int i = 0; i < list.Count; i++)
			{
				ConfigurationElement configurationElement = (ConfigurationElement)list[i];
				object elementKey = GetElementKey(configurationElement);
				ConfigurationElement parent = configurationElementCollection?.BaseGet(elementKey);
				configurationElement.PrepareSave(parent, mode);
			}
		}

		internal override bool HasValues(ConfigurationElement parentElement, ConfigurationSaveMode mode)
		{
			ConfigurationElementCollection configurationElementCollection = (ConfigurationElementCollection)parentElement;
			if (mode == ConfigurationSaveMode.Full)
			{
				return list.Count > 0;
			}
			for (int i = 0; i < list.Count; i++)
			{
				ConfigurationElement configurationElement = (ConfigurationElement)list[i];
				object elementKey = GetElementKey(configurationElement);
				ConfigurationElement parent = configurationElementCollection?.BaseGet(elementKey);
				if (configurationElement.HasValues(parent, mode))
				{
					return true;
				}
			}
			return false;
		}

		protected internal override void Reset(ConfigurationElement parentElement)
		{
			bool isBasic = IsBasic;
			ConfigurationElementCollection configurationElementCollection = (ConfigurationElementCollection)parentElement;
			for (int i = 0; i < configurationElementCollection.Count; i++)
			{
				ConfigurationElement parentElement2 = configurationElementCollection.BaseGet(i);
				ConfigurationElement configurationElement = CreateNewElementInternal(null);
				configurationElement.Reset(parentElement2);
				BaseAdd(configurationElement);
				if (isBasic)
				{
					if (inherited == null)
					{
						inherited = new ArrayList();
					}
					inherited.Add(configurationElement);
				}
			}
			if (IsAlternate)
			{
				inheritedLimitIndex = 0;
			}
			else
			{
				inheritedLimitIndex = Count - 1;
			}
			modified = false;
		}

		protected internal override void ResetModified()
		{
			modified = false;
			for (int i = 0; i < list.Count; i++)
			{
				((ConfigurationElement)list[i]).ResetModified();
			}
		}

		[MonoTODO]
		protected internal override void SetReadOnly()
		{
			base.SetReadOnly();
		}

		protected internal override bool SerializeElement(XmlWriter writer, bool serializeCollectionKey)
		{
			if (serializeCollectionKey)
			{
				return base.SerializeElement(writer, serializeCollectionKey);
			}
			bool flag = false;
			if (IsBasic)
			{
				for (int i = 0; i < list.Count; i++)
				{
					ConfigurationElement configurationElement = (ConfigurationElement)list[i];
					flag = ((!(ElementName != string.Empty)) ? (configurationElement.SerializeElement(writer, serializeCollectionKey: false) || flag) : (configurationElement.SerializeToXmlElement(writer, ElementName) || flag));
				}
			}
			else
			{
				if (emitClear)
				{
					writer.WriteElementString(clearElementName, "");
					flag = true;
				}
				if (removed != null)
				{
					for (int j = 0; j < removed.Count; j++)
					{
						writer.WriteStartElement(removeElementName);
						((ConfigurationElement)removed[j]).SerializeElement(writer, serializeCollectionKey: true);
						writer.WriteEndElement();
					}
					flag = flag || removed.Count > 0;
				}
				for (int k = 0; k < list.Count; k++)
				{
					((ConfigurationElement)list[k]).SerializeToXmlElement(writer, addElementName);
				}
				flag = flag || list.Count > 0;
			}
			return flag;
		}

		protected override bool OnDeserializeUnrecognizedElement(string elementName, XmlReader reader)
		{
			if (IsBasic)
			{
				ConfigurationElement configurationElement = null;
				if (elementName == ElementName)
				{
					configurationElement = CreateNewElementInternal(null);
				}
				if (IsElementName(elementName))
				{
					configurationElement = CreateNewElementInternal(elementName);
				}
				if (configurationElement != null)
				{
					configurationElement.DeserializeElement(reader, serializeCollectionKey: false);
					BaseAdd(configurationElement);
					modified = false;
					return true;
				}
			}
			else
			{
				if (elementName == clearElementName)
				{
					reader.MoveToContent();
					if (reader.MoveToNextAttribute())
					{
						throw new ConfigurationErrorsException("Unrecognized attribute '" + reader.LocalName + "'.");
					}
					reader.MoveToElement();
					reader.Skip();
					BaseClear();
					emitClear = true;
					modified = false;
					return true;
				}
				if (elementName == removeElementName)
				{
					ConfigurationRemoveElement configurationRemoveElement = new ConfigurationRemoveElement(CreateNewElementInternal(null), this);
					configurationRemoveElement.DeserializeElement(reader, serializeCollectionKey: true);
					BaseRemove(configurationRemoveElement.KeyValue);
					modified = false;
					return true;
				}
				if (elementName == addElementName)
				{
					ConfigurationElement configurationElement2 = CreateNewElementInternal(null);
					configurationElement2.DeserializeElement(reader, serializeCollectionKey: false);
					BaseAdd(configurationElement2);
					modified = false;
					return true;
				}
			}
			return false;
		}

		protected internal override void Unmerge(ConfigurationElement sourceElement, ConfigurationElement parentElement, ConfigurationSaveMode saveMode)
		{
			ConfigurationElementCollection configurationElementCollection = (ConfigurationElementCollection)sourceElement;
			ConfigurationElementCollection configurationElementCollection2 = (ConfigurationElementCollection)parentElement;
			for (int i = 0; i < configurationElementCollection.Count; i++)
			{
				ConfigurationElement configurationElement = configurationElementCollection.BaseGet(i);
				object elementKey = configurationElementCollection.GetElementKey(configurationElement);
				ConfigurationElement configurationElement2 = configurationElementCollection2?.BaseGet(elementKey);
				ConfigurationElement configurationElement3 = CreateNewElementInternal(null);
				if (configurationElement2 != null && saveMode != ConfigurationSaveMode.Full)
				{
					configurationElement3.Unmerge(configurationElement, configurationElement2, saveMode);
					if (configurationElement3.HasValues(configurationElement2, saveMode))
					{
						BaseAdd(configurationElement3);
					}
				}
				else
				{
					configurationElement3.Unmerge(configurationElement, null, ConfigurationSaveMode.Full);
					BaseAdd(configurationElement3);
				}
			}
			if (saveMode == ConfigurationSaveMode.Full)
			{
				EmitClear = true;
			}
			else
			{
				if (configurationElementCollection2 == null)
				{
					return;
				}
				for (int j = 0; j < configurationElementCollection2.Count; j++)
				{
					ConfigurationElement configurationElement4 = configurationElementCollection2.BaseGet(j);
					object elementKey2 = configurationElementCollection2.GetElementKey(configurationElement4);
					if (configurationElementCollection.IndexOfKey(elementKey2) == -1)
					{
						if (removed == null)
						{
							removed = new ArrayList();
						}
						removed.Add(configurationElement4);
					}
				}
			}
		}
	}
	public enum ConfigurationElementCollectionType
	{
		BasicMap,
		AddRemoveClearMap,
		BasicMapAlternate,
		AddRemoveClearMapAlternate
	}
	public sealed class ConfigurationElementProperty
	{
		private ConfigurationValidatorBase validator;

		public ConfigurationValidatorBase Validator => validator;

		public ConfigurationElementProperty(ConfigurationValidatorBase validator)
		{
			this.validator = validator;
		}
	}
	[Serializable]
	public class ConfigurationErrorsException : ConfigurationException
	{
		private readonly string filename;

		private readonly int line;

		public override string BareMessage => ((ConfigurationException)this).BareMessage;

		public ICollection Errors
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		public override string Filename => filename;

		public override int Line => line;

		public override string Message
		{
			get
			{
				if (!string.IsNullOrEmpty(filename))
				{
					if (line != 0)
					{
						return ((ConfigurationException)this).BareMessage + " (" + filename + " line " + line + ")";
					}
					return ((ConfigurationException)this).BareMessage + " (" + filename + ")";
				}
				if (line != 0)
				{
					return ((ConfigurationException)this).BareMessage + " (line " + line + ")";
				}
				return ((ConfigurationException)this).BareMessage;
			}
		}

		public ConfigurationErrorsException()
		{
		}

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

		protected ConfigurationErrorsException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
			filename = info.GetString("ConfigurationErrors_Filename");
			line = info.GetInt32("ConfigurationErrors_Line");
		}

		public ConfigurationErrorsException(string message, Exception inner)
			: base(message, inner)
		{
		}

		public ConfigurationErrorsException(string message, XmlNode node)
			: this(message, null, GetFilename(node), GetLineNumber(node))
		{
		}

		public ConfigurationErrorsException(string message, Exception inner, XmlNode node)
			: this(message, inner, GetFilename(node), GetLineNumber(node))
		{
		}

		public ConfigurationErrorsException(string message, XmlReader reader)
			: this(message, null, GetFilename(reader), GetLineNumber(reader))
		{
		}

		public ConfigurationErrorsException(string message, Exception inner, XmlReader reader)
			: this(message, inner, GetFilename(reader), GetLineNumber(reader))
		{
		}

		public ConfigurationErrorsException(string message, string filename, int line)
			: this(message, null, filename, line)
		{
		}

		public ConfigurationErrorsException(string message, Exception inner, string filename, int line)
			: base(message, inner)
		{
			this.filename = filename;
			this.line = line;
		}

		public static string GetFilename(XmlReader reader)
		{
			if (reader is IConfigErrorInfo)
			{
				return ((IConfigErrorInfo)reader).Filename;
			}
			return reader?.BaseURI;
		}

		public static int GetLineNumber(XmlReader reader)
		{
			if (reader is IConfigErrorInfo)
			{
				return ((IConfigErrorInfo)reader).LineNumber;
			}
			if (!(reader is IXmlLineInfo xmlLineInfo))
			{
				return 0;
			}
			return xmlLineInfo.LineNumber;
		}

		public static string GetFilename(XmlNode node)
		{
			if (!(node is IConfigErrorInfo))
			{
				return null;
			}
			return ((IConfigErrorInfo)node).Filename;
		}

		public static int GetLineNumber(XmlNode node)
		{
			if (!(node is IConfigErrorInfo))
			{
				return 0;
			}
			return ((IConfigErrorInfo)node).LineNumber;
		}

		[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			((ConfigurationException)this).GetObjectData(info, context);
			info.AddValue("ConfigurationErrors_Filename", filename);
			info.AddValue("ConfigurationErrors_Line", line);
		}
	}
	public class ConfigurationFileMap : ICloneable
	{
		private string machineConfigFilename;

		public string MachineConfigFilename
		{
			get
			{
				return machineConfigFilename;
			}
			set
			{
				machineConfigFilename = value;
			}
		}

		public ConfigurationFileMap()
		{
			machineConfigFilename = RuntimeEnvironment.SystemConfigurationFile;
		}

		public ConfigurationFileMap(string machineConfigFilename)
		{
			this.machineConfigFilename = machineConfigFilename;
		}

		public virtual object Clone()
		{
			return new ConfigurationFileMap(machineConfigFilename);
		}
	}
	public class ConfigurationLocation
	{
		private static readonly char[] pathTrimChars = new char[1] { '/' };

		private string path;

		private Configuration configuration;

		private Configuration parent;

		private string xmlContent;

		private bool parentResolved;

		private bool allowOverride;

		public string Path => path;

		internal bool AllowOverride => allowOverride;

		internal string XmlContent => xmlContent;

		internal Configuration OpenedConfiguration => configuration;

		internal ConfigurationLocation()
		{
		}

		internal ConfigurationLocation(string path, string xmlContent, Configuration parent, bool allowOverride)
		{
			if (!string.IsNullOrEmpty(path))
			{
				switch (path[0])
				{
				case ' ':
				case '.':
				case '/':
				case '\\':
					throw new ConfigurationErrorsException("<location> path attribute must be a relative virtual path.  It cannot start with any of ' ' '.' '/' or '\\'.");
				}
				path = path.TrimEnd(pathTrimChars);
			}
			this.path = path;
			this.xmlContent = xmlContent;
			this.parent = parent;
			this.allowOverride = allowOverride;
		}

		public Configuration OpenConfiguration()
		{
			if (configuration == null)
			{
				if (!parentResolved)
				{
					Configuration parentWithFile = parent.GetParentWithFile();
					if (parentWithFile != null)
					{
						string configPathFromLocationSubPath = parent.ConfigHost.GetConfigPathFromLocationSubPath(parent.LocationConfigPath, path);
						parent = parentWithFile.FindLocationConfiguration(configPathFromLocationSubPath, parent);
					}
				}
				configuration = new Configuration(parent, path);
				using (XmlTextReader reader = new ConfigXmlTextReader(new StringReader(xmlContent), path))
				{
					configuration.ReadData(reader, allowOverride);
				}
				xmlContent = null;
			}
			return configuration;
		}

		internal void SetParentConfiguration(Configuration parent)
		{
			if (!parentResolved)
			{
				parentResolved = true;
				this.parent = parent;
				if (configuration != null)
				{
					configuration.Parent = parent;
				}
			}
		}
	}
	public class ConfigurationLocationCollection : ReadOnlyCollectionBase
	{
		public ConfigurationLocation this[int index] => base.InnerList[index] as ConfigurationLocation;

		internal ConfigurationLocationCollection()
		{
		}

		internal void Add(ConfigurationLocation loc)
		{
			base.InnerList.Add(loc);
		}

		internal ConfigurationLocation Find(string location)
		{
			foreach (ConfigurationLocation inner in base.InnerList)
			{
				if (string.Compare(inner.Path, location, StringComparison.OrdinalIgnoreCase) == 0)
				{
					return inner;
				}
			}
			return null;
		}

		internal ConfigurationLocation FindBest(string location)
		{
			if (string.IsNullOrEmpty(location))
			{
				return null;
			}
			ConfigurationLocation configurationLocation = null;
			int length = location.Length;
			int num = 0;
			foreach (ConfigurationLocation inner in base.InnerList)
			{
				string path = inner.Path;
				if (string.IsNullOrEmpty(path))
				{
					continue;
				}
				int length2 = path.Length;
				if (!location.StartsWith(path, StringComparison.OrdinalIgnoreCase))
				{
					continue;
				}
				if (length == length2)
				{
					return inner;
				}
				if (length <= length2 || location[length2] == '/')
				{
					if (configurationLocation == null)
					{
						configurationLocation = inner;
					}
					else if (num < length2)
					{
						configurationLocation = inner;
						num = length2;
					}
				}
			}
			return configurationLocation;
		}
	}
	[Flags]
	internal enum ConfigurationLockType
	{
		Attribute = 1,
		Element = 2,
		Exclude = 0x10
	}
	public sealed class ConfigurationLockCollection : ICollection, IEnumerable
	{
		private ArrayList names;

		private ConfigurationElement element;

		private ConfigurationLockType lockType;

		private bool is_modified;

		private Hashtable valid_name_hash;

		private string valid_names;

		public string AttributeList
		{
			get
			{
				string[] array = new string[names.Count];
				names.CopyTo(array, 0);
				return string.Join(",", array);
			}
		}

		public int Count => names.Count;

		[MonoTODO]
		public bool HasParentElements => false;

		[MonoTODO]
		public bool IsModified
		{
			get
			{
				return is_modified;
			}
			internal set
			{
				is_modified = value;
			}
		}

		[MonoTODO]
		public bool IsSynchronized => false;

		[MonoTODO]
		public object SyncRoot => this;

		internal ConfigurationLockCollection(ConfigurationElement element, ConfigurationLockType lockType)
		{
			names = new ArrayList();
			this.element = element;
			this.lockType = lockType;
		}

		private void CheckName(string name)
		{
			bool flag = (lockType & ConfigurationLockType.Attribute) == ConfigurationLockType.Attribute;
			if (valid_name_hash == null)
			{
				valid_name_hash = new Hashtable();
				foreach (ConfigurationProperty property in element.Properties)
				{
					if (flag != property.IsElement)
					{
						valid_name_hash.Add(property.Name, true);
					}
				}
				if (!flag)
				{
					ConfigurationElementCollection defaultCollection = element.GetDefaultCollection();
					valid_name_hash.Add(defaultCollection.AddElementName, true);
					valid_name_hash.Add(defaultCollection.ClearElementName, true);
					valid_name_hash.Add(defaultCollection.RemoveElementName, true);
				}
				string[] array = new string[valid_name_hash.Keys.Count];
				valid_name_hash.Keys.CopyTo(array, 0);
				valid_names = string.Join(",", array);
			}
			if (valid_name_hash[name] == null)
			{
				throw new ConfigurationErrorsException(string.Format("The {2} '{0}' is not valid in the locked list for this section.  The following {3} can be locked: '{1}'", name, valid_names, flag ? "attribute" : "element", flag ? "attributes" : "elements"));
			}
		}

		public void Add(string name)
		{
			CheckName(name);
			if (!names.Contains(name))
			{
				names.Add(name);
				is_modified = true;
			}
		}

		public void Clear()
		{
			names.Clear();
			is_modified = true;
		}

		public bool Contains(string name)
		{
			return names.Contains(name);
		}

		public void CopyTo(string[] array, int index)
		{
			names.CopyTo(array, index);
		}

		public IEnumerator GetEnumerator()
		{
			return names.GetEnumerator();
		}

		[MonoInternalNote("we can't possibly *always* return false here...")]
		public bool IsReadOnly(string name)
		{
			for (int i = 0; i < names.Count; i++)
			{
				if ((string)names[i] == name)
				{
					return false;
				}
			}
			throw new ConfigurationErrorsException($"The entry '{name}' is not in the collection.");
		}

		public void Remove(string name)
		{
			names.Remove(name);
			is_modified = true;
		}

		public void SetFromList(string attributeList)
		{
			Clear();
			char[] separator = new char[1] { ',' };
			string[] array = attributeList.Split(separator);
			foreach (string text in array)
			{
				Add(text.Trim());
			}
		}

		void ICollection.CopyTo(Array array, int index)
		{
			names.CopyTo(array, index);
		}

		internal ConfigurationLockCollection()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	public static class ConfigurationManager
	{
		private static InternalConfigurationFactory configFactory = new InternalConfigurationFactory();

		private static IInternalConfigSystem configSystem = new ClientConfigurationSystem();

		private static object lockobj = new object();

		internal static IInternalConfigConfigurationFactory ConfigurationFactory => configFactory;

		internal static IInternalConfigSystem ConfigurationSystem => configSystem;

		public static NameValueCollection AppSettings => (NameValueCollection)GetSection("appSettings");

		public static ConnectionStringSettingsCollection ConnectionStrings => ((ConnectionStringsSection)GetSection("connectionStrings")).ConnectionStrings;

		[MonoTODO("Evidence and version still needs work")]
		private static string GetAssemblyInfo(Assembly a)
		{
			object[] customAttributes = a.GetCustomAttributes(typeof(AssemblyProductAttribute), inherit: false);
			string arg = ((customAttributes == null || customAttributes.Length == 0) ? AppDomain.CurrentDomain.FriendlyName : ((AssemblyProductAttribute)customAttributes[0]).Product);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("evidencehere");
			string arg2 = stringBuilder.ToString();
			customAttributes = a.GetCustomAttributes(typeof(AssemblyVersionAttribute), inherit: false);
			return Path.Combine(path2: (customAttributes == null || customAttributes.Length == 0) ? "1.0.0.0" : ((AssemblyVersionAttribute)customAttributes[0]).Version, path1: $"{arg}_{arg2}");
		}

		internal static Configuration OpenExeConfigurationInternal(ConfigurationUserLevel userLevel, Assembly calling_assembly, string exePath)
		{
			ExeConfigurationFileMap exeConfigurationFileMap = new ExeConfigurationFileMap();
			if (userLevel != 0)
			{
				if (userLevel != ConfigurationUserLevel.PerUserRoaming)
				{
					if (userLevel != ConfigurationUserLevel.PerUserRoamingAndLocal)
					{
						goto IL_00ea;
					}
					exeConfigurationFileMap.LocalUserConfigFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), GetAssemblyInfo(calling_assembly));
					exeConfigurationFileMap.LocalUserConfigFilename = Path.Combine(exeConfigurationFileMap.LocalUserConfigFilename, "user.config");
				}
				exeConfigurationFileMap.RoamingUserConfigFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), GetAssemblyInfo(calling_assembly));
				exeConfigurationFileMap.RoamingUserConfigFilename = Path.Combine(exeConfigurationFileMap.RoamingUserConfigFilename, "user.config");
			}
			if (exePath == null || exePath.Length == 0)
			{
				exeConfigurationFileMap.ExeConfigFilename = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
			}
			else
			{
				if (!Path.IsPathRooted(exePath))
				{
					exePath = Path.GetFullPath(exePath);
				}
				if (!File.Exists(exePath))
				{
					Exception inner = new ArgumentException("The specified path does not exist.", "exePath");
					throw new ConfigurationErrorsException("Error Initializing the configuration system:", inner);
				}
				exeConfigurationFileMap.ExeConfigFilename = exePath + ".config";
			}
			goto IL_00ea;
			IL_00ea:
			return ConfigurationFactory.Create(typeof(ExeConfigurationHost), exeConfigurationFileMap, userLevel);
		}

		public static Configuration OpenExeConfiguration(ConfigurationUserLevel userLevel)
		{
			return OpenExeConfigurationInternal(userLevel, Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly(), null);
		}

		public static Configuration OpenExeConfiguration(string exePath)
		{
			return OpenExeConfigurationInternal(ConfigurationUserLevel.None, Assembly.GetEntryAssembly() ?? Assembly.GetCallingAssembly(), exePath);
		}

		[MonoLimitation("ConfigurationUserLevel parameter is not supported.")]
		public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel)
		{
			return ConfigurationFactory.Create(typeof(ExeConfigurationHost), fileMap, userLevel);
		}

		public static Configuration OpenMachineConfiguration()
		{
			ConfigurationFileMap configurationFileMap = new ConfigurationFileMap();
			return ConfigurationFactory.Create(typeof(MachineConfigurationHost), configurationFileMap);
		}

		public static Configuration OpenMappedMachineConfiguration(ConfigurationFileMap fileMap)
		{
			return ConfigurationFactory.Create(typeof(MachineConfigurationHost), fileMap);
		}

		public static object GetSection(string sectionName)
		{
			object section = ConfigurationSystem.GetSection(sectionName);
			if (section is ConfigurationSection)
			{
				return ((ConfigurationSection)section).GetRuntimeObject();
			}
			return section;
		}

		public static void RefreshSection(string sectionName)
		{
			ConfigurationSystem.RefreshConfig(sectionName);
		}

		internal static IInternalConfigSystem ChangeConfigurationSystem(IInternalConfigSystem newSystem)
		{
			if (newSystem == null)
			{
				throw new ArgumentNullException("newSystem");
			}
			lock (lockobj)
			{
				IInternalConfigSystem result = configSystem;
				configSystem = newSystem;
				return result;
			}
		}

		public static Configuration OpenMappedExeConfiguration(ExeConfigurationFileMap fileMap, ConfigurationUserLevel userLevel, bool preLoad)
		{
			ThrowStub.ThrowNotSupportedException();
			return null;
		}
	}
	[Serializable]
	public sealed class ConfigurationPermission : CodeAccessPermission, IUnrestrictedPermission
	{
		private bool unrestricted;

		public ConfigurationPermission(PermissionState state)
		{
			unrestricted = state == PermissionState.Unrestricted;
		}

		public override IPermission Copy()
		{
			return (IPermission)(object)new ConfigurationPermission(unrestricted ? PermissionState.Unrestricted : PermissionState.None);
		}

		public override void FromXml(SecurityElement securityElement)
		{
			if (securityElement == null)
			{
				throw new ArgumentNullException("securityElement");
			}
			if (securityElement.Tag != "IPermission")
			{
				throw new ArgumentException("securityElement");
			}
			string text = securityElement.Attribute("Unrestricted");
			if (text != null)
			{
				unrestricted = string.Compare(text, "true", StringComparison.InvariantCultureIgnoreCase) == 0;
			}
		}

		public override IPermission Intersect(IPermission target)
		{
			if (target == null)
			{
				return null;
			}
			if (!(target is ConfigurationPermission configurationPermission))
			{
				throw new ArgumentException("target");
			}
			return (IPermission)(object)new ConfigurationPermission((unrestricted && configurationPermission.IsUnrestricted()) ? PermissionState.Unrestricted : PermissionState.None);
		}

		public override IPermission Union(IPermission target)
		{
			if (target == null)
			{
				return ((CodeAccessPermission)this).Copy();
			}
			if (!(target is ConfigurationPermission configurationPermission))
			{
				throw new ArgumentException("target");
			}
			return (IPermission)(object)new ConfigurationPermission((unrestricted || configurationPermission.IsUnrestricted()) ? PermissionState.Unrestricted : PermissionState.None);
		}

		public override bool IsSubsetOf(IPermission target)
		{
			if (target == null)
			{
				return !unrestricted;
			}
			if (!(target is ConfigurationPermission configurationPermission))
			{
				throw new ArgumentException("target");
			}
			if (unrestricted)
			{
				return configurationPermission.IsUnrestricted();
			}
			return true;
		}

		public bool IsUnrestricted()
		{
			return unrestricted;
		}

		public override SecurityElement ToXml()
		{
			SecurityElement securityElement = new SecurityElement("IPermission");
			securityElement.AddAttribute("class", ((object)this).GetType().AssemblyQualifiedName);
			securityElement.AddAttribute("version", "1");
			if (unrestricted)
			{
				securityElement.AddAttribute("Unrestricted", "true");
			}
			return securityElement;
		}
	}
	[Serializable]
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
	public sealed class ConfigurationPermissionAttribute : CodeAccessSecurityAttribute
	{
		public ConfigurationPermissionAttribute(SecurityAction action)
			: base(action)
		{
		}

		public override IPermission CreatePermission()
		{
			return (IPermission)(object)new ConfigurationPermission(base.Unrestricted ? PermissionState.Unrestricted : PermissionState.None);
		}
	}
	public sealed class ConfigurationProperty
	{
		internal static readonly object NoDefaultValue = new object();

		private string name;

		private Type type;

		private object default_value;

		private TypeConverter converter;

		private ConfigurationValidatorBase validation;

		private ConfigurationPropertyOptions flags;

		private string description;

		private ConfigurationCollectionAttribute collectionAttribute;

		public TypeConverter Converter => converter;

		public object DefaultValue => default_value;

		public bool IsKey => (flags & ConfigurationPropertyOptions.IsKey) != 0;

		public bool IsRequired => (flags & ConfigurationPropertyOptions.IsRequired) != 0;

		public bool IsDefaultCollection => (flags & ConfigurationPropertyOptions.IsDefaultCollection) != 0;

		public string Name => name;

		public string Description => description;

		public Type Type => type;

		public ConfigurationValidatorBase Validator => validation;

		internal bool IsElement => typeof(ConfigurationElement).IsAssignableFrom(type);

		internal ConfigurationCollectionAttribute CollectionAttribute
		{
			get
			{
				return collectionAttribute;
			}
			set
			{
				collectionAttribute = value;
			}
		}

		public bool IsAssemblyStringTransformationRequired
		{
			get
			{
				ThrowStub.ThrowNotSupportedException();
				return default(bool);
			}
		}

		public bool IsTypeStringTransformationRequired
		{
			get
			{
				ThrowStub.ThrowNotSupportedException();
				return default(bool);
			}
		}

		public bool IsVersionCheckRequired
		{
			get
			{
				ThrowStub.ThrowNotSupportedException();
				return default(bool);
			}
		}

		public ConfigurationProperty(string name, Type type)
			: this(name, type, NoDefaultValue, TypeDescriptor.GetConverter(type), new DefaultValidator(), ConfigurationPropertyOptions.None, null)
		{
		}

		public ConfigurationProperty(string name, Type type, object defaultValue)
			: this(name, type, defaultValue, TypeDescriptor.GetConverter(type), new DefaultValidator(), ConfigurationPropertyOptions.None, null)
		{
		}

		public ConfigurationProperty(string name, Type type, object defaultValue, ConfigurationPropertyOptions options)
			: this(name, type, defaultValue, TypeDescriptor.GetConverter(type), new DefaultValidator(), options, null)
		{
		}

		public ConfigurationProperty(string name, Type type, object defaultValue, TypeConverter typeConverter, ConfigurationValidatorBase validator, ConfigurationPropertyOptions options)
			: this(name, type, defaultValue, typeConverter, validator, options, null)
		{
		}

		public ConfigurationProperty(string name, Type type, object defaultValue, TypeConverter typeConverter, ConfigurationValidatorBase validator, ConfigurationPropertyOptions options, string description)
		{
			this.name = name;
			converter = ((typeConverter != null) ? typeConverter : TypeDescriptor.GetConverter(type));
			if (defaultValue != null)
			{
				if (defaultValue == NoDefaultValue)
				{
					defaultValue = Type.GetTypeCo

BepInEx/core/System.Core.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Dynamic;
using System.Dynamic.Utils;
using System.Globalization;
using System.IO;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Linq.Expressions;
using System.Linq.Expressions.Compiler;
using System.Linq.Parallel;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.AccessControl;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using Mono.Security.Cryptography;
using Unity;

[assembly: DefaultDependency(LoadHint.Always)]
[assembly: AssemblyKeyFile("../ecma.pub")]
[assembly: AssemblyDelaySign(true)]
[assembly: CLSCompliant(true)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyDefaultAlias("System.Core.dll")]
[assembly: AssemblyDescription("System.Core.dll")]
[assembly: AssemblyTitle("System.Core.dll")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: CompilationRelaxations(8)]
[assembly: StringFreezing]
[assembly: ComVisible(false)]
[assembly: SecurityCritical]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: TypeForwardedTo(typeof(Action))]
[assembly: TypeForwardedTo(typeof(Action<, >))]
[assembly: TypeForwardedTo(typeof(Action<, , >))]
[assembly: TypeForwardedTo(typeof(Action<, , , >))]
[assembly: TypeForwardedTo(typeof(Func<>))]
[assembly: TypeForwardedTo(typeof(Func<, >))]
[assembly: TypeForwardedTo(typeof(Func<, , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , >))]
[assembly: TypeForwardedTo(typeof(Func<, , , , >))]
[assembly: TypeForwardedTo(typeof(InvalidTimeZoneException))]
[assembly: TypeForwardedTo(typeof(Lazy<>))]
[assembly: TypeForwardedTo(typeof(ExtensionAttribute))]
[assembly: TypeForwardedTo(typeof(Aes))]
[assembly: TypeForwardedTo(typeof(LazyThreadSafetyMode))]
[assembly: TypeForwardedTo(typeof(LockRecursionException))]
[assembly: TypeForwardedTo(typeof(TimeZoneInfo))]
[assembly: TypeForwardedTo(typeof(TimeZoneNotFoundException))]
[module: UnverifiableCode]
internal static class Interop
{
	internal enum BOOL
	{
		FALSE,
		TRUE
	}

	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_BAD_NETPATH = 53;

		internal const int ERROR_BAD_NET_NAME = 67;

		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_DIRECTORY = 267;

		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_NETWORK_UNREACHABLE = 1231;

		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 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 static class Advapi32
	{
		[DllImport("advapi32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool ImpersonateNamedPipeClient(SafePipeHandle hNamedPipe);

		[DllImport("advapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern bool RevertToSelf();
	}

	internal class Kernel32
	{
		internal class IOReparseOptions
		{
			internal const uint IO_REPARSE_TAG_FILE_PLACEHOLDER = 2147483669u;

			internal const uint IO_REPARSE_TAG_MOUNT_POINT = 2684354563u;
		}

		internal class FileOperations
		{
			internal const int OPEN_EXISTING = 3;

			internal const int COPY_FILE_FAIL_IF_EXISTS = 1;

			internal const int FILE_ACTION_ADDED = 1;

			internal const int FILE_ACTION_REMOVED = 2;

			internal const int FILE_ACTION_MODIFIED = 3;

			internal const int FILE_ACTION_RENAMED_OLD_NAME = 4;

			internal const int FILE_ACTION_RENAMED_NEW_NAME = 5;

			internal const int FILE_FLAG_BACKUP_SEMANTICS = 33554432;

			internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 524288;

			internal const int FILE_FLAG_OVERLAPPED = 1073741824;

			internal const int FILE_LIST_DIRECTORY = 1;
		}

		internal class FileTypes
		{
			internal const int FILE_TYPE_UNKNOWN = 0;

			internal const int FILE_TYPE_DISK = 1;

			internal const int FILE_TYPE_CHAR = 2;

			internal const int FILE_TYPE_PIPE = 3;
		}

		internal class GenericOperations
		{
			internal const int GENERIC_READ = int.MinValue;

			internal const int GENERIC_WRITE = 1073741824;
		}

		internal class HandleOptions
		{
			internal const int DUPLICATE_SAME_ACCESS = 2;

			internal const int STILL_ACTIVE = 259;

			internal const int TOKEN_ADJUST_PRIVILEGES = 32;
		}

		internal class PipeOptions
		{
			internal const int PIPE_ACCESS_INBOUND = 1;

			internal const int PIPE_ACCESS_OUTBOUND = 2;

			internal const int PIPE_ACCESS_DUPLEX = 3;

			internal const int PIPE_TYPE_BYTE = 0;

			internal const int PIPE_TYPE_MESSAGE = 4;

			internal const int PIPE_READMODE_BYTE = 0;

			internal const int PIPE_READMODE_MESSAGE = 2;

			internal const int PIPE_UNLIMITED_INSTANCES = 255;
		}

		internal struct SECURITY_ATTRIBUTES
		{
			internal uint nLength;

			internal IntPtr lpSecurityDescriptor;

			internal BOOL bInheritHandle;
		}

		internal class SecurityOptions
		{
			internal const int SECURITY_SQOS_PRESENT = 1048576;

			internal const int SECURITY_ANONYMOUS = 0;

			internal const int SECURITY_IDENTIFICATION = 65536;

			internal const int SECURITY_IMPERSONATION = 131072;

			internal const int SECURITY_DELEGATION = 196608;
		}

		internal const uint SEM_FAILCRITICALERRORS = 1u;

		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;

		internal const int MAX_PATH = 260;

		internal const int CREDUI_MAX_USERNAME_LENGTH = 513;

		[DllImport("kernel32.dll", SetLastError = true)]
		internal unsafe static extern bool CancelIoEx(SafeHandle handle, NativeOverlapped* lpOverlapped);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CloseHandle(IntPtr handle);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal unsafe static extern bool ConnectNamedPipe(SafePipeHandle handle, NativeOverlapped* overlapped);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool ConnectNamedPipe(SafePipeHandle handle, IntPtr overlapped);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateNamedPipeW", SetLastError = true)]
		internal static extern SafePipeHandle CreateNamedPipe(string pipeName, int openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, ref SECURITY_ATTRIBUTES securityAttributes);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", SetLastError = true)]
		internal static extern SafePipeHandle CreateNamedPipeClient(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, ref SECURITY_ATTRIBUTES secAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);

		[DllImport("kernel32.dll", SetLastError = true)]
		internal static extern bool CreatePipe(out SafePipeHandle hReadPipe, out SafePipeHandle hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, int nSize);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool DisconnectNamedPipe(SafePipeHandle hNamedPipe);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, SafePipeHandle hSourceHandle, IntPtr hTargetProcessHandle, out SafePipeHandle lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool FlushFileBuffers(SafeHandle hHandle);

		[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 unsafe static string GetMessage(IntPtr moduleHandle, int errorCode)
		{
			//IL_000d: 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_0015: 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_0034: Unknown result type (might be due to invalid IL or missing references)
			Span<char> buffer = new Span<char>((void*)stackalloc byte[512], 256);
			do
			{
				if (TryGetErrorMessage(moduleHandle, errorCode, buffer, out var errorMsg))
				{
					return errorMsg;
				}
				buffer = Span<char>.op_Implicit(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)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			int num = 12800;
			if (moduleHandle != IntPtr.Zero)
			{
				num |= 0x800;
			}
			int num2;
			fixed (char* lpBuffer = &MemoryMarshal.GetReference<char>(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 = ((object)buffer.Slice(0, num3)).ToString();
			}
			else
			{
				if (Marshal.GetLastWin32Error() == 122)
				{
					errorMsg = "";
					return false;
				}
				errorMsg = $"Unknown error (0x{errorCode:x})";
			}
			return true;
		}

		[DllImport("kernel32.dll", SetLastError = true)]
		internal static extern IntPtr GetCurrentProcess();

		[DllImport("kernel32.dll", SetLastError = true)]
		internal static extern int GetFileType(SafeHandle hFile);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetNamedPipeHandleStateW", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, out int lpState, IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "GetNamedPipeHandleStateW", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState, IntPtr lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, [Out] StringBuilder lpUserName, int nMaxUserNameSize);

		[DllImport("kernel32.dll", EntryPoint = "GetNamedPipeHandleStateW", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool GetNamedPipeHandleState(SafePipeHandle hNamedPipe, IntPtr lpState, out int lpCurInstances, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout, IntPtr lpUserName, int nMaxUserNameSize);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, out int lpFlags, IntPtr lpOutBufferSize, IntPtr lpInBufferSize, IntPtr lpMaxInstances);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, IntPtr lpFlags, out int lpOutBufferSize, IntPtr lpInBufferSize, IntPtr lpMaxInstances);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool GetNamedPipeInfo(SafePipeHandle hNamedPipe, IntPtr lpFlags, IntPtr lpOutBufferSize, out int lpInBufferSize, IntPtr lpMaxInstances);

		[DllImport("kernel32.dll", SetLastError = true)]
		internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);

		[DllImport("kernel32.dll", SetLastError = true)]
		internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, IntPtr numBytesRead_mustBeZero, NativeOverlapped* overlapped);

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal unsafe static extern bool SetNamedPipeHandleState(SafePipeHandle hNamedPipe, int* lpMode, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "WaitNamedPipeW", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool WaitNamedPipe(string name, int timeout);

		[DllImport("kernel32.dll", SetLastError = true)]
		internal unsafe static extern int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, out int numBytesWritten, IntPtr mustBeZero);

		[DllImport("kernel32.dll", SetLastError = true)]
		internal unsafe static extern int WriteFile(SafeHandle handle, byte* bytes, int numBytesToWrite, IntPtr numBytesWritten_mustBeZero, NativeOverlapped* lpOverlapped);
	}
}
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class SR
{
	public const string ReducibleMustOverrideReduce = "reducible nodes must override Expression.Reduce()";

	public const string MustReduceToDifferent = "node cannot reduce to itself or null";

	public const string ReducedNotCompatible = "cannot assign from the reduced node type to the original node type";

	public const string SetterHasNoParams = "Setter must have parameters.";

	public const string PropertyCannotHaveRefType = "Property cannot have a managed pointer type.";

	public const string IndexesOfSetGetMustMatch = "Indexing parameters of getter and setter must match.";

	public const string AccessorsCannotHaveVarArgs = "Accessor method should not have VarArgs.";

	public const string AccessorsCannotHaveByRefArgs = "Accessor indexes cannot be passed ByRef.";

	public const string BoundsCannotBeLessThanOne = "Bounds count cannot be less than 1";

	public const string TypeMustNotBeByRef = "Type must not be ByRef";

	public const string TypeMustNotBePointer = "Type must not be a pointer type";

	public const string SetterMustBeVoid = "Setter should have void type.";

	public const string PropertyTypeMustMatchGetter = "Property type must match the value type of getter";

	public const string PropertyTypeMustMatchSetter = "Property type must match the value type of setter";

	public const string BothAccessorsMustBeStatic = "Both accessors must be static.";

	public const string OnlyStaticFieldsHaveNullInstance = "Static field requires null instance, non-static field requires non-null instance.";

	public const string OnlyStaticPropertiesHaveNullInstance = "Static property requires null instance, non-static property requires non-null instance.";

	public const string OnlyStaticMethodsHaveNullInstance = "Static method requires null instance, non-static method requires non-null instance.";

	public const string PropertyTypeCannotBeVoid = "Property cannot have a void type.";

	public const string InvalidUnboxType = "Can only unbox from an object or interface type to a value type.";

	public const string ExpressionMustBeWriteable = "Expression must be writeable";

	public const string ArgumentMustNotHaveValueType = "Argument must not have a value type.";

	public const string MustBeReducible = "must be reducible node";

	public const string AllTestValuesMustHaveSameType = "All test values must have the same type.";

	public const string AllCaseBodiesMustHaveSameType = "All case bodies and the default body must have the same type.";

	public const string DefaultBodyMustBeSupplied = "Default body must be supplied if case bodies are not System.Void.";

	public const string LabelMustBeVoidOrHaveExpression = "Label type must be System.Void if an expression is not supplied";

	public const string LabelTypeMustBeVoid = "Type must be System.Void for this label argument";

	public const string QuotedExpressionMustBeLambda = "Quoted expression must be a lambda";

	public const string VariableMustNotBeByRef = "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables.";

	public const string DuplicateVariable = "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object.";

	public const string StartEndMustBeOrdered = "Start and End must be well ordered";

	public const string FaultCannotHaveCatchOrFinally = "fault cannot be used with catch or finally clauses";

	public const string TryMustHaveCatchFinallyOrFault = "try must have at least one catch, finally, or fault clause";

	public const string BodyOfCatchMustHaveSameTypeAsBodyOfTry = "Body of catch must have the same type as body of try.";

	public const string ExtensionNodeMustOverrideProperty = "Extension node must override the property {0}.";

	public const string UserDefinedOperatorMustBeStatic = "User-defined operator method '{0}' must be static.";

	public const string UserDefinedOperatorMustNotBeVoid = "User-defined operator method '{0}' must not be void.";

	public const string CoercionOperatorNotDefined = "No coercion operator is defined between types '{0}' and '{1}'.";

	public const string UnaryOperatorNotDefined = "The unary operator {0} is not defined for the type '{1}'.";

	public const string BinaryOperatorNotDefined = "The binary operator {0} is not defined for the types '{1}' and '{2}'.";

	public const string ReferenceEqualityNotDefined = "Reference equality is not defined for the types '{0}' and '{1}'.";

	public const string OperandTypesDoNotMatchParameters = "The operands for operator '{0}' do not match the parameters of method '{1}'.";

	public const string OverloadOperatorTypeDoesNotMatchConversionType = "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'.";

	public const string ConversionIsNotSupportedForArithmeticTypes = "Conversion is not supported for arithmetic types without operator overloading.";

	public const string ArgumentMustBeArray = "Argument must be array";

	public const string ArgumentMustBeBoolean = "Argument must be boolean";

	public const string EqualityMustReturnBoolean = "The user-defined equality method '{0}' must return a boolean value.";

	public const string ArgumentMustBeFieldInfoOrPropertyInfo = "Argument must be either a FieldInfo or PropertyInfo";

	public const string ArgumentMustBeFieldInfoOrPropertyInfoOrMethod = "Argument must be either a FieldInfo, PropertyInfo or MethodInfo";

	public const string ArgumentMustBeInstanceMember = "Argument must be an instance member";

	public const string ArgumentMustBeInteger = "Argument must be of an integer type";

	public const string ArgumentMustBeArrayIndexType = "Argument for array index must be of type Int32";

	public const string ArgumentMustBeSingleDimensionalArrayType = "Argument must be single-dimensional, zero-based array type";

	public const string ArgumentTypesMustMatch = "Argument types do not match";

	public const string CannotAutoInitializeValueTypeElementThroughProperty = "Cannot auto initialize elements of value type through property '{0}', use assignment instead";

	public const string CannotAutoInitializeValueTypeMemberThroughProperty = "Cannot auto initialize members of value type through property '{0}', use assignment instead";

	public const string IncorrectTypeForTypeAs = "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither";

	public const string CoalesceUsedOnNonNullType = "Coalesce used with type that cannot be null";

	public const string ExpressionTypeCannotInitializeArrayType = "An expression of type '{0}' cannot be used to initialize an array of type '{1}'";

	public const string ArgumentTypeDoesNotMatchMember = " Argument type '{0}' does not match the corresponding member type '{1}'";

	public const string ArgumentMemberNotDeclOnType = " The member '{0}' is not declared on type '{1}' being created";

	public const string ExpressionTypeDoesNotMatchReturn = "Expression of type '{0}' cannot be used for return type '{1}'";

	public const string ExpressionTypeDoesNotMatchAssignment = "Expression of type '{0}' cannot be used for assignment to type '{1}'";

	public const string ExpressionTypeDoesNotMatchLabel = "Expression of type '{0}' cannot be used for label of type '{1}'";

	public const string ExpressionTypeNotInvocable = "Expression of type '{0}' cannot be invoked";

	public const string FieldNotDefinedForType = "Field '{0}' is not defined for type '{1}'";

	public const string InstanceFieldNotDefinedForType = "Instance field '{0}' is not defined for type '{1}'";

	public const string FieldInfoNotDefinedForType = "Field '{0}.{1}' is not defined for type '{2}'";

	public const string IncorrectNumberOfIndexes = "Incorrect number of indexes";

	public const string IncorrectNumberOfLambdaDeclarationParameters = "Incorrect number of parameters supplied for lambda declaration";

	public const string IncorrectNumberOfMembersForGivenConstructor = " Incorrect number of members for constructor";

	public const string IncorrectNumberOfArgumentsForMembers = "Incorrect number of arguments for the given members ";

	public const string LambdaTypeMustBeDerivedFromSystemDelegate = "Lambda type parameter must be derived from System.MulticastDelegate";

	public const string MemberNotFieldOrProperty = "Member '{0}' not field or property";

	public const string MethodContainsGenericParameters = "Method {0} contains generic parameters";

	public const string MethodIsGeneric = "Method {0} is a generic method definition";

	public const string MethodNotPropertyAccessor = "The method '{0}.{1}' is not a property accessor";

	public const string PropertyDoesNotHaveGetter = "The property '{0}' has no 'get' accessor";

	public const string PropertyDoesNotHaveSetter = "The property '{0}' has no 'set' accessor";

	public const string PropertyDoesNotHaveAccessor = "The property '{0}' has no 'get' or 'set' accessors";

	public const string NotAMemberOfType = "'{0}' is not a member of type '{1}'";

	public const string NotAMemberOfAnyType = "'{0}' is not a member of any type";

	public const string UnsupportedExpressionType = "The expression type '{0}' is not supported";

	public const string ParameterExpressionNotValidAsDelegate = "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'";

	public const string PropertyNotDefinedForType = "Property '{0}' is not defined for type '{1}'";

	public const string InstancePropertyNotDefinedForType = "Instance property '{0}' is not defined for type '{1}'";

	public const string InstancePropertyWithoutParameterNotDefinedForType = "Instance property '{0}' that takes no argument is not defined for type '{1}'";

	public const string InstancePropertyWithSpecifiedParametersNotDefinedForType = "Instance property '{0}{1}' is not defined for type '{2}'";

	public const string InstanceAndMethodTypeMismatch = "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'";

	public const string TypeContainsGenericParameters = "Type {0} contains generic parameters";

	public const string TypeIsGeneric = "Type {0} is a generic type definition";

	public const string TypeMissingDefaultConstructor = "Type '{0}' does not have a default constructor";

	public const string ElementInitializerMethodNotAdd = "Element initializer method must be named 'Add'";

	public const string ElementInitializerMethodNoRefOutParam = "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter";

	public const string ElementInitializerMethodWithZeroArgs = "Element initializer method must have at least 1 parameter";

	public const string ElementInitializerMethodStatic = "Element initializer method must be an instance method";

	public const string TypeNotIEnumerable = "Type '{0}' is not IEnumerable";

	public const string UnhandledBinary = "Unhandled binary: {0}";

	public const string UnhandledBinding = "Unhandled binding ";

	public const string UnhandledBindingType = "Unhandled Binding Type: {0}";

	public const string UnhandledUnary = "Unhandled unary: {0}";

	public const string UnknownBindingType = "Unknown binding type";

	public const string UserDefinedOpMustHaveConsistentTypes = "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types.";

	public const string UserDefinedOpMustHaveValidReturnType = "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type.";

	public const string LogicalOperatorMustHaveBooleanOperators = "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators.";

	public const string MethodWithArgsDoesNotExistOnType = "No method '{0}' on type '{1}' is compatible with the supplied arguments.";

	public const string GenericMethodWithArgsDoesNotExistOnType = "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. ";

	public const string MethodWithMoreThanOneMatch = "More than one method '{0}' on type '{1}' is compatible with the supplied arguments.";

	public const string PropertyWithMoreThanOneMatch = "More than one property '{0}' on type '{1}' is compatible with the supplied arguments.";

	public const string IncorrectNumberOfTypeArgsForFunc = "An incorrect number of type arguments were specified for the declaration of a Func type.";

	public const string IncorrectNumberOfTypeArgsForAction = "An incorrect number of type arguments were specified for the declaration of an Action type.";

	public const string ArgumentCannotBeOfTypeVoid = "Argument type cannot be System.Void.";

	public const string OutOfRange = "{0} must be greater than or equal to {1}";

	public const string LabelTargetAlreadyDefined = "Cannot redefine label '{0}' in an inner block.";

	public const string LabelTargetUndefined = "Cannot jump to undefined label '{0}'.";

	public const string ControlCannotLeaveFinally = "Control cannot leave a finally block.";

	public const string ControlCannotLeaveFilterTest = "Control cannot leave a filter test.";

	public const string AmbiguousJump = "Cannot jump to ambiguous label '{0}'.";

	public const string ControlCannotEnterTry = "Control cannot enter a try block.";

	public const string ControlCannotEnterExpression = "Control cannot enter an expression--only statements can be jumped into.";

	public const string NonLocalJumpWithValue = "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values.";

	public const string CannotCompileConstant = "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value.";

	public const string CannotCompileDynamic = "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite.";

	public const string InvalidLvalue = "Invalid lvalue for assignment: {0}.";

	public const string UndefinedVariable = "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined";

	public const string CannotCloseOverByRef = "Cannot close over byref parameter '{0}' referenced in lambda '{1}'";

	public const string UnexpectedVarArgsCall = "Unexpected VarArgs call to method '{0}'";

	public const string RethrowRequiresCatch = "Rethrow statement is valid only inside a Catch block.";

	public const string TryNotAllowedInFilter = "Try expression is not allowed inside a filter body.";

	public const string MustRewriteToSameNode = "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type.";

	public const string MustRewriteChildToSameType = "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite.";

	public const string MustRewriteWithoutMethod = "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is intentional, override '{1}' and change it to allow this rewrite.";

	public const string InvalidNullValue = "The value null is not of type '{0}' and cannot be used in this collection.";

	public const string InvalidObjectType = "The value '{0}' is not of type '{1}' and cannot be used in this collection.";

	public const string TryNotSupportedForMethodsWithRefArgs = "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression.";

	public const string TryNotSupportedForValueTypeInstances = "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression.";

	public const string EnumerationIsDone = "Enumeration has either not started or has already finished.";

	public const string TestValueTypeDoesNotMatchComparisonMethodParameter = "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'";

	public const string SwitchValueTypeDoesNotMatchComparisonMethodParameter = "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'";

	public const string PdbGeneratorNeedsExpressionCompiler = "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod.";

	public const string InvalidArgumentValue = "Invalid argument value";

	public const string NonEmptyCollectionRequired = "Non-empty collection required";

	public const string CollectionModifiedWhileEnumerating = "Collection was modified; enumeration operation may not execute.";

	public const string ExpressionMustBeReadable = "Expression must be readable";

	public const string ExpressionTypeDoesNotMatchMethodParameter = "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'";

	public const string ExpressionTypeDoesNotMatchParameter = "Expression of type '{0}' cannot be used for parameter of type '{1}'";

	public const string ExpressionTypeDoesNotMatchConstructorParameter = "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'";

	public const string IncorrectNumberOfMethodCallArguments = "Incorrect number of arguments supplied for call to method '{0}'";

	public const string IncorrectNumberOfLambdaArguments = "Incorrect number of arguments supplied for lambda invocation";

	public const string IncorrectNumberOfConstructorArguments = "Incorrect number of arguments for constructor";

	public const string NonStaticConstructorRequired = "The constructor should not be static";

	public const string NonAbstractConstructorRequired = "Can't compile a NewExpression with a constructor declared on an abstract class";

	public const string FirstArgumentMustBeCallSite = "First argument of delegate must be CallSite";

	public const string NoOrInvalidRuleProduced = "No or Invalid rule produced";

	public const string TypeMustBeDerivedFromSystemDelegate = "Type must be derived from System.Delegate";

	public const string TypeParameterIsNotDelegate = "Type parameter is {0}. Expected a delegate.";

	public const string ArgumentTypeCannotBeVoid = "Argument type cannot be void";

	public const string ArgCntMustBeGreaterThanNameCnt = "Argument count must be greater than number of named arguments.";

	public const string BinderNotCompatibleWithCallSite = "The result type '{0}' of the binder '{1}' is not compatible with the result type '{2}' expected by the call site.";

	public const string BindingCannotBeNull = "Bind cannot return null.";

	public const string DynamicBinderResultNotAssignable = "The result type '{0}' of the dynamic binding produced by binder '{1}' is not compatible with the result type '{2}' expected by the call site.";

	public const string DynamicBindingNeedsRestrictions = "The result of the dynamic binding produced by the object with type '{0}' for the binder '{1}' needs at least one restriction.";

	public const string DynamicObjectResultNotAssignable = "The result type '{0}' of the dynamic binding produced by the object with type '{1}' for the binder '{2}' is not compatible with the result type '{3}' expected by the call site.";

	public const string InvalidMetaObjectCreated = "An IDynamicMetaObjectProvider {0} created an invalid DynamicMetaObject instance.";

	public const string AmbiguousMatchInExpandoObject = "More than one key matching '{0}' was found in the ExpandoObject.";

	public const string CollectionReadOnly = "Collection is read-only.";

	public const string KeyDoesNotExistInExpando = "The specified key '{0}' does not exist in the ExpandoObject.";

	public const string SameKeyExistsInExpando = "An element with the same key '{0}' already exists in the ExpandoObject.";

	public const string Arg_KeyNotFoundWithKey = "The given key '{0}' was not present in the dictionary.";

	public const string EmptyEnumerable = "Enumeration yielded no results";

	public const string MoreThanOneElement = "Sequence contains more than one element";

	public const string MoreThanOneMatch = "Sequence contains more than one matching element";

	public const string NoElements = "Sequence contains no elements";

	public const string NoMatch = "Sequence contains no matching element";

	public const string ParallelPartitionable_NullReturn = "The return value must not be null.";

	public const string ParallelPartitionable_IncorretElementCount = "The returned array's length must equal the number of partitions requested.";

	public const string ParallelPartitionable_NullElement = "Elements returned must not be null.";

	public const string PLINQ_CommonEnumerator_Current_NotStarted = "Enumeration has not started. MoveNext must be called to initiate enumeration.";

	public const string PLINQ_ExternalCancellationRequested = "The query has been canceled via the token supplied to WithCancellation.";

	public const string PLINQ_DisposeRequested = "The query enumerator has been disposed.";

	public const string ParallelQuery_DuplicateTaskScheduler = "The WithTaskScheduler operator may be used at most once in a query.";

	public const string ParallelQuery_DuplicateDOP = "The WithDegreeOfParallelism operator may be used at most once in a query.";

	public const string ParallelQuery_DuplicateExecutionMode = "The WithExecutionMode operator may be used at most once in a query.";

	public const string PartitionerQueryOperator_NullPartitionList = "Partitioner returned null instead of a list of partitions.";

	public const string PartitionerQueryOperator_WrongNumberOfPartitions = "Partitioner returned a wrong number of partitions.";

	public const string PartitionerQueryOperator_NullPartition = "Partitioner returned a null partition.";

	public const string ParallelQuery_DuplicateWithCancellation = "The WithCancellation operator may by used at most once in a query.";

	public const string ParallelQuery_DuplicateMergeOptions = "The WithMergeOptions operator may be used at most once in a query.";

	public const string PLINQ_EnumerationPreviouslyFailed = "The query enumerator previously threw an exception.";

	public const string ParallelQuery_PartitionerNotOrderable = "AsOrdered may not be used with a partitioner that is not orderable.";

	public const string ParallelQuery_InvalidAsOrderedCall = "AsOrdered may only be called on the result of AsParallel, ParallelEnumerable.Range, or ParallelEnumerable.Repeat.";

	public const string ParallelQuery_InvalidNonGenericAsOrderedCall = "Non-generic AsOrdered may only be called on the result of the non-generic AsParallel.";

	public const string ParallelEnumerable_BinaryOpMustUseAsParallel = "The second data source of a binary operator must be of type System.Linq.ParallelQuery<T> rather than System.Collections.Generic.IEnumerable<T>. To fix this problem, use the AsParallel() extension method to convert the right data source to System.Linq.ParallelQuery<T>.";

	public const string ParallelEnumerable_WithQueryExecutionMode_InvalidMode = "The executionMode argument contains an invalid value.";

	public const string ParallelEnumerable_WithMergeOptions_InvalidOptions = "The mergeOptions argument contains an invalid value.";

	public const string ArgumentNotIEnumerableGeneric = "{0} is not IEnumerable<>";

	public const string ArgumentNotValid = "Argument {0} is not valid";

	public const string NoMethodOnType = "There is no method '{0}' on type '{1}'";

	public const string NoMethodOnTypeMatchingArguments = "There is no method '{0}' on type '{1}' that matches the specified arguments";

	public const string EnumeratingNullEnumerableExpression = "Cannot enumerate a query created from a null IEnumerable<>";

	public const string ArgumentOutOfRange_NeedNonNegNum = "Non negative number is required.";

	public const string ArgumentOutOfRange_NeedValidPipeAccessRights = "Invalid PipeAccessRights value.";

	public const string Argument_InvalidOffLen = "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.";

	public const string Argument_NeedNonemptyPipeName = "pipeName cannot be an empty string.";

	public const string Argument_NonContainerInvalidAnyFlag = "This flag may not be set on a pipe.";

	public const string Argument_EmptyServerName = "serverName cannot be an empty string.  Use \\\\\\\".\\\\\\\" for current machine.";

	public const string Argument_InvalidHandle = "Invalid handle.";

	public const string ArgumentNull_Buffer = "Buffer cannot be null.";

	public const string ArgumentNull_ServerName = "serverName cannot be null. Use \\\".\\\" for current machine.";

	public const string ArgumentOutOfRange_AnonymousReserved = "The pipeName \\\"anonymous\\\" is reserved.";

	public const string ArgumentOutOfRange_TransmissionModeByteOrMsg = "For named pipes, transmission mode can be TransmissionMode.Byte or PipeTransmissionMode.Message. For anonymous pipes, transmission mode can be TransmissionMode.Byte.";

	public const string ArgumentOutOfRange_DirectionModeInOutOrInOut = "For named pipes, the pipe direction can be PipeDirection.In, PipeDirection.Out or PipeDirection.InOut. For anonymous pipes, the pipe direction can be PipeDirection.In or PipeDirection.Out.";

	public const string ArgumentOutOfRange_ImpersonationInvalid = "TokenImpersonationLevel.None, TokenImpersonationLevel.Anonymous, TokenImpersonationLevel.Identification, TokenImpersonationLevel.Impersonation or TokenImpersonationLevel.Delegation required.";

	public const string ArgumentOutOfRange_OptionsInvalid = "options contains an invalid flag.";

	public const string ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable = "HandleInheritability.None or HandleInheritability.Inheritable required.";

	public const string ArgumentOutOfRange_InvalidTimeout = "Timeout must be non-negative or equal to -1 (Timeout.Infinite)";

	public const string ArgumentOutOfRange_MaxNumServerInstances = "maxNumberOfServerInstances must either be a value between 1 and 254, or NamedPipeServerStream.MaxAllowedServerInstances (to obtain the maximum number allowed by system resources).";

	public const string ArgumentOutOfRange_NeedPosNum = "Positive number required.";

	public const string InvalidOperation_PipeNotYetConnected = "Pipe hasn't been connected yet.";

	public const string InvalidOperation_PipeDisconnected = "Pipe is in a disconnected state.";

	public const string InvalidOperation_PipeHandleNotSet = "Pipe handle has not been set.  Did your PipeStream implementation call InitializeHandle?";

	public const string InvalidOperation_PipeNotAsync = "Pipe is not opened in asynchronous mode.";

	public const string InvalidOperation_PipeReadModeNotMessage = "ReadMode is not of PipeTransmissionMode.Message.";

	public const string InvalidOperation_PipeAlreadyConnected = "Already in a connected state.";

	public const string InvalidOperation_PipeAlreadyDisconnected = "Already in a disconnected state.";

	public const string IO_EOF_ReadBeyondEOF = "Unable to read beyond the end of the stream.";

	public const string IO_FileNotFound = "Unable to find the specified file.";

	public const string IO_FileNotFound_FileName = "Could not find file '{0}'.";

	public const string IO_AlreadyExists_Name = "Cannot create \\\"{0}\\\" because a file or directory with the same name already exists.";

	public const string IO_FileExists_Name = "The file '{0}' already exists.";

	public const string IO_IO_PipeBroken = "Pipe is broken.";

	public const string IO_OperationAborted = "IO operation was aborted unexpectedly.";

	public const string IO_SharingViolation_File = "The process cannot access the file '{0}' because it is being used by another process.";

	public const string IO_SharingViolation_NoFileName = "The process cannot access the file because it is being used by another process.";

	public const string IO_PipeBroken = "Pipe is broken.";

	public const string IO_InvalidPipeHandle = "Invalid pipe handle.";

	public const string IO_PathNotFound_Path = "Could not find a part of the path '{0}'.";

	public const string IO_PathNotFound_NoPathName = "Could not find a part of the path.";

	public const string IO_PathTooLong = "The specified file name or path is too long, or a component of the specified path is too long.";

	public const string NotSupported_UnreadableStream = "Stream does not support reading.";

	public const string NotSupported_UnseekableStream = "Stream does not support seeking.";

	public const string NotSupported_UnwritableStream = "Stream does not support writing.";

	public const string NotSupported_AnonymousPipeUnidirectional = "Anonymous pipes can only be in one direction.";

	public const string NotSupported_AnonymousPipeMessagesNotSupported = "Anonymous pipes do not support PipeTransmissionMode.Message ReadMode.";

	public const string ObjectDisposed_PipeClosed = "Cannot access a closed pipe.";

	public const string UnauthorizedAccess_IODenied_Path = "Access to the path '{0}' is denied.";

	public const string UnauthorizedAccess_IODenied_NoPathName = "Access to the path is denied.";

	public const string ArgumentOutOfRange_FileLengthTooBig = "Specified file length was too large for the file system.";

	public const string PlatformNotSupported_MessageTransmissionMode = "Message transmission mode is not supported on this platform.";

	public const string PlatformNotSupported_RemotePipes = "Access to remote named pipes is not supported on this platform.";

	public const string PlatformNotSupported_InvalidPipeNameChars = "The name of a pipe on this platform must be a valid file name or a valid absolute path to a file name.";

	public const string ObjectDisposed_StreamClosed = "Cannot access a closed Stream.";

	public const string PlatformNotSupported_OperatingSystemError = "The operating system returned error '{0}' indicating that the operation is not supported.";

	public const string IO_AllPipeInstancesAreBusy = "All pipe instances are busy.";

	public const string IO_PathTooLong_Path = "The path '{0}' is too long, or a component of the specified path is too long.";

	public const string UnauthorizedAccess_NotOwnedByCurrentUser = "Could not connect to the pipe because it was not owned by the current user.";

	public const string UnauthorizedAccess_ClientIsNotCurrentUser = "Client connection (user id {0}) was refused because it was not owned by the current user (id {1}).";

	public const string net_invalidversion = "This protocol version is not supported.";

	public const string net_noseek = "This stream does not support seek operations.";

	public const string net_invasync = "Cannot block a call on this socket while an earlier asynchronous call is in progress.";

	public const string net_io_timeout_use_gt_zero = "Timeout can be only be set to 'System.Threading.Timeout.Infinite' or a value > 0.";

	public const string net_notconnected = "The operation is not allowed on non-connected sockets.";

	public const string net_notstream = "The operation is not allowed on non-stream oriented sockets.";

	public const string net_stopped = "Not listening. You must call the Start() method before calling this method.";

	public const string net_udpconnected = "Cannot send packets to an arbitrary host while connected.";

	public const string net_readonlystream = "The stream does not support writing.";

	public const string net_writeonlystream = "The stream does not support reading.";

	public const string net_InvalidAddressFamily = "The AddressFamily {0} is not valid for the {1} end point, use {2} instead.";

	public const string net_InvalidEndPointAddressFamily = "The supplied EndPoint of AddressFamily {0} is not valid for this Socket, use {1} instead.";

	public const string net_InvalidSocketAddressSize = "The supplied {0} is an invalid size for the {1} end point.";

	public const string net_invalidAddressList = "None of the discovered or specified addresses match the socket address family.";

	public const string net_completed_result = "This operation cannot be performed on a completed asynchronous result object.";

	public const string net_protocol_invalid_family = "'{0}' Client can only accept InterNetwork or InterNetworkV6 addresses.";

	public const string net_protocol_invalid_multicast_family = "Multicast family is not the same as the family of the '{0}' Client.";

	public const string net_sockets_zerolist = "The parameter {0} must contain one or more elements.";

	public const string net_sockets_blocking = "The operation is not allowed on a non-blocking Socket.";

	public const string net_sockets_useblocking = "Use the Blocking property to change the status of the Socket.";

	public const string net_sockets_select = "The operation is not allowed on objects of type {0}. Use only objects of type {1}.";

	public const string net_sockets_toolarge_select = "The {0} list contains too many items; a maximum of {1} is allowed.";

	public const string net_sockets_empty_select = "All lists are either null or empty.";

	public const string net_sockets_mustbind = "You must call the Bind method before performing this operation.";

	public const string net_sockets_mustlisten = "You must call the Listen method before performing this operation.";

	public const string net_sockets_mustnotlisten = "You may not perform this operation after calling the Listen method.";

	public const string net_sockets_mustnotbebound = "The socket must not be bound or connected.";

	public const string net_sockets_namedmustnotbebound = "{0}: The socket must not be bound or connected.";

	public const string net_sockets_invalid_ipaddress_length = "The number of specified IP addresses has to be greater than 0.";

	public const string net_sockets_invalid_optionValue = "The specified value is not a valid '{0}'.";

	public const string net_sockets_invalid_optionValue_all = "The specified value is not valid.";

	public const string net_sockets_invalid_dnsendpoint = "The parameter {0} must not be of type DnsEndPoint.";

	public const string net_sockets_disconnectedConnect = "Once the socket has been disconnected, you can only reconnect again asynchronously, and only to a different EndPoint.  BeginConnect must be called on a thread that won't exit until the operation has been completed.";

	public const string net_sockets_disconnectedAccept = "Once the socket has been disconnected, you can only accept again asynchronously.  BeginAccept must be called on a thread that won't exit until the operation has been completed.";

	public const string net_tcplistener_mustbestopped = "The TcpListener must not be listening before performing this operation.";

	public const string net_socketopinprogress = "An asynchronous socket operation is already in progress using this SocketAsyncEventArgs instance.";

	public const string net_buffercounttoosmall = "The Buffer space specified by the Count property is insufficient for the AcceptAsync method.";

	public const string net_multibuffernotsupported = "Multiple buffers cannot be used with this method.";

	public const string net_ambiguousbuffers = "Buffer and BufferList properties cannot both be non-null.";

	public const string net_io_writefailure = "Unable to write data to the transport connection: {0}.";

	public const string net_io_readfailure = "Unable to read data from the transport connection: {0}.";

	public const string net_io_invalidasyncresult = "The IAsyncResult object was not returned from the corresponding asynchronous method on this class.";

	public const string net_io_invalidendcall = "{0} can only be called once for each asynchronous operation.";

	public const string net_value_cannot_be_negative = "The specified value cannot be negative.";

	public const string ArgumentOutOfRange_Bounds_Lower_Upper = "Argument must be between {0} and {1}.";

	public const string net_sockets_connect_multiconnect_notsupported = "Sockets on this platform are invalid for use after a failed connection attempt.";

	public const string net_sockets_dualmode_receivefrom_notsupported = "This platform does not support packet information for dual-mode sockets.  If packet information is not required, use Socket.Receive.  If packet information is required set Socket.DualMode to false.";

	public const string net_sockets_accept_receive_notsupported = "This platform does not support receiving data with Socket.AcceptAsync.  Instead, make a separate call to Socket.ReceiveAsync.";

	public const string net_sockets_duplicateandclose_notsupported = "This platform does not support Socket.DuplicateAndClose.  Instead, create a new socket.";

	public const string net_sockets_transmitfileoptions_notsupported = "This platform does not support TransmitFileOptions other than TransmitFileOptions.UseDefaultWorkerThread.";

	public const string ArgumentOutOfRange_PathLengthInvalid = "The path '{0}' is of an invalid length for use with domain sockets on this platform.  The length must be between 1 and {1} characters, inclusive.";

	public const string net_io_readwritefailure = "Unable to transfer data on the transport connection: {0}.";

	public const string PlatformNotSupported_AcceptSocket = "Accepting into an existing Socket is not supported on this platform.";

	public const string PlatformNotSupported_IOControl = "Socket.IOControl handles Windows-specific control codes and is not supported on this platform.";

	public const string PlatformNotSupported_IPProtectionLevel = "IP protection level cannot be controlled on this platform.";

	public const string InvalidOperation_BufferNotExplicitArray = "This operation may only be performed when the buffer was set using the SetBuffer overload that accepts an array.";

	public const string InvalidOperation_IncorrectToken = "The result of the operation was already consumed and may not be used again.";

	public const string InvalidOperation_MultipleContinuations = "Another continuation was already registered.";

	public const string Argument_InvalidOidValue = "The OID value was invalid.";

	public const string Argument_InvalidValue = "Value was invalid.";

	public const string Arg_CryptographyException = "Error occurred during a cryptographic operation.";

	public const string Cryptography_ArgECDHKeySizeMismatch = "The keys from both parties must be the same size to generate a secret agreement.";

	public const string Cryptography_ArgECDHRequiresECDHKey = "Keys used with the ECDiffieHellmanCng algorithm must have an algorithm group of ECDiffieHellman.";

	public const string Cryptography_TlsRequiresLabelAndSeed = "The TLS key derivation function requires both the label and seed properties to be set.";

	public const string Cryptography_TlsRequires64ByteSeed = "The TLS key derivation function requires a seed value of exactly 64 bytes.";

	public const string Cryptography_BadHashSize_ForAlgorithm = "The provided value of {0} bytes does not match the expected size of {1} bytes for the algorithm ({2}).";

	public const string Cryptography_Config_EncodedOIDError = "Encoded OID length is too large (greater than 0x7f bytes).";

	public const string Cryptography_CSP_NoPrivateKey = "Object contains only the public half of a key pair. A private key must also be provided.";

	public const string Cryptography_Der_Invalid_Encoding = "ASN1 corrupted data.";

	public const string Cryptography_DSA_KeyGenNotSupported = "DSA keys can be imported, but new key generation is not supported on this platform.";

	public const string Cryptography_Encryption_MessageTooLong = "The message exceeds the maximum allowable length for the chosen options ({0}).";

	public const string Cryptography_ECXmlSerializationFormatRequired = "XML serialization of an elliptic curve key requires using an overload which specifies the XML format to be used.";

	public const string Cryptography_ECC_NamedCurvesOnly = "Only named curves are supported on this platform.";

	public const string Cryptography_HashAlgorithmNameNullOrEmpty = "The hash algorithm name cannot be null or empty.";

	public const string Cryptography_InvalidOID = "Object identifier (OID) is unknown.";

	public const string Cryptography_CurveNotSupported = "The specified curve '{0}' or its parameters are not valid for this platform.";

	public const string Cryptography_InvalidCurveOid = "The specified Oid is not valid. The Oid.FriendlyName or Oid.Value property must be set.";

	public const string Cryptography_InvalidCurveKeyParameters = "The specified key parameters are not valid. Q.X and Q.Y are required fields. Q.X, Q.Y must be the same length. If D is specified it must be the same length as Q.X and Q.Y for named curves or the same length as Order for explicit curves.";

	public const string Cryptography_InvalidDsaParameters_MissingFields = "The specified DSA parameters are not valid; P, Q, G and Y are all required.";

	public const string Cryptography_InvalidDsaParameters_MismatchedPGY = "The specified DSA parameters are not valid; P, G and Y must be the same length (the key size).";

	public const string Cryptography_InvalidDsaParameters_MismatchedQX = "The specified DSA parameters are not valid; Q and X (if present) must be the same length.";

	public const string Cryptography_InvalidDsaParameters_MismatchedPJ = "The specified DSA parameters are not valid; J (if present) must be shorter than P.";

	public const string Cryptography_InvalidDsaParameters_SeedRestriction_ShortKey = "The specified DSA parameters are not valid; Seed, if present, must be 20 bytes long for keys shorter than 1024 bits.";

	public const string Cryptography_InvalidDsaParameters_QRestriction_ShortKey = "The specified DSA parameters are not valid; Q must be 20 bytes long for keys shorter than 1024 bits.";

	public const string Cryptography_InvalidDsaParameters_QRestriction_LargeKey = "The specified DSA parameters are not valid; Q's length must be one of 20, 32 or 64 bytes.";

	public const string Cryptography_InvalidECCharacteristic2Curve = "The specified Characteristic2 curve parameters are not valid. Polynomial, A, B, G.X, G.Y, and Order are required. A, B, G.X, G.Y must be the same length, and the same length as Q.X, Q.Y and D if those are specified. Seed, Cofactor and Hash are optional. Other parameters are not allowed.";

	public const string Cryptography_InvalidECPrimeCurve = "The specified prime curve parameters are not valid. Prime, A, B, G.X, G.Y and Order are required and must be the same length, and the same length as Q.X, Q.Y and D if those are specified. Seed, Cofactor and Hash are optional. Other parameters are not allowed.";

	public const string Cryptography_InvalidECNamedCurve = "The specified named curve parameters are not valid. Only the Oid parameter must be set.";

	public const string Cryptography_InvalidKeySize = "Specified key is not a valid size for this algorithm.";

	public const string Cryptography_InvalidKey_SemiWeak = "Specified key is a known semi-weak key for '{0}' and cannot be used.";

	public const string Cryptography_InvalidKey_Weak = "Specified key is a known weak key for '{0}' and cannot be used.";

	public const string Cryptography_InvalidIVSize = "Specified initialization vector (IV) does not match the block size for this algorithm.";

	public const string Cryptography_InvalidOperation = "This operation is not supported for this class.";

	public const string Cryptography_InvalidPadding = "Padding is invalid and cannot be removed.";

	public const string Cryptography_InvalidRsaParameters = "The specified RSA parameters are not valid; both Exponent and Modulus are required fields.";

	public const string Cryptography_InvalidPaddingMode = "Specified padding mode is not valid for this algorithm.";

	public const string Cryptography_Invalid_IA5String = "The string contains a character not in the 7 bit ASCII character set.";

	public const string Cryptography_KeyTooSmall = "The key is too small for the requested operation.";

	public const string Cryptography_MissingIV = "The cipher mode specified requires that an initialization vector (IV) be used.";

	public const string Cryptography_MissingKey = "No asymmetric key object has been associated with this formatter object.";

	public const string Cryptography_MissingOID = "Required object identifier (OID) cannot be found.";

	public const string Cryptography_MustTransformWholeBlock = "TransformBlock may only process bytes in block sized increments.";

	public const string Cryptography_NotValidPrivateKey = "Key is not a valid private key.";

	public const string Cryptography_NotValidPublicOrPrivateKey = "Key is not a valid public or private key.";

	public const string Cryptography_OAEP_Decryption_Failed = "Error occurred while decoding OAEP padding.";

	public const string Cryptography_OpenInvalidHandle = "Cannot open an invalid handle.";

	public const string Cryptography_PartialBlock = "The input data is not a complete block.";

	public const string Cryptography_PasswordDerivedBytes_FewBytesSalt = "Salt is not at least eight bytes.";

	public const string Cryptography_RC2_EKS40 = "EffectiveKeySize value must be at least 40 bits.";

	public const string Cryptography_RC2_EKSKS = "KeySize value must be at least as large as the EffectiveKeySize value.";

	public const string Cryptography_RC2_EKSKS2 = "EffectiveKeySize must be the same as KeySize in this implementation.";

	public const string Cryptography_Rijndael_BlockSize = "BlockSize must be 128 in this implementation.";

	public const string Cryptography_RSA_DecryptWrongSize = "The length of the data to decrypt is not valid for the size of this key.";

	public const string Cryptography_SignHash_WrongSize = "The provided hash value is not the expected size for the specified hash algorithm.";

	public const string Cryptography_TransformBeyondEndOfBuffer = "Attempt to transform beyond end of buffer.";

	public const string Cryptography_CipherModeNotSupported = "The specified CipherMode '{0}' is not supported.";

	public const string Cryptography_UnknownHashAlgorithm = "'{0}' is not a known hash algorithm.";

	public const string Cryptography_UnknownPaddingMode = "Unknown padding mode used.";

	public const string Cryptography_UnexpectedTransformTruncation = "CNG provider unexpectedly terminated encryption or decryption prematurely.";

	public const string Cryptography_Unmapped_System_Typed_Error = "The system cryptographic library returned error '{0}' of type '{1}'";

	public const string Cryptography_UnsupportedPaddingMode = "The specified PaddingMode is not supported.";

	public const string NotSupported_Method = "Method not supported.";

	public const string NotSupported_SubclassOverride = "Method not supported. Derived class must override.";

	public const string Cryptography_AlgorithmTypesMustBeVisible = "Algorithms added to CryptoConfig must be accessable from outside their assembly.";

	public const string Cryptography_AddNullOrEmptyName = "CryptoConfig cannot add a mapping for a null or empty name.";

	public const string Argument_Invalid_SafeHandleInvalidOrClosed = "The method cannot be called with an invalid or closed SafeHandle.";

	public const string Cryptography_ArgExpectedECDiffieHellmanCngPublicKey = "DeriveKeyMaterial requires an ECDiffieHellmanCngPublicKey.";

	public const string Cryptography_ArgDSARequiresDSAKey = "Keys used with the DSACng algorithm must have an algorithm group of DSA.";

	public const string Cryptography_ArgECDsaRequiresECDsaKey = "Keys used with the ECDsaCng algorithm must have an algorithm group of ECDsa.";

	public const string Cryptography_ArgRSARequiresRSAKey = "Keys used with the RSACng algorithm must have an algorithm group of RSA.";

	public const string Cryptography_CngKeyWrongAlgorithm = "This key is for algorithm '{0}'. Expected '{1}'.";

	public const string Cryptography_InvalidAlgorithmGroup = "The algorithm group '{0}' is invalid.";

	public const string Cryptography_InvalidAlgorithmName = "The algorithm name '{0}' is invalid.";

	public const string Cryptography_InvalidCipherMode = "Specified cipher mode is not valid for this algorithm.";

	public const string Cryptography_InvalidKeyBlobFormat = "The key blob format '{0}' is invalid.";

	public const string Cryptography_InvalidProviderName = "The provider name '{0}' is invalid.";

	public const string Cryptography_KeyBlobParsingError = "Key Blob not in expected format.";

	public const string Cryptography_OpenEphemeralKeyHandleWithoutEphemeralFlag = "The CNG key handle being opened was detected to be ephemeral, but the EphemeralKey open option was not specified.";

	public const string Cryptography_WeakKey = "Specified key is a known weak key for this algorithm and cannot be used.";

	public const string PlatformNotSupported_CryptographyCng = "Windows Cryptography Next Generation (CNG) is not supported on this platform.";

	public const string CountdownEvent_Increment_AlreadyZero = "The event is already signaled and cannot be incremented.";

	public const string CountdownEvent_Increment_AlreadyMax = "The increment operation would cause the CurrentCount to overflow.";

	public const string CountdownEvent_Decrement_BelowZero = "Invalid attempt made to decrement the event's count below zero.";

	public const string Common_OperationCanceled = "The operation was canceled.";

	public const string Barrier_Dispose = "The barrier has been disposed.";

	public const string Barrier_SignalAndWait_InvalidOperation_ZeroTotal = "The barrier has no registered participants.";

	public const string Barrier_SignalAndWait_ArgumentOutOfRange = "The specified timeout must represent a value between -1 and Int32.MaxValue, inclusive.";

	public const string Barrier_RemoveParticipants_InvalidOperation = "The participantCount argument is greater than the number of participants that haven't yet arrived at the barrier in this phase.";

	public const string Barrier_RemoveParticipants_ArgumentOutOfRange = "The participantCount argument must be less than or equal the number of participants.";

	public const string Barrier_RemoveParticipants_NonPositive_ArgumentOutOfRange = "The participantCount argument must be a positive value.";

	public const string Barrier_InvalidOperation_CalledFromPHA = "This method may not be called from within the postPhaseAction.";

	public const string Barrier_AddParticipants_NonPositive_ArgumentOutOfRange = "The participantCount argument must be a positive value.";

	public const string Barrier_SignalAndWait_InvalidOperation_ThreadsExceeded = "The number of threads using the barrier exceeded the total number of registered participants.";

	public const string BarrierPostPhaseException = "The postPhaseAction failed with an exception.";

	public const string Barrier_ctor_ArgumentOutOfRange = "The participantCount argument must be non-negative and less than or equal to 32767.";

	public const string Barrier_AddParticipants_Overflow_ArgumentOutOfRange = "Adding participantCount participants would result in the number of participants exceeding the maximum number allowed.";

	public const string SynchronizationLockException_IncorrectDispose = "The lock is being disposed while still being used. It either is being held by a thread and/or has active waiters waiting to acquire the lock.";

	public const string SynchronizationLockException_MisMatchedWrite = "The write lock is being released without being held.";

	public const string LockRecursionException_UpgradeAfterReadNotAllowed = "Upgradeable lock may not be acquired with read lock held.";

	public const string LockRecursionException_UpgradeAfterWriteNotAllowed = "Upgradeable lock may not be acquired with write lock held in this mode. Acquiring Upgradeable lock gives the ability to read along with an option to upgrade to a writer.";

	public const string SynchronizationLockException_MisMatchedUpgrade = "The upgradeable lock is being released without being held.";

	public const string SynchronizationLockException_MisMatchedRead = "The read lock is being released without being held.";

	public const string LockRecursionException_WriteAfterReadNotAllowed = "Write lock may not be acquired with read lock held. This pattern is prone to deadlocks. Please ensure that read locks are released before taking a write lock. If an upgrade is necessary, use an upgrade lock in place of the read lock.";

	public const string LockRecursionException_RecursiveWriteNotAllowed = "Recursive write lock acquisitions not allowed in this mode.";

	public const string LockRecursionException_ReadAfterWriteNotAllowed = "A read lock may not be acquired with the write lock held in this mode.";

	public const string LockRecursionException_RecursiveUpgradeNotAllowed = "Recursive upgradeable lock acquisitions not allowed in this mode.";

	public const string LockRecursionException_RecursiveReadNotAllowed = "Recursive read lock acquisitions not allowed in this mode.";

	public const string Overflow_UInt16 = "Value was either too large or too small for a UInt16.";

	public const string ReaderWriterLock_Timeout = "The operation has timed out. {0}";

	public const string ArgumentOutOfRange_TimeoutMilliseconds = "Timeout value in milliseconds must be nonnegative and less than or equal to Int32.MaxValue, or -1 for an infinite timeout.";

	public const string ReaderWriterLock_NotOwner = "Attempt to release a lock that is not owned by the calling thread. {0}";

	public const string ExceptionFromHResult = "(Exception from HRESULT: 0x{0:X})";

	public const string ReaderWriterLock_InvalidLockCookie = "The specified lock cookie is invalid for this operation. {0}";

	public const string ReaderWriterLock_RestoreLockWithOwnedLocks = "ReaderWriterLock.RestoreLock was called without releasing all locks acquired since the call to ReleaseLock.";

	public const string HostExecutionContextManager_InvalidOperation_NotNewCaptureContext = "Cannot apply a context that has been marshaled across AppDomains, that was not acquired through a Capture operation or that has already been the argument to a Set call.";

	public const string HostExecutionContextManager_InvalidOperation_CannotOverrideSetWithoutRevert = "Must override both HostExecutionContextManager.SetHostExecutionContext and HostExecutionContextManager.Revert.";

	public const string HostExecutionContextManager_InvalidOperation_CannotUseSwitcherOtherThread = "Undo operation must be performed on the thread where the corresponding context was Set.";

	public const string Arg_NonZeroLowerBound = "The lower bound of target array must be zero.";

	public const string Arg_WrongType = "The value '{0}' is not of type '{1}' and cannot be used in this generic collection.";

	public const string Arg_ArrayPlusOffTooSmall = "Destination array is not long enough to copy all the items in the collection. Check array index and length.";

	public const string ArgumentOutOfRange_SmallCapacity = "capacity was less than the current size.";

	public const string Argument_AddingDuplicate = "An item with the same key has already been added. Key: {0}";

	public const string InvalidOperation_ConcurrentOperationsNotSupported = "Operations that change non-concurrent collections must have exclusive access. A concurrent update was performed on this collection and corrupted its state. The collection's state is no longer correct.";

	public const string InvalidOperation_EmptyQueue = "Queue empty.";

	public const string InvalidOperation_EnumOpCantHappen = "Enumeration has either not started or has already finished.";

	public const string InvalidOperation_EnumFailedVersion = "Collection was modified; enumeration operation may not execute.";

	public const string InvalidOperation_EmptyStack = "Stack empty.";

	public const string InvalidOperation_EnumNotStarted = "Enumeration has not started. Call MoveNext.";

	public const string InvalidOperation_EnumEnded = "Enumeration already finished.";

	public const string NotSupported_KeyCollectionSet = "Mutating a key collection derived from a dictionary is not allowed.";

	public const string NotSupported_ValueCollectionSet = "Mutating a value collection derived from a dictionary is not allowed.";

	public const string Arg_ArrayLengthsDiffer = "Array lengths must be the same.";

	public const string Arg_BitArrayTypeUnsupported = "Only supported array types for CopyTo on BitArrays are Boolean[], Int32[] and Byte[].";

	public const string Arg_HSCapacityOverflow = "HashSet capacity is too big.";

	public const string Arg_HTCapacityOverflow = "Hashtable's capacity overflowed and went negative. Check load factor, capacity and the current size of the table.";

	public const string Arg_InsufficientSpace = "Insufficient space in the target location to copy the information.";

	public const string Arg_RankMultiDimNotSupported = "Only single dimensional arrays are supported for the requested action.";

	public const string Argument_ArrayTooLarge = "The input array length must not exceed Int32.MaxValue / {0}. Otherwise BitArray.Length would exceed Int32.MaxValue.";

	public const string Argument_InvalidArrayType = "Target array type is not compatible with the type of items in the collection.";

	public const string ArgumentOutOfRange_BiggerThanCollection = "Must be less than or equal to the size of the collection.";

	public const string ArgumentOutOfRange_Index = "Index was out of range. Must be non-negative and less than the size of the collection.";

	public const string ExternalLinkedListNode = "The LinkedList node does not belong to current LinkedList.";

	public const string LinkedListEmpty = "The LinkedList is empty.";

	public const string LinkedListNodeIsAttached = "The LinkedList node already belongs to a LinkedList.";

	public const string NotSupported_SortedListNestedWrite = "This operation is not supported on SortedList nested types because they require modifying the original SortedList.";

	public const string SortedSet_LowerValueGreaterThanUpperValue = "Must be less than or equal to upperValue.";

	public const string Serialization_InvalidOnDeser = "OnDeserialization method was called while the object was not being deserialized.";

	public const string Serialization_MismatchedCount = "The serialized Count information doesn't match the number of items.";

	public const string Serialization_MissingKeys = "The keys for this dictionary are missing.";

	public const string Serialization_MissingValues = "The values for this dictionary are missing.";

	public const string Argument_MapNameEmptyString = "Map name cannot be an empty string.";

	public const string Argument_EmptyFile = "A positive capacity must be specified for a Memory Mapped File backed by an empty file.";

	public const string Argument_NewMMFWriteAccessNotAllowed = "MemoryMappedFileAccess.Write is not permitted when creating new memory mapped files. Use MemoryMappedFileAccess.ReadWrite instead.";

	public const string Argument_ReadAccessWithLargeCapacity = "When specifying MemoryMappedFileAccess.Read access, the capacity must not be larger than the file size.";

	public const string Argument_NewMMFAppendModeNotAllowed = "FileMode.Append is not permitted when creating new memory mapped files. Instead, use MemoryMappedFileView to ensure write-only access within a specified region.";

	public const string Argument_NewMMFTruncateModeNotAllowed = "FileMode.Truncate is not permitted when creating new memory mapped files.";

	public const string ArgumentNull_MapName = "Map name cannot be null.";

	public const string ArgumentNull_FileStream = "fileStream cannot be null.";

	public const string ArgumentOutOfRange_CapacityLargerThanLogicalAddressSpaceNotAllowed = "The capacity cannot be greater than the size of the system's logical address space.";

	public const string ArgumentOutOfRange_NeedPositiveNumber = "A positive number is required.";

	public const string ArgumentOutOfRange_PositiveOrDefaultCapacityRequired = "The capacity must be greater than or equal to 0. 0 represents the size of the file being mapped.";

	public const string ArgumentOutOfRange_PositiveOrDefaultSizeRequired = "The size must be greater than or equal to 0. If 0 is specified, the view extends from the specified offset to the end of the file mapping.";

	public const string ArgumentOutOfRange_CapacityGEFileSizeRequired = "The capacity may not be smaller than the file size.";

	public const string IO_NotEnoughMemory = "Not enough memory to map view.";

	public const string InvalidOperation_CantCreateFileMapping = "Cannot create file mapping.";

	public const string NotSupported_MMViewStreamsFixedLength = "MemoryMappedViewStreams are fixed length.";

	public const string ObjectDisposed_ViewAccessorClosed = "Cannot access a closed accessor.";

	public const string ObjectDisposed_StreamIsClosed = "Cannot access a closed Stream.";

	public const string PlatformNotSupported_NamedMaps = "Named maps are not supported.";

	public const string MethodBuilderDoesNotHaveTypeBuilder = "MethodBuilder does not have a valid TypeBuilder";

	public const string Cryptography_NonCompliantFIPSAlgorithm = "This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms.";

	public const string InvalidOperation_ViewIsNull = "The underlying MemoryMappedView object is null.";

	public const string ArgumentOutOfRange_InvalidPipeAccessRights = "Invalid PipeAccessRights flag.";

	public const string ArgumentOutOfRange_AdditionalAccessLimited = "additionalAccessRights is limited to the PipeAccessRights.ChangePermissions, PipeAccessRights.TakeOwnership, and PipeAccessRights.AccessSystemSecurity flags when creating NamedPipeServerStreams.";

	public const string InterfaceType_Must_Be_Interface = "The type '{0}' must be an interface, not a class.";

	public const string BaseType_Cannot_Be_Sealed = "The base type '{0}' cannot be sealed.";

	public const string BaseType_Cannot_Be_Abstract = "The base type '{0}' cannot be abstract.";

	public const string BaseType_Must_Have_Default_Ctor = "The base type '{0}' must have a public parameterless constructor.";

	public const string Cryptography_Cert_AlreadyHasPrivateKey = "The certificate already has an associated private key.";

	public const string Cryptography_PrivateKey_WrongAlgorithm = "The provided key does not match the public key algorithm for this certificate.";

	public const string Cryptography_PrivateKey_DoesNotMatch = "The provided key does not match the public key for this certificate.";

	internal static string GetString(string name, params object[] args)
	{
		return GetString(CultureInfo.InvariantCulture, name, args);
	}

	internal static string GetString(CultureInfo culture, string name, params object[] args)
	{
		return string.Format(culture, name, args);
	}

	internal static string GetString(string name)
	{
		return name;
	}

	internal static string GetString(CultureInfo culture, string name)
	{
		return name;
	}

	internal static string Format(string resourceFormat, params object[] args)
	{
		if (args != null)
		{
			return string.Format(CultureInfo.InvariantCulture, resourceFormat, args);
		}
		return resourceFormat;
	}

	internal static string Format(string resourceFormat, object p1)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1);
	}

	internal static string Format(string resourceFormat, object p1, object p2)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2);
	}

	internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2)
	{
		return string.Format(ci, resourceFormat, p1, p2);
	}

	internal static string Format(string resourceFormat, object p1, object p2, object p3)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3);
	}

	internal static string GetResourceString(string str)
	{
		return str;
	}
}
namespace Microsoft.Win32.SafeHandles
{
	public sealed class SafePipeHandle : SafeHandleZeroOrMinusOneIsInvalid
	{
		private const int DefaultInvalidHandle = 0;

		protected override bool ReleaseHandle()
		{
			return global::Interop.Kernel32.CloseHandle(handle);
		}

		internal SafePipeHandle()
			: this(new IntPtr(0), ownsHandle: true)
		{
		}

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

		internal void SetHandle(int descriptor)
		{
			SetHandle((IntPtr)descriptor);
		}
	}
	public sealed class SafeMemoryMappedFileHandle : SafeHandleZeroOrMinusOneIsInvalid
	{
		public SafeMemoryMappedFileHandle(IntPtr preexistingHandle, bool ownsHandle)
			: base(ownsHandle)
		{
			handle = preexistingHandle;
		}

		protected override bool ReleaseHandle()
		{
			MemoryMapImpl.CloseMapping(handle);
			handle = IntPtr.Zero;
			return true;
		}

		internal SafeMemoryMappedFileHandle()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	public sealed class SafeMemoryMappedViewHandle : SafeBuffer
	{
		private IntPtr mmap_handle;

		internal SafeMemoryMappedViewHandle(IntPtr mmap_handle, IntPtr base_address, long size)
			: base(ownsHandle: true)
		{
			this.mmap_handle = mmap_handle;
			handle = base_address;
			Initialize((ulong)size);
		}

		internal void Flush()
		{
			MemoryMapImpl.Flush(mmap_handle);
		}

		protected override bool ReleaseHandle()
		{
			if (handle != (IntPtr)(-1))
			{
				return MemoryMapImpl.Unmap(mmap_handle);
			}
			throw new NotImplementedException();
		}

		internal SafeMemoryMappedViewHandle()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	public abstract class SafeNCryptHandle : SafeHandleZeroOrMinusOneIsInvalid
	{
		public override bool IsInvalid
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		protected SafeNCryptHandle()
			: base(ownsHandle: true)
		{
		}

		protected SafeNCryptHandle(IntPtr handle, SafeHandle parentHandle)
			: base(ownsHandle: false)
		{
			throw new NotImplementedException();
		}

		protected override bool ReleaseHandle()
		{
			return false;
		}

		protected abstract bool ReleaseNativeHandle();
	}
	public sealed class SafeNCryptKeyHandle : SafeNCryptHandle
	{
		public SafeNCryptKeyHandle()
		{
		}

		public SafeNCryptKeyHandle(IntPtr handle, SafeHandle parentHandle)
			: base(handle, parentHandle)
		{
		}

		protected override bool ReleaseNativeHandle()
		{
			return false;
		}
	}
	public sealed class SafeNCryptProviderHandle : SafeNCryptHandle
	{
		protected override bool ReleaseNativeHandle()
		{
			return false;
		}
	}
	public sealed class SafeNCryptSecretHandle : SafeNCryptHandle
	{
		protected override bool ReleaseNativeHandle()
		{
			return false;
		}
	}
}
namespace System
{
	internal static class NotImplemented
	{
		internal static Exception ByDesign => new NotImplementedException();

		internal static Exception ByDesignWithMessage(string message)
		{
			return new NotImplementedException(message);
		}

		internal static Exception ActiveIssue(string issue)
		{
			return new NotImplementedException();
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoTODOAttribute : Attribute
	{
		private string comment;

		public string Comment => comment;

		public MonoTODOAttribute()
		{
		}

		public MonoTODOAttribute(string comment)
		{
			this.comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoDocumentationNoteAttribute : MonoTODOAttribute
	{
		public MonoDocumentationNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoExtensionAttribute : MonoTODOAttribute
	{
		public MonoExtensionAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoInternalNoteAttribute : MonoTODOAttribute
	{
		public MonoInternalNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoLimitationAttribute : MonoTODOAttribute
	{
		public MonoLimitationAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoNotSupportedAttribute : MonoTODOAttribute
	{
		public MonoNotSupportedAttribute(string comment)
			: base(comment)
		{
		}
	}
	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
	public delegate void Action<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9);
	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10);
	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11);
	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12);
	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13);
	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14);
	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15);
	public delegate TResult Func<in T1, in T2, in T3, in T4, in T5, in T6, in T7, in T8, in T9, in T10, in T11, in T12, in T13, in T14, in T15, in T16, out TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, T6 arg6, T7 arg7, T8 arg8, T9 arg9, T10 arg10, T11 arg11, T12 arg12, T13 arg13, T14 arg14, T15 arg15, T16 arg16);
	internal static class MonoUtil
	{
		public static readonly bool IsUnix;

		static MonoUtil()
		{
			int platform = (int)Environment.OSVersion.Platform;
			IsUnix = platform == 4 || platform == 128 || platform == 6;
		}
	}
}
namespace System.Security.Cryptography
{
	[DebuggerDisplay("ECCurve: {Oid}")]
	public struct ECCurve
	{
		public enum ECCurveType
		{
			Implicit,
			PrimeShortWeierstrass,
			PrimeTwistedEdwards,
			PrimeMontgomery,
			Characteristic2,
			Named
		}

		public static class NamedCurves
		{
			private const string ECDSA_P256_OID_VALUE = "1.2.840.10045.3.1.7";

			private const string ECDSA_P384_OID_VALUE = "1.3.132.0.34";

			private const string ECDSA_P521_OID_VALUE = "1.3.132.0.35";

			public static ECCurve brainpoolP160r1 => CreateFromFriendlyName("brainpoolP160r1");

			public static ECCurve brainpoolP160t1 => CreateFromFriendlyName("brainpoolP160t1");

			public static ECCurve brainpoolP192r1 => CreateFromFriendlyName("brainpoolP192r1");

			public static ECCurve brainpoolP192t1 => CreateFromFriendlyName("brainpoolP192t1");

			public static ECCurve brainpoolP224r1 => CreateFromFriendlyName("brainpoolP224r1");

			public static ECCurve brainpoolP224t1 => CreateFromFriendlyName("brainpoolP224t1");

			public static ECCurve brainpoolP256r1 => CreateFromFriendlyName("brainpoolP256r1");

			public static ECCurve brainpoolP256t1 => CreateFromFriendlyName("brainpoolP256t1");

			public static ECCurve brainpoolP320r1 => CreateFromFriendlyName("brainpoolP320r1");

			public static ECCurve brainpoolP320t1 => CreateFromFriendlyName("brainpoolP320t1");

			public static ECCurve brainpoolP384r1 => CreateFromFriendlyName("brainpoolP384r1");

			public static ECCurve brainpoolP384t1 => CreateFromFriendlyName("brainpoolP384t1");

			public static ECCurve brainpoolP512r1 => CreateFromFriendlyName("brainpoolP512r1");

			public static ECCurve brainpoolP512t1 => CreateFromFriendlyName("brainpoolP512t1");

			public static ECCurve nistP256 => CreateFromValueAndName("1.2.840.10045.3.1.7", "nistP256");

			public static ECCurve nistP384 => CreateFromValueAndName("1.3.132.0.34", "nistP384");

			public static ECCurve nistP521 => CreateFromValueAndName("1.3.132.0.35", "nistP521");
		}

		public byte[] A;

		public byte[] B;

		public ECPoint G;

		public byte[] Order;

		public byte[] Cofactor;

		public byte[] Seed;

		public ECCurveType CurveType;

		public HashAlgorithmName? Hash;

		public byte[] Polynomial;

		public byte[] Prime;

		private Oid _oid;

		public Oid Oid
		{
			get
			{
				return new Oid(_oid.Value, _oid.FriendlyName);
			}
			private set
			{
				if (value == null)
				{
					throw new ArgumentNullException("Oid");
				}
				if (string.IsNullOrEmpty(value.Value) && string.IsNullOrEmpty(value.FriendlyName))
				{
					throw new ArgumentException($"The specified Oid is not valid. The Oid.FriendlyName or Oid.Value property must be set.");
				}
				_oid = value;
			}
		}

		public bool IsPrime
		{
			get
			{
				if (CurveType != ECCurveType.PrimeShortWeierstrass && CurveType != ECCurveType.PrimeMontgomery)
				{
					return CurveType == ECCurveType.PrimeTwistedEdwards;
				}
				return true;
			}
		}

		public bool IsCharacteristic2 => CurveType == ECCurveType.Characteristic2;

		public bool IsExplicit
		{
			get
			{
				if (!IsPrime)
				{
					return IsCharacteristic2;
				}
				return true;
			}
		}

		public bool IsNamed => CurveType == ECCurveType.Named;

		private static ECCurve Create(Oid oid)
		{
			ECCurve result = default(ECCurve);
			result.CurveType = ECCurveType.Named;
			result.Oid = oid;
			return result;
		}

		public static ECCurve CreateFromOid(Oid curveOid)
		{
			return Create(new Oid(curveOid.Value, curveOid.FriendlyName));
		}

		public static ECCurve CreateFromFriendlyName(string oidFriendlyName)
		{
			if (oidFriendlyName == null)
			{
				throw new ArgumentNullException("oidFriendlyName");
			}
			return CreateFromValueAndName(null, oidFriendlyName);
		}

		public static ECCurve CreateFromValue(string oidValue)
		{
			if (oidValue == null)
			{
				throw new ArgumentNullException("oidValue");
			}
			return CreateFromValueAndName(oidValue, null);
		}

		private static ECCurve CreateFromValueAndName(string oidValue, string oidFriendlyName)
		{
			return Create(new Oid(oidValue, oidFriendlyName));
		}

		public void Validate()
		{
			if (IsNamed)
			{
				if (HasAnyExplicitParameters())
				{
					throw new CryptographicException("The specified named curve parameters are not valid. Only the Oid parameter must be set.");
				}
				if (Oid == null || (string.IsNullOrEmpty(Oid.FriendlyName) && string.IsNullOrEmpty(Oid.Value)))
				{
					throw new CryptographicException("The specified Oid is not valid. The Oid.FriendlyName or Oid.Value property must be set.");
				}
			}
			else if (IsExplicit)
			{
				bool flag = false;
				if (A == null || B == null || B.Length != A.Length || G.X == null || G.X.Length != A.Length || G.Y == null || G.Y.Length != A.Length || Order == null || Order.Length == 0 || Cofactor == null || Cofactor.Length == 0)
				{
					flag = true;
				}
				if (IsPrime)
				{
					if (!flag && (Prime == null || Prime.Length != A.Length))
					{
						flag = true;
					}
					if (flag)
					{
						throw new CryptographicException("The specified prime curve parameters are not valid. Prime, A, B, G.X, G.Y and Order are required and must be the same length, and the same length as Q.X, Q.Y and D if those are 

BepInEx/core/System.Data.DataSetExtensions.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Threading;
using Unity;

[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Data.DataSetExtensions.dll")]
[assembly: AssemblyDescription("System.Data.DataSetExtensions.dll")]
[assembly: AssemblyDefaultAlias("System.Data.DataSetExtensions.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: ComVisible(false)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: SecurityCritical]
[assembly: AssemblyVersion("4.0.0.0")]
internal static class DataSetUtil
{
	private static readonly Type s_stackOverflowType = typeof(StackOverflowException);

	private static readonly Type s_outOfMemoryType = typeof(OutOfMemoryException);

	private static readonly Type s_threadAbortType = typeof(ThreadAbortException);

	private static readonly Type s_nullReferenceType = typeof(NullReferenceException);

	private static readonly Type s_accessViolationType = typeof(AccessViolationException);

	private static readonly Type s_securityType = typeof(SecurityException);

	internal static void CheckArgumentNull<T>(T argumentValue, string argumentName) where T : class
	{
		if (argumentValue == null)
		{
			throw ArgumentNull(argumentName);
		}
	}

	private static T TraceException<T>(string trace, T e)
	{
		return e;
	}

	private static T TraceExceptionAsReturnValue<T>(T e)
	{
		return TraceException("<comm.ADP.TraceException|ERR|THROW> '%ls'\n", e);
	}

	internal static ArgumentException Argument(string message)
	{
		return TraceExceptionAsReturnValue(new ArgumentException(message));
	}

	internal static ArgumentNullException ArgumentNull(string message)
	{
		return TraceExceptionAsReturnValue(new ArgumentNullException(message));
	}

	internal static ArgumentOutOfRangeException ArgumentOutOfRange(string message, string parameterName)
	{
		return TraceExceptionAsReturnValue(new ArgumentOutOfRangeException(parameterName, message));
	}

	internal static InvalidCastException InvalidCast(string message)
	{
		return TraceExceptionAsReturnValue(new InvalidCastException(message));
	}

	internal static InvalidOperationException InvalidOperation(string message)
	{
		return TraceExceptionAsReturnValue(new InvalidOperationException(message));
	}

	internal static NotSupportedException NotSupported(string message)
	{
		return TraceExceptionAsReturnValue(new NotSupportedException(message));
	}

	internal static ArgumentOutOfRangeException InvalidEnumerationValue(Type type, int value)
	{
		return ArgumentOutOfRange($"The {type.Name} enumeration value, {value.ToString(CultureInfo.InvariantCulture)}, is not valid.", type.Name);
	}

	internal static ArgumentOutOfRangeException InvalidDataRowState(DataRowState value)
	{
		return InvalidEnumerationValue(typeof(DataRowState), (int)value);
	}

	internal static ArgumentOutOfRangeException InvalidLoadOption(LoadOption value)
	{
		return InvalidEnumerationValue(typeof(LoadOption), (int)value);
	}

	internal static bool IsCatchableExceptionType(Exception e)
	{
		Type type = e.GetType();
		if (type != s_stackOverflowType && type != s_outOfMemoryType && type != s_threadAbortType && type != s_nullReferenceType && type != s_accessViolationType)
		{
			return !s_securityType.IsAssignableFrom(type);
		}
		return false;
	}
}
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal class SR
{
	public const string DataSetLinq_InvalidEnumerationValue = "The {0} enumeration value, {1}, is not valid.";

	public const string DataSetLinq_EmptyDataRowSource = "The source contains no DataRows.";

	public const string DataSetLinq_NullDataRow = "The source contains a DataRow reference that is null.";

	public const string DataSetLinq_CannotLoadDetachedRow = "The source contains a detached DataRow that cannot be copied to the DataTable.";

	public const string DataSetLinq_CannotCompareDeletedRow = "The DataRowComparer does not work with DataRows that have been deleted since it only compares current values.";

	public const string DataSetLinq_CannotLoadDeletedRow = "The source contains a deleted DataRow that cannot be copied to the DataTable.";

	public const string DataSetLinq_NonNullableCast = "Cannot cast DBNull. Value to type '{0}'. Please use a nullable type.";
}
namespace System.Data
{
	public static class DataRowComparer
	{
		public static DataRowComparer<DataRow> Default => DataRowComparer<DataRow>.Default;

		internal static bool AreEqual(object a, object b)
		{
			if (a == b)
			{
				return true;
			}
			if (a == null || a == DBNull.Value || b == null || b == DBNull.Value)
			{
				return false;
			}
			if (!a.Equals(b))
			{
				if (a.GetType().IsArray)
				{
					return CompareArray((Array)a, b as Array);
				}
				return false;
			}
			return true;
		}

		private static bool AreElementEqual(object a, object b)
		{
			if (a == b)
			{
				return true;
			}
			if (a == null || a == DBNull.Value || b == null || b == DBNull.Value)
			{
				return false;
			}
			return a.Equals(b);
		}

		private static bool CompareArray(Array a, Array b)
		{
			if (b == null || 1 != a.Rank || 1 != b.Rank || a.Length != b.Length)
			{
				return false;
			}
			int num = a.GetLowerBound(0);
			int num2 = b.GetLowerBound(0);
			if (a.GetType() == b.GetType() && num == 0 && num2 == 0)
			{
				switch (Type.GetTypeCode(a.GetType().GetElementType()))
				{
				case TypeCode.Byte:
					return CompareEquatableArray((byte[])a, (byte[])b);
				case TypeCode.Int16:
					return CompareEquatableArray((short[])a, (short[])b);
				case TypeCode.Int32:
					return CompareEquatableArray((int[])a, (int[])b);
				case TypeCode.Int64:
					return CompareEquatableArray((long[])a, (long[])b);
				case TypeCode.String:
					return CompareEquatableArray((string[])a, (string[])b);
				}
			}
			int num3 = num + a.Length;
			while (num < num3)
			{
				if (!AreElementEqual(a.GetValue(num), b.GetValue(num2)))
				{
					return false;
				}
				num++;
				num2++;
			}
			return true;
		}

		private static bool CompareEquatableArray<TElem>(TElem[] a, TElem[] b) where TElem : IEquatable<TElem>
		{
			for (int i = 0; i < a.Length; i++)
			{
				if (!a[i].Equals(b[i]))
				{
					return false;
				}
			}
			return true;
		}
	}
	public sealed class DataRowComparer<TRow> : IEqualityComparer<TRow> where TRow : DataRow
	{
		private static DataRowComparer<TRow> s_instance = new DataRowComparer<TRow>();

		public static DataRowComparer<TRow> Default => s_instance;

		private DataRowComparer()
		{
		}

		public bool Equals(TRow leftRow, TRow rightRow)
		{
			if (leftRow == rightRow)
			{
				return true;
			}
			if (leftRow == null || rightRow == null)
			{
				return false;
			}
			if (leftRow.RowState == DataRowState.Deleted || rightRow.RowState == DataRowState.Deleted)
			{
				throw global::DataSetUtil.InvalidOperation("The DataRowComparer does not work with DataRows that have been deleted since it only compares current values.");
			}
			int count = leftRow.Table.Columns.Count;
			if (count != rightRow.Table.Columns.Count)
			{
				return false;
			}
			for (int i = 0; i < count; i++)
			{
				if (!DataRowComparer.AreEqual(leftRow[i], rightRow[i]))
				{
					return false;
				}
			}
			return true;
		}

		public int GetHashCode(TRow row)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			if (row.RowState == DataRowState.Deleted)
			{
				throw global::DataSetUtil.InvalidOperation("The DataRowComparer does not work with DataRows that have been deleted since it only compares current values.");
			}
			int result = 0;
			if (row.Table.Columns.Count > 0)
			{
				object obj = row[0];
				if (!obj.GetType().IsArray)
				{
					result = ((!(obj is ValueType valueType)) ? obj.GetHashCode() : valueType.GetHashCode());
				}
				else
				{
					Array array = obj as Array;
					if (array.Rank > 1)
					{
						result = obj.GetHashCode();
					}
					else if (array.Length > 0)
					{
						result = array.GetValue(array.GetLowerBound(0)).GetHashCode();
					}
				}
			}
			return result;
		}
	}
	public static class DataRowExtensions
	{
		private static class UnboxT<T>
		{
			internal static readonly Converter<object, T> s_unbox = Create();

			private static Converter<object, T> Create()
			{
				if (default(T) == null)
				{
					return ReferenceOrNullableField;
				}
				return ValueField;
			}

			private static T ReferenceOrNullableField(object value)
			{
				if (DBNull.Value != value)
				{
					return (T)value;
				}
				return default(T);
			}

			private static T ValueField(object value)
			{
				if (DBNull.Value == value)
				{
					throw global::DataSetUtil.InvalidCast($"Cannot cast DBNull. Value to type '{typeof(T).ToString()}'. Please use a nullable type.");
				}
				return (T)value;
			}
		}

		public static T Field<T>(this DataRow row, string columnName)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			return UnboxT<T>.s_unbox(row[columnName]);
		}

		public static T Field<T>(this DataRow row, DataColumn column)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			return UnboxT<T>.s_unbox(row[column]);
		}

		public static T Field<T>(this DataRow row, int columnIndex)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			return UnboxT<T>.s_unbox(row[columnIndex]);
		}

		public static T Field<T>(this DataRow row, int columnIndex, DataRowVersion version)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			return UnboxT<T>.s_unbox(row[columnIndex, version]);
		}

		public static T Field<T>(this DataRow row, string columnName, DataRowVersion version)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			return UnboxT<T>.s_unbox(row[columnName, version]);
		}

		public static T Field<T>(this DataRow row, DataColumn column, DataRowVersion version)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			return UnboxT<T>.s_unbox(row[column, version]);
		}

		public static void SetField<T>(this DataRow row, int columnIndex, T value)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			row[columnIndex] = ((object)value) ?? DBNull.Value;
		}

		public static void SetField<T>(this DataRow row, string columnName, T value)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			row[columnName] = ((object)value) ?? DBNull.Value;
		}

		public static void SetField<T>(this DataRow row, DataColumn column, T value)
		{
			global::DataSetUtil.CheckArgumentNull(row, "row");
			row[column] = ((object)value) ?? DBNull.Value;
		}
	}
	public static class DataTableExtensions
	{
		public static EnumerableRowCollection<DataRow> AsEnumerable(this DataTable source)
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return new EnumerableRowCollection<DataRow>(source);
		}

		public static DataTable CopyToDataTable<T>(this IEnumerable<T> source) where T : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return LoadTableFromEnumerable(source, null, null, null);
		}

		public static void CopyToDataTable<T>(this IEnumerable<T> source, DataTable table, LoadOption options) where T : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			global::DataSetUtil.CheckArgumentNull(table, "table");
			LoadTableFromEnumerable(source, table, options, null);
		}

		public static void CopyToDataTable<T>(this IEnumerable<T> source, DataTable table, LoadOption options, FillErrorEventHandler errorHandler) where T : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			global::DataSetUtil.CheckArgumentNull(table, "table");
			LoadTableFromEnumerable(source, table, options, errorHandler);
		}

		private static DataTable LoadTableFromEnumerable<T>(IEnumerable<T> source, DataTable table, LoadOption? options, FillErrorEventHandler errorHandler) where T : DataRow
		{
			if (options.HasValue)
			{
				LoadOption value = options.Value;
				if ((uint)(value - 1) > 2u)
				{
					throw global::DataSetUtil.InvalidLoadOption(options.Value);
				}
			}
			using (IEnumerator<T> enumerator = source.GetEnumerator())
			{
				if (!enumerator.MoveNext())
				{
					return table ?? throw global::DataSetUtil.InvalidOperation("The source contains no DataRows.");
				}
				if (table == null)
				{
					DataRow current = enumerator.Current;
					if (current == null)
					{
						throw global::DataSetUtil.InvalidOperation("The source contains a DataRow reference that is null.");
					}
					table = new DataTable
					{
						Locale = CultureInfo.CurrentCulture
					};
					foreach (DataColumn column in current.Table.Columns)
					{
						table.Columns.Add(column.ColumnName, column.DataType);
					}
				}
				table.BeginLoadData();
				try
				{
					do
					{
						DataRow current = enumerator.Current;
						if (current == null)
						{
							continue;
						}
						object[] values = null;
						try
						{
							switch (current.RowState)
							{
							case DataRowState.Detached:
								if (!current.HasVersion(DataRowVersion.Proposed))
								{
									throw global::DataSetUtil.InvalidOperation("The source contains a detached DataRow that cannot be copied to the DataTable.");
								}
								goto case DataRowState.Unchanged;
							case DataRowState.Unchanged:
							case DataRowState.Added:
							case DataRowState.Modified:
								values = current.ItemArray;
								if (options.HasValue)
								{
									table.LoadDataRow(values, options.Value);
								}
								else
								{
									table.LoadDataRow(values, fAcceptChanges: true);
								}
								break;
							case DataRowState.Deleted:
								throw global::DataSetUtil.InvalidOperation("The source contains a deleted DataRow that cannot be copied to the DataTable.");
							default:
								throw global::DataSetUtil.InvalidDataRowState(current.RowState);
							}
						}
						catch (Exception ex)
						{
							if (!global::DataSetUtil.IsCatchableExceptionType(ex))
							{
								throw;
							}
							FillErrorEventArgs fillErrorEventArgs = null;
							if (errorHandler != null)
							{
								fillErrorEventArgs = new FillErrorEventArgs(table, values)
								{
									Errors = ex
								};
								errorHandler(enumerator, fillErrorEventArgs);
							}
							if (fillErrorEventArgs == null)
							{
								throw;
							}
							if (!fillErrorEventArgs.Continue)
							{
								if ((fillErrorEventArgs.Errors ?? ex) == ex)
								{
									throw;
								}
								throw fillErrorEventArgs.Errors;
							}
						}
					}
					while (enumerator.MoveNext());
				}
				finally
				{
					table.EndLoadData();
				}
			}
			return table;
		}

		public static DataView AsDataView(this DataTable table)
		{
			throw new PlatformNotSupportedException();
		}

		public static DataView AsDataView<T>(this EnumerableRowCollection<T> source) where T : DataRow
		{
			throw new PlatformNotSupportedException();
		}
	}
	public abstract class EnumerableRowCollection : IEnumerable
	{
		internal abstract Type ElementType { get; }

		internal abstract DataTable Table { get; }

		internal EnumerableRowCollection()
		{
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return null;
		}
	}
	public class EnumerableRowCollection<TRow> : EnumerableRowCollection, IEnumerable<TRow>, IEnumerable
	{
		private readonly DataTable _table;

		private readonly IEnumerable<TRow> _enumerableRows;

		private readonly List<Func<TRow, bool>> _listOfPredicates;

		private readonly System.Data.SortExpressionBuilder<TRow> _sortExpression;

		private readonly Func<TRow, TRow> _selector;

		internal override Type ElementType => typeof(TRow);

		internal IEnumerable<TRow> EnumerableRows => _enumerableRows;

		internal override DataTable Table => _table;

		internal EnumerableRowCollection(IEnumerable<TRow> enumerableRows, bool isDataViewable, DataTable table)
		{
			_enumerableRows = enumerableRows;
			if (isDataViewable)
			{
				_table = table;
			}
			_listOfPredicates = new List<Func<TRow, bool>>();
			_sortExpression = new System.Data.SortExpressionBuilder<TRow>();
		}

		internal EnumerableRowCollection(DataTable table)
		{
			_table = table;
			_enumerableRows = table.Rows.Cast<TRow>();
			_listOfPredicates = new List<Func<TRow, bool>>();
			_sortExpression = new System.Data.SortExpressionBuilder<TRow>();
		}

		internal EnumerableRowCollection(EnumerableRowCollection<TRow> source, IEnumerable<TRow> enumerableRows, Func<TRow, TRow> selector)
		{
			_enumerableRows = enumerableRows;
			_selector = selector;
			if (source != null)
			{
				if (source._selector == null)
				{
					_table = source._table;
				}
				_listOfPredicates = new List<Func<TRow, bool>>(source._listOfPredicates);
				_sortExpression = source._sortExpression.Clone();
			}
			else
			{
				_listOfPredicates = new List<Func<TRow, bool>>();
				_sortExpression = new System.Data.SortExpressionBuilder<TRow>();
			}
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public IEnumerator<TRow> GetEnumerator()
		{
			return _enumerableRows.GetEnumerator();
		}

		internal void AddPredicate(Func<TRow, bool> pred)
		{
			_listOfPredicates.Add(pred);
		}

		internal void AddSortExpression<TKey>(Func<TRow, TKey> keySelector, bool isDescending, bool isOrderBy)
		{
			AddSortExpression(keySelector, Comparer<TKey>.Default, isDescending, isOrderBy);
		}

		internal void AddSortExpression<TKey>(Func<TRow, TKey> keySelector, IComparer<TKey> comparer, bool isDescending, bool isOrderBy)
		{
			global::DataSetUtil.CheckArgumentNull(keySelector, "keySelector");
			global::DataSetUtil.CheckArgumentNull(comparer, "comparer");
			_sortExpression.Add((TRow input) => keySelector(input), (object val1, object val2) => ((!isDescending) ? 1 : (-1)) * comparer.Compare((TKey)val1, (TKey)val2), isOrderBy);
		}

		internal EnumerableRowCollection()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	public static class EnumerableRowCollectionExtensions
	{
		public static EnumerableRowCollection<TRow> Where<TRow>(this EnumerableRowCollection<TRow> source, Func<TRow, bool> predicate)
		{
			EnumerableRowCollection<TRow> enumerableRowCollection = new EnumerableRowCollection<TRow>(source, Enumerable.Where(source, predicate), null);
			enumerableRowCollection.AddPredicate(predicate);
			return enumerableRowCollection;
		}

		public static OrderedEnumerableRowCollection<TRow> OrderBy<TRow, TKey>(this EnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector)
		{
			IEnumerable<TRow> enumerableRows = Enumerable.OrderBy(source, keySelector);
			OrderedEnumerableRowCollection<TRow> orderedEnumerableRowCollection = new OrderedEnumerableRowCollection<TRow>(source, enumerableRows);
			orderedEnumerableRowCollection.AddSortExpression(keySelector, isDescending: false, isOrderBy: true);
			return orderedEnumerableRowCollection;
		}

		public static OrderedEnumerableRowCollection<TRow> OrderBy<TRow, TKey>(this EnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer)
		{
			IEnumerable<TRow> enumerableRows = Enumerable.OrderBy(source, keySelector, comparer);
			OrderedEnumerableRowCollection<TRow> orderedEnumerableRowCollection = new OrderedEnumerableRowCollection<TRow>(source, enumerableRows);
			orderedEnumerableRowCollection.AddSortExpression(keySelector, comparer, isDescending: false, isOrderBy: true);
			return orderedEnumerableRowCollection;
		}

		public static OrderedEnumerableRowCollection<TRow> OrderByDescending<TRow, TKey>(this EnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector)
		{
			IEnumerable<TRow> enumerableRows = Enumerable.OrderByDescending(source, keySelector);
			OrderedEnumerableRowCollection<TRow> orderedEnumerableRowCollection = new OrderedEnumerableRowCollection<TRow>(source, enumerableRows);
			orderedEnumerableRowCollection.AddSortExpression(keySelector, isDescending: true, isOrderBy: true);
			return orderedEnumerableRowCollection;
		}

		public static OrderedEnumerableRowCollection<TRow> OrderByDescending<TRow, TKey>(this EnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer)
		{
			IEnumerable<TRow> enumerableRows = Enumerable.OrderByDescending(source, keySelector, comparer);
			OrderedEnumerableRowCollection<TRow> orderedEnumerableRowCollection = new OrderedEnumerableRowCollection<TRow>(source, enumerableRows);
			orderedEnumerableRowCollection.AddSortExpression(keySelector, comparer, isDescending: true, isOrderBy: true);
			return orderedEnumerableRowCollection;
		}

		public static OrderedEnumerableRowCollection<TRow> ThenBy<TRow, TKey>(this OrderedEnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector)
		{
			IEnumerable<TRow> enumerableRows = ((IOrderedEnumerable<TRow>)source.EnumerableRows).ThenBy(keySelector);
			OrderedEnumerableRowCollection<TRow> orderedEnumerableRowCollection = new OrderedEnumerableRowCollection<TRow>(source, enumerableRows);
			orderedEnumerableRowCollection.AddSortExpression(keySelector, isDescending: false, isOrderBy: false);
			return orderedEnumerableRowCollection;
		}

		public static OrderedEnumerableRowCollection<TRow> ThenBy<TRow, TKey>(this OrderedEnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer)
		{
			IEnumerable<TRow> enumerableRows = ((IOrderedEnumerable<TRow>)source.EnumerableRows).ThenBy(keySelector, comparer);
			OrderedEnumerableRowCollection<TRow> orderedEnumerableRowCollection = new OrderedEnumerableRowCollection<TRow>(source, enumerableRows);
			orderedEnumerableRowCollection.AddSortExpression(keySelector, comparer, isDescending: false, isOrderBy: false);
			return orderedEnumerableRowCollection;
		}

		public static OrderedEnumerableRowCollection<TRow> ThenByDescending<TRow, TKey>(this OrderedEnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector)
		{
			IEnumerable<TRow> enumerableRows = ((IOrderedEnumerable<TRow>)source.EnumerableRows).ThenByDescending(keySelector);
			OrderedEnumerableRowCollection<TRow> orderedEnumerableRowCollection = new OrderedEnumerableRowCollection<TRow>(source, enumerableRows);
			orderedEnumerableRowCollection.AddSortExpression(keySelector, isDescending: true, isOrderBy: false);
			return orderedEnumerableRowCollection;
		}

		public static OrderedEnumerableRowCollection<TRow> ThenByDescending<TRow, TKey>(this OrderedEnumerableRowCollection<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer)
		{
			IEnumerable<TRow> enumerableRows = ((IOrderedEnumerable<TRow>)source.EnumerableRows).ThenByDescending(keySelector, comparer);
			OrderedEnumerableRowCollection<TRow> orderedEnumerableRowCollection = new OrderedEnumerableRowCollection<TRow>(source, enumerableRows);
			orderedEnumerableRowCollection.AddSortExpression(keySelector, comparer, isDescending: true, isOrderBy: false);
			return orderedEnumerableRowCollection;
		}

		public static EnumerableRowCollection<S> Select<TRow, S>(this EnumerableRowCollection<TRow> source, Func<TRow, S> selector)
		{
			IEnumerable<S> enumerableRows = Enumerable.Select(source, selector);
			return new EnumerableRowCollection<S>(source as EnumerableRowCollection<S>, enumerableRows, selector as Func<S, S>);
		}

		public static EnumerableRowCollection<TResult> Cast<TResult>(this EnumerableRowCollection source)
		{
			if (source != null && source.ElementType.Equals(typeof(TResult)))
			{
				return (EnumerableRowCollection<TResult>)source;
			}
			return new EnumerableRowCollection<TResult>(Enumerable.Cast<TResult>(source), typeof(TResult).IsAssignableFrom(source.ElementType) && typeof(DataRow).IsAssignableFrom(typeof(TResult)), source.Table);
		}
	}
	public sealed class OrderedEnumerableRowCollection<TRow> : EnumerableRowCollection<TRow>
	{
		internal OrderedEnumerableRowCollection(EnumerableRowCollection<TRow> enumerableTable, IEnumerable<TRow> enumerableRows)
			: base(enumerableTable, enumerableRows, (Func<TRow, TRow>)null)
		{
		}

		internal OrderedEnumerableRowCollection()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	internal class SortExpressionBuilder<T> : IComparer<List<object>>
	{
		private LinkedList<Func<T, object>> _selectors = new LinkedList<Func<T, object>>();

		private LinkedList<Comparison<object>> _comparers = new LinkedList<Comparison<object>>();

		private LinkedListNode<Func<T, object>> _currentSelector;

		private LinkedListNode<Comparison<object>> _currentComparer;

		internal int Count => _selectors.Count;

		internal void Add(Func<T, object> keySelector, Comparison<object> compare, bool isOrderBy)
		{
			if (isOrderBy)
			{
				_currentSelector = _selectors.AddFirst(keySelector);
				_currentComparer = _comparers.AddFirst(compare);
			}
			else
			{
				_currentSelector = _selectors.AddAfter(_currentSelector, keySelector);
				_currentComparer = _comparers.AddAfter(_currentComparer, compare);
			}
		}

		public List<object> Select(T row)
		{
			List<object> list = new List<object>();
			foreach (Func<T, object> selector in _selectors)
			{
				list.Add(selector(row));
			}
			return list;
		}

		public int Compare(List<object> a, List<object> b)
		{
			int num = 0;
			foreach (Comparison<object> comparer in _comparers)
			{
				int num2 = comparer(a[num], b[num]);
				if (num2 != 0)
				{
					return num2;
				}
				num++;
			}
			return 0;
		}

		internal System.Data.SortExpressionBuilder<T> Clone()
		{
			System.Data.SortExpressionBuilder<T> sortExpressionBuilder = new System.Data.SortExpressionBuilder<T>();
			foreach (Func<T, object> selector in _selectors)
			{
				if (selector == _currentSelector.Value)
				{
					sortExpressionBuilder._currentSelector = sortExpressionBuilder._selectors.AddLast(selector);
				}
				else
				{
					sortExpressionBuilder._selectors.AddLast(selector);
				}
			}
			foreach (Comparison<object> comparer in _comparers)
			{
				if (comparer == _currentComparer.Value)
				{
					sortExpressionBuilder._currentComparer = sortExpressionBuilder._comparers.AddLast(comparer);
				}
				else
				{
					sortExpressionBuilder._comparers.AddLast(comparer);
				}
			}
			return sortExpressionBuilder;
		}

		internal System.Data.SortExpressionBuilder<TResult> CloneCast<TResult>()
		{
			System.Data.SortExpressionBuilder<TResult> sortExpressionBuilder = new System.Data.SortExpressionBuilder<TResult>();
			foreach (Func<T, object> selector in _selectors)
			{
				if (selector == _currentSelector.Value)
				{
					sortExpressionBuilder._currentSelector = sortExpressionBuilder._selectors.AddLast((TResult r) => selector((T)(object)r));
				}
				else
				{
					sortExpressionBuilder._selectors.AddLast((TResult r) => selector((T)(object)r));
				}
			}
			foreach (Comparison<object> comparer in _comparers)
			{
				if (comparer == _currentComparer.Value)
				{
					sortExpressionBuilder._currentComparer = sortExpressionBuilder._comparers.AddLast(comparer);
				}
				else
				{
					sortExpressionBuilder._comparers.AddLast(comparer);
				}
			}
			return sortExpressionBuilder;
		}
	}
	[Serializable]
	public abstract class TypedTableBase<T> : DataTable, IEnumerable<T>, IEnumerable where T : DataRow
	{
		protected TypedTableBase()
		{
		}

		protected TypedTableBase(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public IEnumerator<T> GetEnumerator()
		{
			return base.Rows.Cast<T>().GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		public EnumerableRowCollection<TResult> Cast<TResult>()
		{
			return new EnumerableRowCollection<T>(this).Cast<TResult>();
		}
	}
	public static class TypedTableBaseExtensions
	{
		public static EnumerableRowCollection<TRow> Where<TRow>(this TypedTableBase<TRow> source, Func<TRow, bool> predicate) where TRow : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return new EnumerableRowCollection<TRow>(source).Where(predicate);
		}

		public static OrderedEnumerableRowCollection<TRow> OrderBy<TRow, TKey>(this TypedTableBase<TRow> source, Func<TRow, TKey> keySelector) where TRow : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return new EnumerableRowCollection<TRow>(source).OrderBy(keySelector);
		}

		public static OrderedEnumerableRowCollection<TRow> OrderBy<TRow, TKey>(this TypedTableBase<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer) where TRow : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return new EnumerableRowCollection<TRow>(source).OrderBy(keySelector, comparer);
		}

		public static OrderedEnumerableRowCollection<TRow> OrderByDescending<TRow, TKey>(this TypedTableBase<TRow> source, Func<TRow, TKey> keySelector) where TRow : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return new EnumerableRowCollection<TRow>(source).OrderByDescending(keySelector);
		}

		public static OrderedEnumerableRowCollection<TRow> OrderByDescending<TRow, TKey>(this TypedTableBase<TRow> source, Func<TRow, TKey> keySelector, IComparer<TKey> comparer) where TRow : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return new EnumerableRowCollection<TRow>(source).OrderByDescending(keySelector, comparer);
		}

		public static EnumerableRowCollection<S> Select<TRow, S>(this TypedTableBase<TRow> source, Func<TRow, S> selector) where TRow : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return new EnumerableRowCollection<TRow>(source).Select(selector);
		}

		public static EnumerableRowCollection<TRow> AsEnumerable<TRow>(this TypedTableBase<TRow> source) where TRow : DataRow
		{
			global::DataSetUtil.CheckArgumentNull(source, "source");
			return new EnumerableRowCollection<TRow>(source);
		}

		public static TRow ElementAtOrDefault<TRow>(this TypedTableBase<TRow> source, int index) where TRow : DataRow
		{
			if (index >= 0 && index < source.Rows.Count)
			{
				return (TRow)source.Rows[index];
			}
			return null;
		}
	}
}
namespace Unity
{
	internal sealed class ThrowStub : ObjectDisposedException
	{
		public static void ThrowNotSupportedException()
		{
			throw new PlatformNotSupportedException();
		}
	}
}

BepInEx/core/System.Data.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.Odbc;
using System.Data.OleDb;
using System.Data.ProviderBase;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlClient.SNI;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Drawing;
using System.Dynamic;
using System.EnterpriseServices;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.Serialization.Advanced;
using System.Xml.XPath;
using Microsoft.CodeAnalysis;
using Microsoft.SqlServer.Server;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using Unity;

[assembly: InternalsVisibleTo("System.Design, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: AssemblyDescription("System.Data.dll")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyDefaultAlias("System.Data.dll")]
[assembly: InternalsVisibleTo("System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyTitle("System.Data.dll")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyDelaySign(true)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: ComVisible(false)]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class 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;
		}
	}
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	[CompilerGenerated]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
}
internal static class Interop
{
	internal static class Odbc
	{
		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLAllocHandle(ODBC32.SQL_HANDLE HandleType, IntPtr InputHandle, out IntPtr OutputHandle);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLAllocHandle(ODBC32.SQL_HANDLE HandleType, OdbcHandle InputHandle, out IntPtr OutputHandle);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLBindCol(OdbcStatementHandle StatementHandle, ushort ColumnNumber, ODBC32.SQL_C TargetType, HandleRef TargetValue, IntPtr BufferLength, IntPtr StrLen_or_Ind);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLBindCol(OdbcStatementHandle StatementHandle, ushort ColumnNumber, ODBC32.SQL_C TargetType, IntPtr TargetValue, IntPtr BufferLength, IntPtr StrLen_or_Ind);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLBindParameter(OdbcStatementHandle StatementHandle, ushort ParameterNumber, short ParamDirection, ODBC32.SQL_C SQLCType, short SQLType, IntPtr cbColDef, IntPtr ibScale, HandleRef rgbValue, IntPtr BufferLength, HandleRef StrLen_or_Ind);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLCancel(OdbcStatementHandle StatementHandle);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLCloseCursor(OdbcStatementHandle StatementHandle);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLColAttributeW(OdbcStatementHandle StatementHandle, short ColumnNumber, short FieldIdentifier, CNativeBuffer CharacterAttribute, short BufferLength, out short StringLength, out IntPtr NumericAttribute);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLColumnsW(OdbcStatementHandle StatementHandle, string CatalogName, short NameLen1, string SchemaName, short NameLen2, string TableName, short NameLen3, string ColumnName, short NameLen4);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLDisconnect(IntPtr ConnectionHandle);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLDriverConnectW(OdbcConnectionHandle hdbc, IntPtr hwnd, string connectionstring, short cbConnectionstring, IntPtr connectionstringout, short cbConnectionstringoutMax, out short cbConnectionstringout, short fDriverCompletion);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLEndTran(ODBC32.SQL_HANDLE HandleType, IntPtr Handle, short CompletionType);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLExecDirectW(OdbcStatementHandle StatementHandle, string StatementText, int TextLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLExecute(OdbcStatementHandle StatementHandle);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLFetch(OdbcStatementHandle StatementHandle);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLFreeHandle(ODBC32.SQL_HANDLE HandleType, IntPtr StatementHandle);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLFreeStmt(OdbcStatementHandle StatementHandle, ODBC32.STMT Option);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLGetConnectAttrW(OdbcConnectionHandle ConnectionHandle, ODBC32.SQL_ATTR Attribute, byte[] Value, int BufferLength, out int StringLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLGetData(OdbcStatementHandle StatementHandle, ushort ColumnNumber, ODBC32.SQL_C TargetType, CNativeBuffer TargetValue, IntPtr BufferLength, out IntPtr StrLen_or_Ind);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLGetDescFieldW(OdbcDescriptorHandle StatementHandle, short RecNumber, ODBC32.SQL_DESC FieldIdentifier, CNativeBuffer ValuePointer, int BufferLength, out int StringLength);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLGetDiagRecW(ODBC32.SQL_HANDLE HandleType, OdbcHandle Handle, short RecNumber, StringBuilder rchState, out int NativeError, StringBuilder MessageText, short BufferLength, out short TextLength);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLGetDiagFieldW(ODBC32.SQL_HANDLE HandleType, OdbcHandle Handle, short RecNumber, short DiagIdentifier, StringBuilder rchState, short BufferLength, out short StringLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLGetFunctions(OdbcConnectionHandle hdbc, ODBC32.SQL_API fFunction, out short pfExists);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLGetInfoW(OdbcConnectionHandle hdbc, ODBC32.SQL_INFO fInfoType, byte[] rgbInfoValue, short cbInfoValueMax, out short pcbInfoValue);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLGetInfoW(OdbcConnectionHandle hdbc, ODBC32.SQL_INFO fInfoType, byte[] rgbInfoValue, short cbInfoValueMax, IntPtr pcbInfoValue);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLGetStmtAttrW(OdbcStatementHandle StatementHandle, ODBC32.SQL_ATTR Attribute, out IntPtr Value, int BufferLength, out int StringLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLGetTypeInfo(OdbcStatementHandle StatementHandle, short fSqlType);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLMoreResults(OdbcStatementHandle StatementHandle);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLNumResultCols(OdbcStatementHandle StatementHandle, out short ColumnCount);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLPrepareW(OdbcStatementHandle StatementHandle, string StatementText, int TextLength);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLPrimaryKeysW(OdbcStatementHandle StatementHandle, string CatalogName, short NameLen1, string SchemaName, short NameLen2, string TableName, short NameLen3);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLProcedureColumnsW(OdbcStatementHandle StatementHandle, string CatalogName, short NameLen1, string SchemaName, short NameLen2, string ProcName, short NameLen3, string ColumnName, short NameLen4);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLProceduresW(OdbcStatementHandle StatementHandle, string CatalogName, short NameLen1, string SchemaName, short NameLen2, string ProcName, short NameLen3);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLRowCount(OdbcStatementHandle StatementHandle, out IntPtr RowCount);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLSetConnectAttrW(OdbcConnectionHandle ConnectionHandle, ODBC32.SQL_ATTR Attribute, IDtcTransaction Value, int StringLength);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLSetConnectAttrW(OdbcConnectionHandle ConnectionHandle, ODBC32.SQL_ATTR Attribute, string Value, int StringLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLSetConnectAttrW(OdbcConnectionHandle ConnectionHandle, ODBC32.SQL_ATTR Attribute, IntPtr Value, int StringLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLSetConnectAttrW(IntPtr ConnectionHandle, ODBC32.SQL_ATTR Attribute, IntPtr Value, int StringLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLSetDescFieldW(OdbcDescriptorHandle StatementHandle, short ColumnNumber, ODBC32.SQL_DESC FieldIdentifier, HandleRef CharacterAttribute, int BufferLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLSetDescFieldW(OdbcDescriptorHandle StatementHandle, short ColumnNumber, ODBC32.SQL_DESC FieldIdentifier, IntPtr CharacterAttribute, int BufferLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLSetEnvAttr(OdbcEnvironmentHandle EnvironmentHandle, ODBC32.SQL_ATTR Attribute, IntPtr Value, ODBC32.SQL_IS StringLength);

		[DllImport("odbc32.dll")]
		internal static extern ODBC32.RetCode SQLSetStmtAttrW(OdbcStatementHandle StatementHandle, int Attribute, IntPtr Value, int StringLength);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLSpecialColumnsW(OdbcStatementHandle StatementHandle, ODBC32.SQL_SPECIALCOLS IdentifierType, string CatalogName, short NameLen1, string SchemaName, short NameLen2, string TableName, short NameLen3, ODBC32.SQL_SCOPE Scope, ODBC32.SQL_NULLABILITY Nullable);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLStatisticsW(OdbcStatementHandle StatementHandle, string CatalogName, short NameLen1, string SchemaName, short NameLen2, string TableName, short NameLen3, short Unique, short Reserved);

		[DllImport("odbc32.dll", CharSet = CharSet.Unicode)]
		internal static extern ODBC32.RetCode SQLTablesW(OdbcStatementHandle StatementHandle, string CatalogName, short NameLen1, string SchemaName, short NameLen2, string TableName, short NameLen3, string TableType, short NameLen4);
	}

	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 Kernel32
	{
		public const int LOAD_LIBRARY_AS_DATAFILE = 2;

		public const int LOAD_LIBRARY_SEARCH_SYSTEM32 = 2048;

		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		public static extern bool FreeLibrary([In] IntPtr hModule);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Ansi)]
		public static extern IntPtr GetProcAddress(SafeLibraryHandle hModule, string lpProcName);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Ansi)]
		public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		public static extern SafeLibraryHandle LoadLibraryExW([In] string lpwLibFileName, [In] IntPtr hFile, [In] uint dwFlags);
	}
}
internal class SqlDependencyProcessDispatcher : MarshalByRefObject
{
	private class SqlConnectionContainer
	{
		private SqlConnection _con;

		private SqlCommand _com;

		private SqlParameter _conversationGuidParam;

		private SqlParameter _timeoutParam;

		private SqlConnectionContainerHashHelper _hashHelper;

		private string _queue;

		private string _receiveQuery;

		private string _beginConversationQuery;

		private string _endConversationQuery;

		private string _concatQuery;

		private readonly int _defaultWaitforTimeout = 60000;

		private string _escapedQueueName;

		private string _sprocName;

		private string _dialogHandle;

		private string _cachedServer;

		private string _cachedDatabase;

		private volatile bool _errorState;

		private volatile bool _stop;

		private volatile bool _stopped;

		private volatile bool _serviceQueueCreated;

		private int _startCount;

		private Timer _retryTimer;

		private Dictionary<string, int> _appDomainKeyHash;

		internal string Database
		{
			get
			{
				if (_cachedDatabase == null)
				{
					_cachedDatabase = _con.Database;
				}
				return _cachedDatabase;
			}
		}

		internal SqlConnectionContainerHashHelper HashHelper => _hashHelper;

		internal bool InErrorState => _errorState;

		internal string Queue => _queue;

		internal string Server => _cachedServer;

		internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults)
		{
			bool flag = false;
			try
			{
				_hashHelper = hashHelper;
				string text = null;
				if (useDefaults)
				{
					text = Guid.NewGuid().ToString();
					_queue = "SqlQueryNotificationService-" + text;
					_hashHelper.ConnectionStringBuilder.ApplicationName = _queue;
				}
				else
				{
					_queue = _hashHelper.Queue;
				}
				_con = new SqlConnection(_hashHelper.ConnectionStringBuilder.ConnectionString);
				_ = (SqlConnectionString)_con.ConnectionOptions;
				_con.Open();
				_cachedServer = _con.DataSource;
				_escapedQueueName = SqlConnection.FixupDatabaseTransactionName(_queue);
				_appDomainKeyHash = new Dictionary<string, int>();
				_com = new SqlCommand
				{
					Connection = _con,
					CommandText = "select is_broker_enabled from sys.databases where database_id=db_id()"
				};
				if (!(bool)_com.ExecuteScalar())
				{
					throw SQL.SqlDependencyDatabaseBrokerDisabled();
				}
				_conversationGuidParam = new SqlParameter("@p1", SqlDbType.UniqueIdentifier);
				_timeoutParam = new SqlParameter("@p2", SqlDbType.Int)
				{
					Value = 0
				};
				_com.Parameters.Add(_timeoutParam);
				flag = true;
				_receiveQuery = "WAITFOR(RECEIVE TOP (1) message_type_name, conversation_handle, cast(message_body AS XML) as message_body from " + _escapedQueueName + "), TIMEOUT @p2;";
				if (useDefaults)
				{
					_sprocName = SqlConnection.FixupDatabaseTransactionName("SqlQueryNotificationStoredProcedure-" + text);
					CreateQueueAndService(restart: false);
				}
				else
				{
					_com.CommandText = _receiveQuery;
					_endConversationQuery = "END CONVERSATION @p1; ";
					_concatQuery = _endConversationQuery + _receiveQuery;
				}
				IncrementStartCount(appDomainKey, out var _);
				SynchronouslyQueryServiceBrokerQueue();
				_timeoutParam.Value = _defaultWaitforTimeout;
				AsynchronouslyQueryServiceBrokerQueue();
			}
			catch (Exception e)
			{
				if (!ADP.IsCatchableExceptionType(e))
				{
					throw;
				}
				ADP.TraceExceptionWithoutRethrow(e);
				if (flag)
				{
					TearDownAndDispose();
				}
				else
				{
					if (_com != null)
					{
						_com.Dispose();
						_com = null;
					}
					if (_con != null)
					{
						_con.Dispose();
						_con = null;
					}
				}
				throw;
			}
		}

		internal bool AppDomainUnload(string appDomainKey)
		{
			lock (_appDomainKeyHash)
			{
				if (_appDomainKeyHash.ContainsKey(appDomainKey))
				{
					int num = _appDomainKeyHash[appDomainKey];
					bool appDomainStop = false;
					while (num > 0)
					{
						Stop(appDomainKey, out appDomainStop);
						num--;
					}
				}
			}
			return _stopped;
		}

		private void AsynchronouslyQueryServiceBrokerQueue()
		{
			AsyncCallback callback = AsyncResultCallback;
			_com.BeginExecuteReader(CommandBehavior.Default, callback, null);
		}

		private void AsyncResultCallback(IAsyncResult asyncResult)
		{
			try
			{
				using (SqlDataReader reader = _com.EndExecuteReader(asyncResult))
				{
					ProcessNotificationResults(reader);
				}
				if (!_stop)
				{
					AsynchronouslyQueryServiceBrokerQueue();
				}
				else
				{
					TearDownAndDispose();
				}
			}
			catch (Exception e)
			{
				if (!ADP.IsCatchableExceptionType(e))
				{
					_errorState = true;
					throw;
				}
				if (!_stop)
				{
					ADP.TraceExceptionWithoutRethrow(e);
				}
				if (_stop)
				{
					TearDownAndDispose();
					return;
				}
				_errorState = true;
				Restart(null);
			}
		}

		private void CreateQueueAndService(bool restart)
		{
			SqlCommand sqlCommand = new SqlCommand
			{
				Connection = _con
			};
			SqlTransaction sqlTransaction = null;
			try
			{
				sqlTransaction = (sqlCommand.Transaction = _con.BeginTransaction());
				string text = SqlServerEscapeHelper.MakeStringLiteral(_queue);
				sqlCommand.CommandText = "CREATE PROCEDURE " + _sprocName + " AS BEGIN BEGIN TRANSACTION; RECEIVE TOP(0) conversation_handle FROM " + _escapedQueueName + "; IF (SELECT COUNT(*) FROM " + _escapedQueueName + " WHERE message_type_name = 'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer') > 0 BEGIN if ((SELECT COUNT(*) FROM sys.services WHERE name = " + text + ") > 0)   DROP SERVICE " + _escapedQueueName + "; if (OBJECT_ID(" + text + ", 'SQ') IS NOT NULL)   DROP QUEUE " + _escapedQueueName + "; DROP PROCEDURE " + _sprocName + "; END COMMIT TRANSACTION; END";
				if (!restart)
				{
					sqlCommand.ExecuteNonQuery();
				}
				else
				{
					try
					{
						sqlCommand.ExecuteNonQuery();
					}
					catch (Exception e)
					{
						if (!ADP.IsCatchableExceptionType(e))
						{
							throw;
						}
						ADP.TraceExceptionWithoutRethrow(e);
						try
						{
							if (sqlTransaction != null)
							{
								sqlTransaction.Rollback();
								sqlTransaction = null;
							}
						}
						catch (Exception e2)
						{
							if (!ADP.IsCatchableExceptionType(e2))
							{
								throw;
							}
							ADP.TraceExceptionWithoutRethrow(e2);
						}
					}
					if (sqlTransaction == null)
					{
						sqlTransaction = (sqlCommand.Transaction = _con.BeginTransaction());
					}
				}
				sqlCommand.CommandText = "IF OBJECT_ID(" + text + ", 'SQ') IS NULL BEGIN CREATE QUEUE " + _escapedQueueName + " WITH ACTIVATION (PROCEDURE_NAME=" + _sprocName + ", MAX_QUEUE_READERS=1, EXECUTE AS OWNER); END; IF (SELECT COUNT(*) FROM sys.services WHERE NAME=" + text + ") = 0 BEGIN CREATE SERVICE " + _escapedQueueName + " ON QUEUE " + _escapedQueueName + " ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]); IF (SELECT COUNT(*) FROM sys.database_principals WHERE name='sql_dependency_subscriber' AND type='R') <> 0 BEGIN GRANT SEND ON SERVICE::" + _escapedQueueName + " TO sql_dependency_subscriber; END;  END; BEGIN DIALOG @dialog_handle FROM SERVICE " + _escapedQueueName + " TO SERVICE " + text;
				SqlParameter sqlParameter = new SqlParameter
				{
					ParameterName = "@dialog_handle",
					DbType = DbType.Guid,
					Direction = ParameterDirection.Output
				};
				sqlCommand.Parameters.Add(sqlParameter);
				sqlCommand.ExecuteNonQuery();
				_dialogHandle = ((Guid)sqlParameter.Value).ToString();
				_beginConversationQuery = "BEGIN CONVERSATION TIMER ('" + _dialogHandle + "') TIMEOUT = 120; " + _receiveQuery;
				_com.CommandText = _beginConversationQuery;
				_endConversationQuery = "END CONVERSATION @p1; ";
				_concatQuery = _endConversationQuery + _com.CommandText;
				sqlTransaction.Commit();
				sqlTransaction = null;
				_serviceQueueCreated = true;
			}
			finally
			{
				if (sqlTransaction != null)
				{
					try
					{
						sqlTransaction.Rollback();
						sqlTransaction = null;
					}
					catch (Exception e3)
					{
						if (!ADP.IsCatchableExceptionType(e3))
						{
							throw;
						}
						ADP.TraceExceptionWithoutRethrow(e3);
					}
				}
			}
		}

		internal void IncrementStartCount(string appDomainKey, out bool appDomainStart)
		{
			appDomainStart = false;
			Interlocked.Increment(ref _startCount);
			lock (_appDomainKeyHash)
			{
				if (_appDomainKeyHash.ContainsKey(appDomainKey))
				{
					_appDomainKeyHash[appDomainKey] += 1;
					return;
				}
				_appDomainKeyHash[appDomainKey] = 1;
				appDomainStart = true;
			}
		}

		private void ProcessNotificationResults(SqlDataReader reader)
		{
			Guid guid = Guid.Empty;
			try
			{
				if (_stop)
				{
					return;
				}
				while (reader.Read())
				{
					string @string = reader.GetString(0);
					guid = reader.GetGuid(1);
					if (string.Compare(@string, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase) == 0)
					{
						SqlXml sqlXml = reader.GetSqlXml(2);
						if (sqlXml == null)
						{
							continue;
						}
						SqlNotification sqlNotification = SqlNotificationParser.ProcessMessage(sqlXml);
						if (sqlNotification == null)
						{
							continue;
						}
						string key = sqlNotification.Key;
						int num = key.IndexOf(';');
						if (num < 0)
						{
							continue;
						}
						string key2 = key.Substring(0, num);
						SqlDependencyPerAppDomainDispatcher sqlDependencyPerAppDomainDispatcher;
						lock (s_staticInstance._sqlDependencyPerAppDomainDispatchers)
						{
							sqlDependencyPerAppDomainDispatcher = s_staticInstance._sqlDependencyPerAppDomainDispatchers[key2];
						}
						if (sqlDependencyPerAppDomainDispatcher == null)
						{
							continue;
						}
						try
						{
							sqlDependencyPerAppDomainDispatcher.InvalidateCommandID(sqlNotification);
						}
						catch (Exception e)
						{
							if (!ADP.IsCatchableExceptionType(e))
							{
								throw;
							}
							ADP.TraceExceptionWithoutRethrow(e);
						}
					}
					else
					{
						guid = Guid.Empty;
					}
				}
			}
			finally
			{
				if (guid == Guid.Empty)
				{
					_com.CommandText = _beginConversationQuery ?? _receiveQuery;
					if (_com.Parameters.Count > 1)
					{
						_com.Parameters.Remove(_conversationGuidParam);
					}
				}
				else
				{
					_com.CommandText = _concatQuery;
					_conversationGuidParam.Value = guid;
					if (_com.Parameters.Count == 1)
					{
						_com.Parameters.Add(_conversationGuidParam);
					}
				}
			}
		}

		private void Restart(object unused)
		{
			try
			{
				lock (this)
				{
					if (!_stop)
					{
						try
						{
							_con.Close();
						}
						catch (Exception e)
						{
							if (!ADP.IsCatchableExceptionType(e))
							{
								throw;
							}
							ADP.TraceExceptionWithoutRethrow(e);
						}
					}
				}
				lock (this)
				{
					if (!_stop)
					{
						_con.Open();
					}
				}
				lock (this)
				{
					if (!_stop && _serviceQueueCreated)
					{
						bool flag = false;
						try
						{
							CreateQueueAndService(restart: true);
						}
						catch (Exception e2)
						{
							if (!ADP.IsCatchableExceptionType(e2))
							{
								throw;
							}
							ADP.TraceExceptionWithoutRethrow(e2);
							flag = true;
						}
						if (flag)
						{
							s_staticInstance.Invalidate(Server, new SqlNotification(SqlNotificationInfo.Error, SqlNotificationSource.Client, SqlNotificationType.Change, null));
						}
					}
				}
				lock (this)
				{
					if (!_stop)
					{
						_timeoutParam.Value = 0;
						SynchronouslyQueryServiceBrokerQueue();
						_timeoutParam.Value = _defaultWaitforTimeout;
						AsynchronouslyQueryServiceBrokerQueue();
						_errorState = false;
						Timer retryTimer = _retryTimer;
						if (retryTimer != null)
						{
							_retryTimer = null;
							retryTimer.Dispose();
						}
					}
				}
				if (_stop)
				{
					TearDownAndDispose();
				}
			}
			catch (Exception e3)
			{
				if (!ADP.IsCatchableExceptionType(e3))
				{
					throw;
				}
				ADP.TraceExceptionWithoutRethrow(e3);
				try
				{
					s_staticInstance.Invalidate(Server, new SqlNotification(SqlNotificationInfo.Error, SqlNotificationSource.Client, SqlNotificationType.Change, null));
				}
				catch (Exception e4)
				{
					if (!ADP.IsCatchableExceptionType(e4))
					{
						throw;
					}
					ADP.TraceExceptionWithoutRethrow(e4);
				}
				try
				{
					_con.Close();
				}
				catch (Exception e5)
				{
					if (!ADP.IsCatchableExceptionType(e5))
					{
						throw;
					}
					ADP.TraceExceptionWithoutRethrow(e5);
				}
				if (!_stop)
				{
					_retryTimer = new Timer(Restart, null, _defaultWaitforTimeout, -1);
				}
			}
		}

		internal bool Stop(string appDomainKey, out bool appDomainStop)
		{
			appDomainStop = false;
			if (appDomainKey != null)
			{
				lock (_appDomainKeyHash)
				{
					if (_appDomainKeyHash.ContainsKey(appDomainKey))
					{
						int num = _appDomainKeyHash[appDomainKey];
						if (num > 0)
						{
							_appDomainKeyHash[appDomainKey] = num - 1;
						}
						if (1 == num)
						{
							_appDomainKeyHash.Remove(appDomainKey);
							appDomainStop = true;
						}
					}
				}
			}
			if (Interlocked.Decrement(ref _startCount) == 0)
			{
				lock (this)
				{
					try
					{
						_com.Cancel();
					}
					catch (Exception e)
					{
						if (!ADP.IsCatchableExceptionType(e))
						{
							throw;
						}
						ADP.TraceExceptionWithoutRethrow(e);
					}
					_stop = true;
				}
				Stopwatch stopwatch = Stopwatch.StartNew();
				while (true)
				{
					lock (this)
					{
						if (!_stopped)
						{
							if (!_errorState && stopwatch.Elapsed.Seconds < 30)
							{
								goto IL_0127;
							}
							Timer retryTimer = _retryTimer;
							_retryTimer = null;
							retryTimer?.Dispose();
							TearDownAndDispose();
						}
					}
					break;
					IL_0127:
					Thread.Sleep(1);
				}
			}
			return _stopped;
		}

		private void SynchronouslyQueryServiceBrokerQueue()
		{
			using SqlDataReader reader = _com.ExecuteReader();
			ProcessNotificationResults(reader);
		}

		private void TearDownAndDispose()
		{
			lock (this)
			{
				try
				{
					if (_con.State == ConnectionState.Closed || ConnectionState.Broken == _con.State)
					{
						return;
					}
					if (_com.Parameters.Count > 1)
					{
						try
						{
							_com.CommandText = _endConversationQuery;
							_com.Parameters.Remove(_timeoutParam);
							_com.ExecuteNonQuery();
						}
						catch (Exception e)
						{
							if (!ADP.IsCatchableExceptionType(e))
							{
								throw;
							}
							ADP.TraceExceptionWithoutRethrow(e);
						}
					}
					if (!_serviceQueueCreated || _errorState)
					{
						return;
					}
					_com.CommandText = "BEGIN TRANSACTION; DROP SERVICE " + _escapedQueueName + "; DROP QUEUE " + _escapedQueueName + "; DROP PROCEDURE " + _sprocName + "; COMMIT TRANSACTION;";
					try
					{
						_com.ExecuteNonQuery();
					}
					catch (Exception e2)
					{
						if (!ADP.IsCatchableExceptionType(e2))
						{
							throw;
						}
						ADP.TraceExceptionWithoutRethrow(e2);
					}
				}
				finally
				{
					_stopped = true;
					_con.Dispose();
				}
			}
		}
	}

	private class SqlNotificationParser
	{
		[Flags]
		private enum MessageAttributes
		{
			None = 0,
			Type = 1,
			Source = 2,
			Info = 4,
			All = 7
		}

		private const string RootNode = "QueryNotification";

		private const string MessageNode = "Message";

		private const string InfoAttribute = "info";

		private const string SourceAttribute = "source";

		private const string TypeAttribute = "type";

		internal static SqlNotification ProcessMessage(SqlXml xmlMessage)
		{
			using XmlReader xmlReader = xmlMessage.CreateReader();
			_ = string.Empty;
			MessageAttributes messageAttributes = MessageAttributes.None;
			SqlNotificationType type = SqlNotificationType.Unknown;
			SqlNotificationInfo info = SqlNotificationInfo.Unknown;
			SqlNotificationSource source = SqlNotificationSource.Unknown;
			string key = string.Empty;
			xmlReader.Read();
			if (XmlNodeType.Element == xmlReader.NodeType && "QueryNotification" == xmlReader.LocalName && 3 <= xmlReader.AttributeCount)
			{
				while (MessageAttributes.All != messageAttributes && xmlReader.MoveToNextAttribute())
				{
					try
					{
						switch (xmlReader.LocalName)
						{
						case "type":
							try
							{
								SqlNotificationType sqlNotificationType = (SqlNotificationType)Enum.Parse(typeof(SqlNotificationType), xmlReader.Value, ignoreCase: true);
								if (Enum.IsDefined(typeof(SqlNotificationType), sqlNotificationType))
								{
									type = sqlNotificationType;
								}
							}
							catch (Exception e2)
							{
								if (!ADP.IsCatchableExceptionType(e2))
								{
									throw;
								}
								ADP.TraceExceptionWithoutRethrow(e2);
							}
							messageAttributes |= MessageAttributes.Type;
							break;
						case "source":
							try
							{
								SqlNotificationSource sqlNotificationSource = (SqlNotificationSource)Enum.Parse(typeof(SqlNotificationSource), xmlReader.Value, ignoreCase: true);
								if (Enum.IsDefined(typeof(SqlNotificationSource), sqlNotificationSource))
								{
									source = sqlNotificationSource;
								}
							}
							catch (Exception e3)
							{
								if (!ADP.IsCatchableExceptionType(e3))
								{
									throw;
								}
								ADP.TraceExceptionWithoutRethrow(e3);
							}
							messageAttributes |= MessageAttributes.Source;
							break;
						case "info":
							try
							{
								string value = xmlReader.Value;
								switch (value)
								{
								case "set options":
									info = SqlNotificationInfo.Options;
									break;
								case "previous invalid":
									info = SqlNotificationInfo.PreviousFire;
									break;
								case "query template limit":
									info = SqlNotificationInfo.TemplateLimit;
									break;
								default:
								{
									SqlNotificationInfo sqlNotificationInfo = (SqlNotificationInfo)Enum.Parse(typeof(SqlNotificationInfo), value, ignoreCase: true);
									if (Enum.IsDefined(typeof(SqlNotificationInfo), sqlNotificationInfo))
									{
										info = sqlNotificationInfo;
									}
									break;
								}
								}
							}
							catch (Exception e)
							{
								if (!ADP.IsCatchableExceptionType(e))
								{
									throw;
								}
								ADP.TraceExceptionWithoutRethrow(e);
							}
							messageAttributes |= MessageAttributes.Info;
							break;
						}
					}
					catch (ArgumentException e4)
					{
						ADP.TraceExceptionWithoutRethrow(e4);
						return null;
					}
				}
				if (MessageAttributes.All != messageAttributes)
				{
					return null;
				}
				if (!xmlReader.Read())
				{
					return null;
				}
				if (XmlNodeType.Element != xmlReader.NodeType || string.Compare(xmlReader.LocalName, "Message", StringComparison.OrdinalIgnoreCase) != 0)
				{
					return null;
				}
				if (!xmlReader.Read())
				{
					return null;
				}
				if (xmlReader.NodeType != XmlNodeType.Text)
				{
					return null;
				}
				using (XmlTextReader xmlTextReader = new XmlTextReader(xmlReader.Value, XmlNodeType.Element, null))
				{
					if (!xmlTextReader.Read())
					{
						return null;
					}
					if (xmlTextReader.NodeType != XmlNodeType.Text)
					{
						return null;
					}
					key = xmlTextReader.Value;
					xmlTextReader.Close();
				}
				return new SqlNotification(info, source, type, key);
			}
			return null;
		}
	}

	private class SqlConnectionContainerHashHelper
	{
		private DbConnectionPoolIdentity _identity;

		private string _connectionString;

		private string _queue;

		private SqlConnectionStringBuilder _connectionStringBuilder;

		internal SqlConnectionStringBuilder ConnectionStringBuilder => _connectionStringBuilder;

		internal DbConnectionPoolIdentity Identity => _identity;

		internal string Queue => _queue;

		internal SqlConnectionContainerHashHelper(DbConnectionPoolIdentity identity, string connectionString, string queue, SqlConnectionStringBuilder connectionStringBuilder)
		{
			_identity = identity;
			_connectionString = connectionString;
			_queue = queue;
			_connectionStringBuilder = connectionStringBuilder;
		}

		public override bool Equals(object value)
		{
			SqlConnectionContainerHashHelper sqlConnectionContainerHashHelper = (SqlConnectionContainerHashHelper)value;
			bool flag = false;
			if (sqlConnectionContainerHashHelper == null)
			{
				return false;
			}
			if (this == sqlConnectionContainerHashHelper)
			{
				return true;
			}
			if ((_identity != null && sqlConnectionContainerHashHelper._identity == null) || (_identity == null && sqlConnectionContainerHashHelper._identity != null))
			{
				return false;
			}
			if (_identity == null && sqlConnectionContainerHashHelper._identity == null)
			{
				if (sqlConnectionContainerHashHelper._connectionString == _connectionString && string.Equals(sqlConnectionContainerHashHelper._queue, _queue, StringComparison.OrdinalIgnoreCase))
				{
					return true;
				}
				return false;
			}
			if (sqlConnectionContainerHashHelper._identity.Equals(_identity) && sqlConnectionContainerHashHelper._connectionString == _connectionString && string.Equals(sqlConnectionContainerHashHelper._queue, _queue, StringComparison.OrdinalIgnoreCase))
			{
				return true;
			}
			return false;
		}

		public override int GetHashCode()
		{
			int num = 0;
			if (_identity != null)
			{
				num = _identity.GetHashCode();
			}
			if (_queue != null)
			{
				return _connectionString.GetHashCode() + _queue.GetHashCode() + num;
			}
			return _connectionString.GetHashCode() + num;
		}
	}

	private static SqlDependencyProcessDispatcher s_staticInstance = new SqlDependencyProcessDispatcher(null);

	private Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer> _connectionContainers;

	private Dictionary<string, SqlDependencyPerAppDomainDispatcher> _sqlDependencyPerAppDomainDispatchers;

	internal static SqlDependencyProcessDispatcher SingletonProcessDispatcher => s_staticInstance;

	private SqlDependencyProcessDispatcher(object dummyVariable)
	{
		_connectionContainers = new Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer>();
		_sqlDependencyPerAppDomainDispatchers = new Dictionary<string, SqlDependencyPerAppDomainDispatcher>();
	}

	public SqlDependencyProcessDispatcher()
	{
	}

	private static SqlConnectionContainerHashHelper GetHashHelper(string connectionString, out SqlConnectionStringBuilder connectionStringBuilder, out DbConnectionPoolIdentity identity, out string user, string queue)
	{
		connectionStringBuilder = new SqlConnectionStringBuilder(connectionString)
		{
			Pooling = false,
			Enlist = false,
			ConnectRetryCount = 0
		};
		if (queue != null)
		{
			connectionStringBuilder.ApplicationName = queue;
		}
		if (connectionStringBuilder.IntegratedSecurity)
		{
			identity = DbConnectionPoolIdentity.GetCurrent();
			user = null;
		}
		else
		{
			identity = null;
			user = connectionStringBuilder.UserID;
		}
		return new SqlConnectionContainerHashHelper(identity, connectionStringBuilder.ConnectionString, queue, connectionStringBuilder);
	}

	public override object InitializeLifetimeService()
	{
		return null;
	}

	private void Invalidate(string server, SqlNotification sqlNotification)
	{
		lock (_sqlDependencyPerAppDomainDispatchers)
		{
			foreach (KeyValuePair<string, SqlDependencyPerAppDomainDispatcher> sqlDependencyPerAppDomainDispatcher in _sqlDependencyPerAppDomainDispatchers)
			{
				SqlDependencyPerAppDomainDispatcher value = sqlDependencyPerAppDomainDispatcher.Value;
				try
				{
					value.InvalidateServer(server, sqlNotification);
				}
				catch (Exception e)
				{
					if (!ADP.IsCatchableExceptionType(e))
					{
						throw;
					}
					ADP.TraceExceptionWithoutRethrow(e);
				}
			}
		}
	}

	internal void QueueAppDomainUnloading(string appDomainKey)
	{
		ThreadPool.QueueUserWorkItem(AppDomainUnloading, appDomainKey);
	}

	private void AppDomainUnloading(object state)
	{
		string text = (string)state;
		lock (_connectionContainers)
		{
			List<SqlConnectionContainerHashHelper> list = new List<SqlConnectionContainerHashHelper>();
			foreach (KeyValuePair<SqlConnectionContainerHashHelper, SqlConnectionContainer> connectionContainer in _connectionContainers)
			{
				SqlConnectionContainer value = connectionContainer.Value;
				if (value.AppDomainUnload(text))
				{
					list.Add(value.HashHelper);
				}
			}
			foreach (SqlConnectionContainerHashHelper item in list)
			{
				_connectionContainers.Remove(item);
			}
		}
		lock (_sqlDependencyPerAppDomainDispatchers)
		{
			_sqlDependencyPerAppDomainDispatchers.Remove(text);
		}
	}

	internal bool StartWithDefault(string connectionString, out string server, out DbConnectionPoolIdentity identity, out string user, out string database, ref string service, string appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher, out bool errorOccurred, out bool appDomainStart)
	{
		return Start(connectionString, out server, out identity, out user, out database, ref service, appDomainKey, dispatcher, out errorOccurred, out appDomainStart, useDefaults: true);
	}

	internal bool Start(string connectionString, string queue, string appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher)
	{
		string server;
		DbConnectionPoolIdentity identity;
		bool errorOccurred;
		return Start(connectionString, out server, out identity, out server, out server, ref queue, appDomainKey, dispatcher, out errorOccurred, out errorOccurred, useDefaults: false);
	}

	private bool Start(string connectionString, out string server, out DbConnectionPoolIdentity identity, out string user, out string database, ref string queueService, string appDomainKey, SqlDependencyPerAppDomainDispatcher dispatcher, out bool errorOccurred, out bool appDomainStart, bool useDefaults)
	{
		server = null;
		identity = null;
		user = null;
		database = null;
		errorOccurred = false;
		appDomainStart = false;
		lock (_sqlDependencyPerAppDomainDispatchers)
		{
			if (!_sqlDependencyPerAppDomainDispatchers.ContainsKey(appDomainKey))
			{
				_sqlDependencyPerAppDomainDispatchers[appDomainKey] = dispatcher;
			}
		}
		SqlConnectionStringBuilder connectionStringBuilder;
		SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString, out connectionStringBuilder, out identity, out user, queueService);
		bool result = false;
		SqlConnectionContainer sqlConnectionContainer = null;
		lock (_connectionContainers)
		{
			if (!_connectionContainers.ContainsKey(hashHelper))
			{
				sqlConnectionContainer = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults);
				_connectionContainers.Add(hashHelper, sqlConnectionContainer);
				result = true;
				appDomainStart = true;
			}
			else
			{
				sqlConnectionContainer = _connectionContainers[hashHelper];
				if (sqlConnectionContainer.InErrorState)
				{
					errorOccurred = true;
				}
				else
				{
					sqlConnectionContainer.IncrementStartCount(appDomainKey, out appDomainStart);
				}
			}
		}
		if (useDefaults && !errorOccurred)
		{
			server = sqlConnectionContainer.Server;
			database = sqlConnectionContainer.Database;
			queueService = sqlConnectionContainer.Queue;
		}
		return result;
	}

	internal bool Stop(string connectionString, out string server, out DbConnectionPoolIdentity identity, out string user, out string database, ref string queueService, string appDomainKey, out bool appDomainStop)
	{
		server = null;
		identity = null;
		user = null;
		database = null;
		appDomainStop = false;
		SqlConnectionStringBuilder connectionStringBuilder;
		SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString, out connectionStringBuilder, out identity, out user, queueService);
		bool result = false;
		lock (_connectionContainers)
		{
			if (_connectionContainers.ContainsKey(hashHelper))
			{
				SqlConnectionContainer sqlConnectionContainer = _connectionContainers[hashHelper];
				server = sqlConnectionContainer.Server;
				database = sqlConnectionContainer.Database;
				queueService = sqlConnectionContainer.Queue;
				if (sqlConnectionContainer.Stop(appDomainKey, out appDomainStop))
				{
					result = true;
					_connectionContainers.Remove(hashHelper);
				}
			}
		}
		return result;
	}
}
internal static class AssemblyRef
{
	internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string EcmaPublicKey = "b77a5c561934e089";

	public const string FrameworkPublicKeyFull = "00000000000000000400000000000000";

	public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000";

	public const string MicrosoftPublicKey = "b03f5f7f11d50a3a";

	public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal sealed class Locale
{
	private Locale()
	{
	}

	public static string GetText(string msg)
	{
		return msg;
	}

	public static string GetText(string fmt, params object[] args)
	{
		return string.Format(fmt, args);
	}
}
internal static class SR
{
	public const string ADP_CollectionIndexString = "An {0} with {1} '{2}' is not contained by this {3}.";

	public const string ADP_CollectionInvalidType = "The {0} only accepts non-null {1} type objects, not {2} objects.";

	public const string ADP_CollectionIsNotParent = "The {0} is already contained by another {1}.";

	public const string ADP_CollectionNullValue = "The {0} only accepts non-null {1} type objects.";

	public const string ADP_CollectionRemoveInvalidObject = "Attempted to remove an {0} that is not contained by this {1}.";

	public const string ADP_CollectionUniqueValue = "The {0}.{1} is required to be unique, '{2}' already exists in the collection.";

	public const string ADP_ConnectionStateMsg_Closed = "The connection's current state is closed.";

	public const string ADP_ConnectionStateMsg_Connecting = "The connection's current state is connecting.";

	public const string ADP_ConnectionStateMsg_Open = "The connection's current state is open.";

	public const string ADP_ConnectionStateMsg_OpenExecuting = "The connection's current state is executing.";

	public const string ADP_ConnectionStateMsg_OpenFetching = "The connection's current state is fetching.";

	public const string ADP_ConnectionStateMsg = "The connection's current state: {0}.";

	public const string ADP_ConnectionStringSyntax = "Format of the initialization string does not conform to specification starting at index {0}.";

	public const string ADP_DataReaderClosed = "Invalid attempt to call {0} when reader is closed.";

	public const string ADP_EmptyString = "Expecting non-empty string for '{0}' parameter.";

	public const string ADP_InvalidEnumerationValue = "The {0} enumeration value, {1}, is invalid.";

	public const string ADP_InvalidKey = "Invalid keyword, contain one or more of 'no characters', 'control characters', 'leading or trailing whitespace' or 'leading semicolons'.";

	public const string ADP_InvalidValue = "The value contains embedded nulls (\\\\u0000).";

	public const string Xml_SimpleTypeNotSupported = "DataSet doesn't support 'union' or 'list' as simpleType.";

	public const string Xml_MissingAttribute = "Invalid {0} syntax: missing required '{1}' attribute.";

	public const string Xml_ValueOutOfRange = "Value '{1}' is invalid for attribute '{0}'.";

	public const string Xml_AttributeValues = "The value of attribute '{0}' should be '{1}' or '{2}'.";

	public const string Xml_RelationParentNameMissing = "Parent table name is missing in relation '{0}'.";

	public const string Xml_RelationChildNameMissing = "Child table name is missing in relation '{0}'.";

	public const string Xml_RelationTableKeyMissing = "Parent table key is missing in relation '{0}'.";

	public const string Xml_RelationChildKeyMissing = "Child table key is missing in relation '{0}'.";

	public const string Xml_UndefinedDatatype = "Undefined data type: '{0}'.";

	public const string Xml_DatatypeNotDefined = "Data type not defined.";

	public const string Xml_InvalidField = "Invalid XPath selection inside field node. Cannot find: {0}.";

	public const string Xml_InvalidSelector = "Invalid XPath selection inside selector node: {0}.";

	public const string Xml_InvalidKey = "Invalid 'Key' node inside constraint named: {0}.";

	public const string Xml_DuplicateConstraint = "The constraint name {0} is already used in the schema.";

	public const string Xml_CannotConvert = " Cannot convert '{0}' to type '{1}'.";

	public const string Xml_MissingRefer = "Missing '{0}' part in '{1}' constraint named '{2}'.";

	public const string Xml_MismatchKeyLength = "Invalid Relation definition: different length keys.";

	public const string Xml_CircularComplexType = "DataSet doesn't allow the circular reference in the ComplexType named '{0}'.";

	public const string Xml_CannotInstantiateAbstract = "DataSet cannot instantiate an abstract ComplexType for the node {0}.";

	public const string Xml_MultipleTargetConverterError = "An error occurred with the multiple target converter while writing an Xml Schema.  See the inner exception for details.";

	public const string Xml_MultipleTargetConverterEmpty = "An error occurred with the multiple target converter while writing an Xml Schema.  A null or empty string was returned.";

	public const string Xml_MergeDuplicateDeclaration = "Duplicated declaration '{0}'.";

	public const string Xml_MissingTable = "Cannot load diffGram. Table '{0}' is missing in the destination dataset.";

	public const string Xml_MissingSQL = "Cannot load diffGram. The 'sql' node is missing.";

	public const string Xml_ColumnConflict = "Column name '{0}' is defined for different mapping types.";

	public const string Xml_InvalidPrefix = "Prefix '{0}' is not valid, because it contains special characters.";

	public const string Xml_NestedCircular = "Circular reference in self-nested table '{0}'.";

	public const string Xml_FoundEntity = "DataSet cannot expand entities. Use XmlValidatingReader and set the EntityHandling property accordingly.";

	public const string Xml_PolymorphismNotSupported = "Type '{0}' does not implement IXmlSerializable interface therefore can not proceed with serialization.";

	public const string Xml_CanNotDeserializeObjectType = "Unable to proceed with deserialization. Data does not implement IXMLSerializable, therefore polymorphism is not supported.";

	public const string Xml_DataTableInferenceNotSupported = "DataTable does not support schema inference from Xml.";

	public const string Xml_MultipleParentRows = "Cannot proceed with serializing DataTable '{0}'. It contains a DataRow which has multiple parent rows on the same Foreign Key.";

	public const string Xml_IsDataSetAttributeMissingInSchema = "IsDataSet attribute is missing in input Schema.";

	public const string Xml_TooManyIsDataSetAtributeInSchema = "Cannot determine the DataSet Element. IsDataSet attribute exist more than once.";

	public const string Xml_DynamicWithoutXmlSerializable = "DataSet will not serialize types that implement IDynamicMetaObjectProvider but do not also implement IXmlSerializable.";

	public const string Expr_NYI = "The feature not implemented. {0}.";

	public const string Expr_MissingOperand = "Syntax error: Missing operand after '{0}' operator.";

	public const string Expr_TypeMismatch = "Type mismatch in expression '{0}'.";

	public const string Expr_ExpressionTooComplex = "Expression is too complex.";

	public const string Expr_UnboundName = "Cannot find column [{0}].";

	public const string Expr_InvalidString = "The expression contains an invalid string constant: {0}.";

	public const string Expr_UndefinedFunction = "The expression contains undefined function call {0}().";

	public const string Expr_Syntax = "Syntax error in the expression.";

	public const string Expr_FunctionArgumentCount = "Invalid number of arguments: function {0}().";

	public const string Expr_MissingRightParen = "The expression is missing the closing parenthesis.";

	public const string Expr_UnknownToken = "Cannot interpret token '{0}' at position {1}.";

	public const string Expr_UnknownToken1 = "Expected {0}, but actual token at the position {2} is {1}.";

	public const string Expr_DatatypeConvertion = "Cannot convert from {0} to {1}.";

	public const string Expr_DatavalueConvertion = "Cannot convert value '{0}' to Type: {1}.";

	public const string Expr_InvalidName = "Invalid column name [{0}].";

	public const string Expr_InvalidDate = "The expression contains invalid date constant '{0}'.";

	public const string Expr_NonConstantArgument = "Only constant expressions are allowed in the expression list for the IN operator.";

	public const string Expr_InvalidPattern = "Error in Like operator: the string pattern '{0}' is invalid.";

	public const string Expr_InWithoutParentheses = "Syntax error: The items following the IN keyword must be separated by commas and be enclosed in parentheses.";

	public const string Expr_ArgumentType = "Type mismatch in function argument: {0}(), argument {1}, expected {2}.";

	public const string Expr_ArgumentTypeInteger = "Type mismatch in function argument: {0}(), argument {1}, expected one of the Integer types.";

	public const string Expr_TypeMismatchInBinop = "Cannot perform '{0}' operation on {1} and {2}.";

	public const string Expr_AmbiguousBinop = "Operator '{0}' is ambiguous on operands of type '{1}' and '{2}'. Cannot mix signed and unsigned types. Please use explicit Convert() function.";

	public const string Expr_InWithoutList = "Syntax error: The IN keyword must be followed by a non-empty list of expressions separated by commas, and also must be enclosed in parentheses.";

	public const string Expr_UnsupportedOperator = "The expression contains unsupported operator '{0}'.";

	public const string Expr_InvalidNameBracketing = "The expression contains invalid name: '{0}'.";

	public const string Expr_MissingOperandBefore = "Syntax error: Missing operand before '{0}' operator.";

	public const string Expr_TooManyRightParentheses = "The expression has too many closing parentheses.";

	public const string Expr_UnresolvedRelation = "The table [{0}] involved in more than one relation. You must explicitly mention a relation name in the expression '{1}'.";

	public const string Expr_AggregateArgument = "Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier.";

	public const string Expr_AggregateUnbound = "Unbound reference in the aggregate expression '{0}'.";

	public const string Expr_EvalNoContext = "Cannot evaluate non-constant expression without current row.";

	public const string Expr_ExpressionUnbound = "Unbound reference in the expression '{0}'.";

	public const string Expr_ComputeNotAggregate = "Cannot evaluate. Expression '{0}' is not an aggregate.";

	public const string Expr_FilterConvertion = "Filter expression '{0}' does not evaluate to a Boolean term.";

	public const string Expr_InvalidType = "Invalid type name '{0}'.";

	public const string Expr_LookupArgument = "Syntax error in Lookup expression: Expecting keyword 'Parent' followed by a single column argument with possible relation qualifier: Parent[(<relation_name>)].<column_name>.";

	public const string Expr_InvokeArgument = "Need a row or a table to Invoke DataFilter.";

	public const string Expr_ArgumentOutofRange = "{0}() argument is out of range.";

	public const string Expr_IsSyntax = "Syntax error: Invalid usage of 'Is' operator. Correct syntax: <expression> Is [Not] Null.";

	public const string Expr_Overflow = "Value is either too large or too small for Type '{0}'.";

	public const string Expr_BindFailure = "Cannot find the parent relation '{0}'.";

	public const string Expr_InvalidHoursArgument = "'hours' argument is out of range. Value must be between -14 and +14.";

	public const string Expr_InvalidMinutesArgument = "'minutes' argument is out of range. Value must be between -59 and +59.";

	public const string Expr_InvalidTimeZoneRange = "Provided range for time one exceeds total of 14 hours.";

	public const string Expr_MismatchKindandTimeSpan = "Kind property of provided DateTime argument, does not match 'hours' and 'minutes' arguments.";

	public const string Expr_UnsupportedType = "A DataColumn of type '{0}' does not support expression.";

	public const string Data_EnforceConstraints = "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.";

	public const string Data_CannotModifyCollection = "Collection itself is not modifiable.";

	public const string Data_CaseInsensitiveNameConflict = "The given name '{0}' matches at least two names in the collection object with different cases, but does not match either of them with the same case.";

	public const string Data_NamespaceNameConflict = "The given name '{0}' matches at least two names in the collection object with different namespaces.";

	public const string Data_InvalidOffsetLength = "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.";

	public const string Data_ArgumentOutOfRange = "'{0}' argument is out of range.";

	public const string Data_ArgumentNull = "'{0}' argument cannot be null.";

	public const string Data_ArgumentContainsNull = "'{0}' argument contains null value.";

	public const string Data_TypeNotAllowed = "Type '{0}' is not allowed here. See https://go.microsoft.com/fwlink/?linkid=2132227 for more details.";

	public const string DataColumns_OutOfRange = "Cannot find column {0}.";

	public const string DataColumns_Add1 = "Column '{0}' already belongs to this DataTable.";

	public const string DataColumns_Add2 = "Column '{0}' already belongs to another DataTable.";

	public const string DataColumns_Add3 = "Cannot have more than one SimpleContent columns in a DataTable.";

	public const string DataColumns_Add4 = "Cannot add a SimpleContent column to a table containing element columns or nested relations.";

	public const string DataColumns_AddDuplicate = "A column named '{0}' already belongs to this DataTable.";

	public const string DataColumns_AddDuplicate2 = "Cannot add a column named '{0}': a nested table with the same name already belongs to this DataTable.";

	public const string DataColumns_AddDuplicate3 = "A column named '{0}' already belongs to this DataTable: cannot set a nested table name to the same name.";

	public const string DataColumns_Remove = "Cannot remove a column that doesn't belong to this table.";

	public const string DataColumns_RemovePrimaryKey = "Cannot remove this column, because it's part of the primary key.";

	public const string DataColumns_RemoveChildKey = "Cannot remove this column, because it is part of the parent key for relationship {0}.";

	public const string DataColumns_RemoveConstraint = "Cannot remove this column, because it is a part of the constraint {0} on the table {1}.";

	public const string DataColumn_AutoIncrementAndExpression = "Cannot set AutoIncrement property for a computed column.";

	public const string DataColumn_AutoIncrementAndDefaultValue = "Cannot set AutoIncrement property for a column with DefaultValue set.";

	public const string DataColumn_DefaultValueAndAutoIncrement = "Cannot set a DefaultValue on an AutoIncrement column.";

	public const string DataColumn_AutoIncrementSeed = "AutoIncrementStep must be a non-zero value.";

	public const string DataColumn_NameRequired = "ColumnName is required when it is part of a DataTable.";

	public const string DataColumn_ChangeDataType = "Cannot change DataType of a column once it has data.";

	public const string DataColumn_NullDataType = "Column requires a valid DataType.";

	public const string DataColumn_DefaultValueDataType = "The DefaultValue for column {0} is of type {1} and cannot be converted to {2}.";

	public const string DataColumn_DefaultValueDataType1 = "The DefaultValue for the column is of type {0} and cannot be converted to {1}.";

	public const string DataColumn_DefaultValueColumnDataType = "The DefaultValue for column {0} is of type {1}, but the column is of type {2}.";

	public const string DataColumn_ReadOnlyAndExpression = "Cannot change ReadOnly property for the expression column.";

	public const string DataColumn_UniqueAndExpression = "Cannot change Unique property for the expression column.";

	public const string DataColumn_ExpressionAndUnique = "Cannot create an expression on a column that has AutoIncrement or Unique.";

	public const string DataColumn_ExpressionAndReadOnly = "Cannot set expression because column cannot be made ReadOnly.";

	public const string DataColumn_ExpressionAndConstraint = "Cannot set Expression property on column {0}, because it is a part of a constraint.";

	public const string DataColumn_ExpressionInConstraint = "Cannot create a constraint based on Expression column {0}.";

	public const string DataColumn_ExpressionCircular = "Cannot set Expression property due to circular reference in the expression.";

	public const string DataColumn_NullKeyValues = "Column '{0}' has null values in it.";

	public const string DataColumn_NullValues = "Column '{0}' does not allow nulls.";

	public const string DataColumn_ReadOnly = "Column '{0}' is read only.";

	public const string DataColumn_NonUniqueValues = "Column '{0}' contains non-unique values.";

	public const string DataColumn_NotInTheTable = "Column '{0}' does not belong to table {1}.";

	public const string DataColumn_NotInAnyTable = "Column must belong to a table.";

	public const string DataColumn_SetFailed = "Couldn't store <{0}> in {1} Column.  Expected type is {2}.";

	public const string DataColumn_CannotSetToNull = "Cannot set Column '{0}' to be null. Please use DBNull instead.";

	public const string DataColumn_LongerThanMaxLength = "Cannot set column '{0}'. The value violates the MaxLength limit of this column.";

	public const string DataColumn_HasToBeStringType = "MaxLength applies to string data type only. You cannot set Column '{0}' property MaxLength to be non-negative number.";

	public const string DataColumn_CannotSetMaxLength = "Cannot set Column '{0}' property MaxLength to '{1}'. There is at least one string in the table longer than the new limit.";

	public const string DataColumn_CannotSetMaxLength2 = "Cannot set Column '{0}' property MaxLength. The Column is SimpleContent.";

	public const string DataColumn_CannotSimpleContentType = "Cannot set Column '{0}' property DataType to {1}. The Column is SimpleContent.";

	public const string DataColumn_CannotSimpleContent = "Cannot set Column '{0}' property MappingType to SimpleContent. The Column DataType is {1}.";

	public const string DataColumn_ExceedMaxLength = "Column '{0}' exceeds the MaxLength limit.";

	public const string DataColumn_NotAllowDBNull = "Column '{0}' does not allow DBNull.Value.";

	public const string DataColumn_CannotChangeNamespace = "Cannot change the Column '{0}' property Namespace. The Column is SimpleContent.";

	public const string DataColumn_AutoIncrementCannotSetIfHasData = "Cannot change AutoIncrement of a DataColumn with type '{0}' once it has data.";

	public const string DataColumn_NotInTheUnderlyingTable = "Column '{0}' does not belong to underlying table '{1}'.";

	public const string DataColumn_InvalidDataColumnMapping = "DataColumn with type '{0}' is a complexType. Can not serialize value of a complex type as Attribute";

	public const string DataColumn_CannotSetDateTimeModeForNonDateTimeColumns = "The DateTimeMode can be set only on DataColumns of type DateTime.";

	public const string DataColumn_DateTimeMode = "Cannot change DateTimeMode from '{0}' to '{1}' once the table has data.";

	public const string DataColumn_INullableUDTwithoutStaticNull = "Type '{0}' does not contain static Null property or field.";

	public const string DataColumn_UDTImplementsIChangeTrackingButnotIRevertible = "Type '{0}' does not implement IRevertibleChangeTracking; therefore can not proceed with RejectChanges().";

	public const string DataColumn_SetAddedAndModifiedCalledOnNonUnchanged = "SetAdded and SetModified can only be called on DataRows with Unchanged DataRowState.";

	public const string DataColumn_OrdinalExceedMaximun = "Ordinal '{0}' exceeds the maximum number.";

	public const string DataColumn_NullableTypesNotSupported = "DataSet does not support System.Nullable<>.";

	public const string DataConstraint_NoName = "Cannot change the name of a constraint to empty string when it is in the ConstraintCollection.";

	public const string DataConstraint_Violation = "Cannot enforce constraints on constraint {0}.";

	public const string DataConstraint_ViolationValue = "Column '{0}' is constrained to be unique.  Value '{1}' is already present.";

	public const string DataConstraint_NotInTheTable = "Constraint '{0}' does not belong to this DataTable.";

	public const string DataConstraint_OutOfRange = "Cannot find constraint {0}.";

	public const string DataConstraint_Duplicate = "Constraint matches constraint named {0} already in collection.";

	public const string DataConstraint_DuplicateName = "A Constraint named '{0}' already belongs to this DataTable.";

	public const string DataConstraint_UniqueViolation = "These columns don't currently have unique values.";

	public const string DataConstraint_ForeignTable = "These columns don't point to this table.";

	public const string DataConstraint_ParentValues = "This constraint cannot be enabled as not all values have corresponding parent values.";

	public const string DataConstraint_AddFailed = "This constraint cannot be added since ForeignKey doesn't belong to table {0}.";

	public const string DataConstraint_RemoveFailed = "Cannot remove a constraint that doesn't belong to this table.";

	public const string DataConstraint_NeededForForeignKeyConstraint = "Cannot remove unique constraint '{0}'. Remove foreign key constraint '{1}' first.";

	public const string DataConstraint_CascadeDelete = "Cannot delete this row because constraints are enforced on relation {0}, and deleting this row will strand child rows.";

	public const string DataConstraint_CascadeUpdate = "Cannot make this change because constraints are enforced on relation {0}, and changing this value will strand child rows.";

	public const string DataConstraint_ClearParentTable = "Cannot clear table {0} because ForeignKeyConstraint {1} enforces constraints and there are child rows in {2}.";

	public const string DataConstraint_ForeignKeyViolation = "ForeignKeyConstraint {0} requires the child key values ({1}) to exist in the parent table.";

	public const string DataConstraint_BadObjectPropertyAccess = "Property not accessible because '{0}'.";

	public const string DataConstraint_RemoveParentRow = "Cannot remove this row because it has child rows, and constraints on relation {0} are enforced.";

	public const string DataConstraint_AddPrimaryKeyConstraint = "Cannot add primary key constraint since primary key is already set for the table.";

	public const string DataConstraint_CantAddConstraintToMultipleNestedTable = "Cannot add constraint to DataTable '{0}' which is a child table in two nested relations.";

	public const string DataKey_TableMismatch = "Cannot create a Key from Columns that belong to different tables.";

	public const string DataKey_NoColumns = "Cannot have 0 columns.";

	public const string DataKey_TooManyColumns = "Cannot have more than {0} columns.";

	public const string DataKey_DuplicateColumns = "Cannot create a Key when the same column is listed more than once: '{0}'";

	public const string DataKey_RemovePrimaryKey = "Cannot remove unique constraint since it's the primary key of a table.";

	public const string DataKey_RemovePrimaryKey1 = "Cannot remove unique constraint since it's the primary key of table {0}.";

	public const string DataRelation_ColumnsTypeMismatch = "Parent Columns and Child Columns don't have type-matching columns.";

	public const string DataRelation_KeyColumnsIdentical = "ParentKey and ChildKey are identical.";

	public const string DataRelation_KeyLengthMismatch = "ParentColumns and ChildColumns should be the same length.";

	public const string DataRelation_KeyZeroLength = "ParentColumns and ChildColumns must not be zero length.";

	public const string DataRelation_ForeignRow = "The row doesn't belong to the same DataSet as this relation.";

	public const string DataRelation_NoName = "RelationName is required when it is part of a DataSet.";

	public const string DataRelation_ForeignTable = "GetChildRows requires a row whose Table is {0}, but the specified row's Table is {1}.";

	public const string DataRelation_ForeignDataSet = "This relation should connect two tables in this DataSet to be added to this DataSet.";

	public const string DataRelation_GetParentRowTableMismatch = "GetParentRow requires a row whose Table is {0}, but the specified row's Table is {1}.";

	public const string DataRelation_SetParentRowTableMismatch = "SetParentRow requires a child row whose Table is {0}, but the specified row's Table is {1}.";

	public const string DataRelation_DataSetMismatch = "Cannot have a relationship between tables in different DataSets.";

	public const string DataRelation_TablesInDifferentSets = "Cannot create a relation between tables in different DataSets.";

	public const string DataRelation_AlreadyExists = "A relation already exists for these child columns.";

	public const string DataRelation_DoesNotExist = "This relation doesn't belong to this relation collection.";

	public const string DataRelation_AlreadyInOtherDataSet = "This relation already belongs to another DataSet.";

	public const string DataRelation_AlreadyInTheDataSet = "This relation already belongs to this DataSet.";

	public const string DataRelation_DuplicateName = "A Relation named '{0}' already belongs to this DataSet.";

	public const string DataRelation_NotInTheDataSet = "Relation {0} does not belong to this DataSet.";

	public const string DataRelation_OutOfRange = "Cannot find relation {0}.";

	public const string DataRelation_TableNull = "Cannot create a collection on a null table.";

	public const string DataRelation_TableWasRemoved = "The table this collection displays relations for has been removed from its DataSet.";

	public const string DataRelation_ChildTableMismatch = "Cannot add a relation to this table's ParentRelation collection where this table isn't the child table.";

	public const string DataRelation_ParentTableMismatch = "Cannot add a relation to this table's ChildRelation collection where this table isn't the parent table.";

	public const string DataRelation_RelationNestedReadOnly = "Cannot set the 'Nested' property to false for this relation.";

	public const string DataRelation_TableCantBeNestedInTwoTables = "The same table '{0}' cannot be the child table in two nested relations.";

	public const string DataRelation_LoopInNestedRelations = "The table ({0}) cannot be the child table to itself in nested relations.";

	public const string DataRelation_CaseLocaleMismatch = "Cannot add a DataRelation or Constraint that has different Locale or CaseSensitive settings between its parent and child tables.";

	public const string DataRelation_ParentOrChildColumnsDoNotHaveDataSet = "Cannot create a DataRelation if Parent or Child Columns are not in a DataSet.";

	public const string DataRelation_InValidNestedRelation = "Nested table '{0}' which inherits its namespace cannot have multiple parent tables in different namespaces.";

	public const string DataRelation_InValidNamespaceInNestedRelation = "Nested table '{0}' with empty namespace cannot have multiple parent tables in different namespaces.";

	public const string DataRow_NotInTheDataSet = "The row doesn't belong to the same DataSet as this relation.";

	public const string DataRow_NotInTheTable = "Cannot perform this operation on a row not in the table.";

	public const string DataRow_ParentRowNotInTheDataSet = "This relation and child row don't belong to same DataSet.";

	public const string DataRow_EditInRowChanging = "Cannot change a proposed value in the RowChanging event.";

	public const string DataRow_EndEditInRowChanging = "Cannot call EndEdit() inside an OnRowChanging event.";

	public const string DataRow_BeginEditInRowChanging = "Cannot call BeginEdit() inside the RowChanging event.";

	public const string DataRow_CancelEditInRowChanging = "Cannot call CancelEdit() inside an OnRowChanging event.  Throw an exception to cancel this update.";

	public const string DataRow_DeleteInRowDeleting = "Cannot call Delete inside an OnRowDeleting event.  Throw an exception to cancel this delete.";

	public const string DataRow_ValuesArrayLength = "Input array is longer than the number of columns in this table.";

	public const string DataRow_NoCurrentData = "There is no Current data to access.";

	public const string DataRow_NoOriginalData = "There is no Original data to access.";

	public const string DataRow_NoProposedData = "There is no Proposed data to access.";

	public const string DataRow_RemovedFromTheTable = "This row has been removed from a table and does not have any data.  BeginEdit() will allow creation of new data in this row.";

	public const string DataRow_DeletedRowInaccessible = "Deleted row information cannot be accessed through the row.";

	public const string DataRow_InvalidVersion = "Version must be Original, Current, or Proposed.";

	public const string DataRow_OutOfRange = "There is no row at position {0}.";

	public const string DataRow_RowInsertOutOfRange = "The row insert position {0} is invalid.";

	public const string DataRow_RowInsertMissing = "Values are missing in the rowOrder sequence for table '{0}'.";

	public const string DataRow_RowOutOfRange = "The given DataRow is not in the current DataRowCollection.";

	public const string DataRow_AlreadyInOtherCollection = "This row already belongs to another table.";

	public const string DataRow_AlreadyInTheCollection = "This row already belongs to this table.";

	public const string DataRow_AlreadyDeleted = "Cannot delete this row since it's already deleted.";

	public const string DataRow_Empty = "This row is empty.";

	public const string DataRow_AlreadyRemoved = "Cannot remove a row that's already been removed.";

	public const string DataRow_MultipleParents = "A child row has multiple parents.";

	public const string DataRow_InvalidRowBitPattern = "Unrecognized row state bit pattern.";

	public const string DataSet_SetNameToEmpty = "Cannot change the name of the DataSet to an empty string.";

	public const string DataSet_SetDataSetNameConflicting = "The name '{0}' is invalid. A DataSet cannot have the same name of the DataTable.";

	public const string DataSet_UnsupportedSchema = "The schema namespace is invalid. Please use this one instead: {0}.";

	public const string DataSet_CannotChangeCaseLocale = "Cannot change CaseSensitive or Locale property. This change would lead to at least one DataRelation or Constraint to have different Locale or CaseSensitive settings between its related tables.";

	public const string DataSet_CannotChangeSchemaSerializationMode = "SchemaSerializationMode property can be set only if it is overridden by derived DataSet.";

	public const string DataTable_ForeignPrimaryKey = "PrimaryKey columns do not belong to this table.";

	public const string DataTable_CannotAddToSimpleContent = "Cannot add a nested relation or an element column to a table containing a SimpleContent column.";

	public const string DataTable_NoName = "TableName is required when it is part of a DataSet.";

	public const string DataTable_MultipleSimpleContentColumns = "DataTable already has a simple content column.";

	public const string DataTable_MissingPrimaryKey = "Table doesn't have a primary key.";

	public const string DataTable_InvalidSortString = " {0} isn't a valid Sort string entry.";

	public const string DataTable_CanNotSerializeDataTableHierarchy = "Cannot serialize the DataTable. A DataTable being used in one or more DataColumn expressions is not a descendant of current DataTable.";

	public const string DataTable_CanNotRemoteDataTable = "This DataTable can only be remoted as part of DataSet. One or more Expression Columns has reference to other DataTable(s).";

	public const string DataTable_CanNotSetRemotingFormat = "Cannot have different remoting format property value for DataSet and DataTable.";

	public const string DataTable_CanNotSerializeDataTableWithEmptyName = "Cannot serialize the DataTable. DataTable name is not set.";

	public const string DataTable_DuplicateName = "A DataTable named '{0}' already belongs to this DataSet.";

	public const string DataTable_DuplicateName2 = "A DataTable named '{0}' with the same Namespace '{1}' already belongs to this DataSet.";

	public const string DataTable_SelfnestedDatasetConflictingName = "The table ({0}) cannot be the child table to itself in a nested relation: the DataSet name conflicts with the table name.";

	public const string DataTable_DatasetConflictingName = "The name '{0}' is invalid. A DataTable cannot have the same name of the DataSet.";

	public const string DataTable_AlreadyInOtherDataSet = "DataTable already belongs to another DataSet.";

	public const string DataTable_AlreadyInTheDataSet = "DataTable already belongs to this DataSet.";

	public const string DataTable_NotInTheDataSet = "Table {0} does not belong to this DataSet.";

	public const string DataTable_OutOfRange = "Cannot find table {0}.";

	public const string DataTable_InRelation = "Cannot remove a table that has existing relations.  Remove relations first.";

	public const string DataTable_InConstraint = "Cannot remove table {0}, because it referenced in ForeignKeyConstraint {1}.  Remove the constraint first.";

	public const string DataTable_TableNotFound = "DataTable '{0}' does not match to any DataTable in source.";

	public const string DataMerge_MissingDefinition = "Target DataSet missing definition for {0}.";

	public const string DataMerge_MissingConstraint = "Target DataSet missing {0} {1}.";

	public const string DataMerge_DataTypeMismatch = "<target>.{0} and <source>.{0} have conflicting properties: DataType property mismatch.";

	public const string DataMerge_PrimaryKeyMismatch = "<target>.PrimaryKey and <source>.PrimaryKey have different Length.";

	public const string DataMerge_PrimaryKeyColumnsMismatch = "Mismatch columns in the PrimaryKey : <target>.{0} versus <source>.{1}.";

	public const string DataMerge_ReltionKeyColumnsMismatch = "Relation {0} cannot be merged, because keys have mismatch columns.";

	public const string DataMerge_MissingColumnDefinition = "Target table {0} missing definition for column {1}.";

	public const string DataIndex_RecordStateRange = "The RowStates parameter must be set to a valid combination of values from the DataViewRowState enumeration.";

	public const string DataIndex_FindWithoutSortOrder = "Find finds a row based on a Sort order, and no Sort order is specified.";

	public const string DataIndex_KeyLength = "Expecting {0} value(s) for the key being indexed, but received {1} value(s).";

	public const string DataStorage_AggregateException = "Invalid usage of aggregate function {0}() and Type: {1}.";

	public const string DataStorage_InvalidStorageType = "Invalid storage type: {0}.";

	public const string DataStorage_ProblematicChars = "The DataSet Xml persistency does not support the value '{0}' as Char value, please use Byte storage instead.";

	public const string DataStorage_SetInvalidDataType = "Type of value has a mismatch with column type";

	public const string DataStorage_IComparableNotDefined = " Type '{0}' does not implement IComparable interface. Comparison cannot be done.";

	public const string DataView_SetFailed = "Cannot set {0}.";

	public const string DataView_SetDataSetFailed = "Cannot change DataSet on a DataViewManager that's already the default view for a DataSet.";

	public const string DataView_SetRowStateFilter = "RowStateFilter cannot show ModifiedOriginals and ModifiedCurrents at the same time.";

	public const string DataView_SetTable = "Cannot change Table property on a DefaultView or a DataView coming from a DataViewManager.";

	public const string DataView_CanNotSetDataSet = "Cannot change DataSet property once it is set.";

	public const string DataView_CanNotUseDataViewManager = "DataSet must be set prior to using DataViewManager.";

	public const string DataView_CanNotSetTable = "Cannot change Table property once it is set.";

	public const string DataView_CanNotUse = "DataTable must be set prior to using DataView.";

	public const string DataView_CanNotBindTable = "Cannot bind to DataTable with no name.";

	public const string DataView_SetIListObject = "Cannot set an object into this list.";

	public const string DataView_AddNewNotAllowNull = "Cannot call AddNew on a DataView where AllowNew is false.";

	public const string DataView_NotOpen = "DataView is not open.";

	public const string DataView_CreateChildView = "The relation is not parented to the table to which this DataView points.";

	public const string DataView_CanNotDelete = "Cannot delete on a DataSource where AllowDelete is false.";

	public const string DataView_CanNotEdit = "Cannot edit on a DataSource where AllowEdit is false.";

	public const string DataView_GetElementIndex = "Index {0} is either negative or above rows count.";

	public const string DataView_AddExternalObject = "Cannot add external objects to this list.";

	public const string DataView_CanNotClear = "Cannot clear this list.";

	public const string DataView_InsertExternalObject = "Cannot insert external objects to this list.";

	public const string DataView_RemoveExternalObject = "Cannot remove objects not in the list.";

	public const string DataROWView_PropertyNotFound = "{0} is neither a DataColumn nor a DataRelation for table {1}.";

	public const string Range_Argument = "Min ({0}) must be less than or equal to max ({1}) in a Range object.";

	public const string Range_NullRange = "This is a null range.";

	public const string RecordManager_MinimumCapacity = "MinimumCapacity must be non-negative.";

	public const string SqlConvert_ConvertFailed = " Cannot convert object of type '{0}' to object of type '{1}'.";

	public const string DataSet_DefaultDataException = "Data Exception.";

	public const string DataSet_DefaultConstraintException = "Constraint Exception.";

	public const string DataSet_DefaultDeletedRowInaccessibleException = "Deleted rows inaccessible.";

	public const string DataSet_DefaultDuplicateNameException = "Duplicate name not allowed.";

	public const string DataSet_DefaultInRowChangingEventException = "Operation not supported in the RowChanging event.";

	public const string DataSet_DefaultInvalidConstraintException = "Invalid constraint.";

	public const string DataSet_DefaultMissingPrimaryKeyException = "Missing primary key.";

	public const string DataSet_DefaultNoNullAllowedException = "Null not allowed.";

	public const string DataSet_DefaultReadOnlyException = "Column is marked read only.";

	public const string DataSet_DefaultRowNotInTableException = "Row not found in table.";

	public const string DataSet_DefaultVersionNotFoundException = "Version not found.";

	public const string Load_ReadOnlyDataModified = "ReadOnly Data is Modified.";

	public const string DataTableReader_InvalidDataTableReader = "DataTableReader is invalid for current DataTable '{0}'.";

	public const string DataTableReader_SchemaInvalidDataTableReader = "Schema of current DataTable '{0}' in DataTableReader has changed, DataTableReader is invalid.";

	public const string DataTableReader_CannotCreateDataReaderOnEmptyDataSet = "DataTableReader Cannot be created. There is no DataTable in DataSet.";

	public const string DataTableReader_DataTableReaderArgumentIsEmpty = "Cannot create DataTableReader. Argument is Empty.";

	public const string DataTableReader_ArgumentContainsNullValue = "Cannot create DataTableReader. Arguments contain null value.";

	public const string DataTableReader_InvalidRowInDataTableReader = "Current DataRow is either in Deleted or Detached state.";

	public const string DataTableReader_DataTableCleared = "Current DataTable '{0}' is empty. There is no DataRow in DataTable.";

	public const string RbTree_InvalidState = "DataTable internal index is corrupted: '{0}'.";

	public const string RbTree_EnumerationBroken = "Collection was modified; enumeration operation might not execute.";

	public const string NamedSimpleType_InvalidDuplicateNamedSimpleTypeDelaration = "Simple type '{0}' has already be declared with different '{1}'.";

	public const string DataDom_Foliation = "Invalid foliation.";

	public const string DataDom_TableNameChange = "Cannot change the table name once the associated DataSet is mapped to a loaded XML document.";

	public const string DataDom_TableNamespaceChange = "Cannot change the table namespace once the associated DataSet is mapped to a loaded XML document.";

	public const string DataDom_ColumnNameChange = "Cannot change the column name once the associated DataSet is mapped to a loaded XML document.";

	public const string DataDom_ColumnNamespaceChange = "Cannot change the column namespace once the associated DataSet is mapped to a loaded XML document.";

	public const string DataDom_ColumnMappingChange = "Cannot change the ColumnMapping property once the associated DataSet is mapped to a loaded XML document.";

	public const string DataDom_TableColumnsChange = "Cannot add or remove columns from the table once the DataSet is mapped to a loaded XML document.";

	public const string DataDom_DataSetTablesChange = "Cannot add or remove tables from the DataSet once the DataSet is mapped to a loaded XML document.";

	public const string DataDom_DataSetNestedRelationsChange = "Cannot add, remove, or change Nested relations from the DataSet once the DataSet is mapped to a loaded XML document.";

	public const string DataDom_DataSetNull = "The DataSet parameter is invalid. It cannot be null.";

	public const string DataDom_DataSetNameChange = "Cannot change the DataSet name once the DataSet is mapped to a loaded XML document.";

	public const string DataDom_CloneNode = "This type of node cannot be cloned: {0}.";

	public const string DataDom_MultipleLoad = "Cannot load XmlDataDocument if it already contains data. Please use a new XmlDataDocument.";

	public const string DataDom_MultipleDataSet = "DataSet can be associated with at most one XmlDataDocument. Cannot associate the DataSet with the current XmlDataDocument because the DataSet is already associated with another XmlDataDocument.";

	public const string DataDom_NotSupport_GetElementById = "GetElementById() is not supported on DataDocument.";

	public const string DataDom_NotSupport_EntRef = "Cannot create entity references on DataDocument.";

	public const string DataDom_NotSupport_Clear = "Clear function on DateSet and DataTable is not supported on XmlDataDocument.";

	public const string ADP_EmptyArray = "Expecting non-empty array for '{0}' parameter.";

	public const string SQL_WrongType = "Expecting argument of type {1}, but received type {0}.";

	public const string ADP_InvalidConnectionOptionValue = "Invalid value for key '{0}'.";

	public const string ADP_KeywordNotSupported = "Keyword not supported: '{0}'.";

	public const string ADP_InternalProviderError = "Internal .Net Framework Data Provider error {0}.";

	public const string ADP_NoQuoteChange = "The QuotePrefix and QuoteSuffix properties cannot be changed once an Insert, Update, or Delete command has been generated.";

	public const string ADP_MissingSourceCommand = "The DataAdapter.SelectCommand property needs to be initialized.";

	public const string ADP_MissingSourceCommandConnection = "The DataAdapter.SelectCommand.Connection property needs to be initialized;";

	public const string ADP_InvalidMultipartName = "{0} \"{1}\".";

	public const string ADP_InvalidMultipartNameQuoteUsage = "{0} \"{1}\", incorrect usage of quotes.";

	public const string ADP_InvalidMultipartNameToManyParts = "{0} \"{1}\", the current limit of \"{2}\" is insufficient.";

	public const string ADP_ColumnSchemaExpression = "The column mapping from SourceColumn '{0}' failed because the DataColumn '{1}' is a computed column.";

	public const string ADP_ColumnSchemaMismatch = "Inconvertible type mismatch between SourceColumn '{0}' of {1} and the DataColumn '{2}' of {3}.";

	public const string ADP_ColumnSchemaMissing1 = "Missing the DataColumn '{0}' for the SourceColumn '{2}'.";

	public const string ADP_ColumnSchemaMissing2 = "Missing the DataColumn '{0}' in the DataTable '{1}' for the SourceColumn '{2}'.";

	public const string ADP_InvalidSourceColumn = "SourceColumn is required to be a non-empty string.";

	public const string ADP_MissingColumnMapping = "Missing SourceColumn mapping for '{0}'.";

	public const string ADP_NotSupportedEnumerationValue = "The {0} enumeration value, {1}, is not supported by the {2} method.";

	public const string ADP_MissingTableSchema = "Missing the '{0}' DataTable for the '{1}' SourceTable.";

	public const string ADP_InvalidSourceTable = "SourceTable is required to be a non-empty string";

	public const string ADP_MissingTableMapping = "Missing SourceTable mapping: '{0}'";

	public const string ADP_ConnectionRequired_Insert = "Update requires the InsertCommand to have a connection object. The Connection property of the InsertCommand has not been initialized.";

	public const string ADP_ConnectionRequired_Update = "Update requires the UpdateCommand to have a connection object. The Connection property of the UpdateCommand has not been initialized.";

	public const string ADP_ConnectionRequired_Delete = "Update requires the DeleteCommand to have a connection object. The Connection property of the DeleteCommand has not been initialized.";

	public const string ADP_ConnectionRequired_Batch = "Update requires a connection object.  The Connection property has not been initialized.";

	public const string ADP_ConnectionRequired_Clone = "Update requires the command clone to have a connection object. The Connection property of the command clone has not been initialized.";

	public const string ADP_OpenConnectionRequired_Insert = "Update requires the {0}Command to have an open connection object. {1}";

	public const string ADP_OpenConnectionRequired_Update = "Update requires the {0}Command to have an open connection object. {1}";

	public const string ADP_OpenConnectionRequired_Delete = "Update requires the {0}Command to have an open connection object. {1}";

	public const string ADP_OpenConnectionRequired_Clone = "Update requires the updating command to have an open connection object. {1}";

	public const string ADP_MissingSelectCommand = "The SelectCommand property has not been initialized before calling '{0}'.";

	public const string ADP_UnwantedStatementType = "The StatementType {0} is not expected here.";

	public const string ADP_FillSchemaRequiresSourceTableName = "FillSchema: expected a non-empty string for the SourceTable name.";

	public const string ADP_FillRequiresSourceTableName = "Fill: expected a non-empty string for the SourceTable name.";

	public const string ADP_FillChapterAutoIncrement = "Hierarchical chapter columns must map to an AutoIncrement DataColumn.";

	public const string ADP_MissingDataReaderFieldType = "DataReader.GetFieldType({0}) returned null.";

	public const string ADP_OnlyOneTableForStartRecordOrMaxRecords = "Only specify one item in the dataTables array when using non-zero values for startRecords or maxRecords.";

	public const string ADP_UpdateRequiresSourceTable = "Update unable to find TableMapping['{0}'] or DataTable '{0}'.";

	public const string ADP_UpdateRequiresSourceTableName = "Update: expected a non-empty SourceTable name.";

	public const string ADP_UpdateRequiresCommandClone = "Update requires the command clone to be valid.";

	public const string ADP_UpdateRequiresCommandSelect = "Auto SQL generation during Update requires a valid SelectCommand.";

	public const string ADP_UpdateRequiresCommandInsert = "Update requires a valid InsertCommand when passed DataRow collection with new rows.";

	public const string ADP_UpdateRequiresCommandUpdate = "Update requires a valid UpdateCommand when passed DataRow collection with modified rows.";

	public const string ADP_UpdateRequiresCommandDelete = "Update requires a valid DeleteCommand when passed DataRow collection with deleted rows.";

	public const string ADP_UpdateMismatchRowTable = "DataRow[{0}] is from a different DataTable than DataRow[0].";

	public const string ADP_RowUpdatedErrors = "RowUpdatedEvent: Errors occurred; no additional is information available.";

	public const string ADP_RowUpdatingErrors = "RowUpdatingEvent: Errors occurred; no additional is information available.";

	public const string ADP_ResultsNotAllowedDuringBatch = "When batching, the command's UpdatedRowSource property value of UpdateRowSource.FirstReturnedRecord or UpdateRowSource.Both is invalid.";

	public const string ADP_UpdateConcurrencyViolation_Update = "Concurrency violation: the UpdateCommand affected {0} of the expected {1} records.";

	public const string ADP_UpdateConcurrencyViolation_Delete = "Concurrency violation: the DeleteCommand affected {0} of the expected {1} records.";

	public const string ADP_UpdateConcurrencyViolation_Batch = "Concurrency violation: the batched command affected {0} of the expected {1} records.";

	public const string ADP_InvalidSourceBufferIndex = "Invalid source buffer (size of {0}) offset: {1}";

	public const string ADP_InvalidDestinationBufferIndex = "Invalid destination buffer (size of {0}) offset: {1}";

	public const string ADP_StreamClosed = "Invalid attempt to {0} when stream is closed.";

	public const string ADP_InvalidSeekOrigin = "Specified SeekOrigin value is invalid.";

	public const string ADP_DynamicSQLJoinUnsupported = "Dynamic SQL generation is not supported against multiple base tables.";

	public const string ADP_DynamicSQLNoTableInfo = "Dynamic SQL generation is not supported against a SelectCommand that does not return any base table information.";

	public const string ADP_DynamicSQLNoKeyInfoDelete = "Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.";

	public const string ADP_DynamicSQLNoKeyInfoUpdate = "Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.";

	public const string ADP_DynamicSQLNoKeyInfoRowVersionDelete = "Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not contain a row version column.";

	public const string ADP_DynamicSQLNoKeyInfoRowVersionUpdate = "Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not contain a row version column.";

	public const string ADP_DynamicSQLNestedQuote = "Dynamic SQL generation not supported against table names '{0}' that contain the QuotePrefix or QuoteSuffix character '{1}'.";

	public const string SQL_InvalidBufferSizeOrIndex = "Buffer offset '{1}' plus the bytes available '{0}' is greater than the length of the passed in buffer.";

	public const string SQL_InvalidDataLength = "Data length '{0}' is less than 0.";

	public const string SqlMisc_NullString = "Null";

	public const string SqlMisc_MessageString = "Message";

	public const string SqlMisc_ArithOverflowMessage = "Arithmetic Overflow.";

	public const string SqlMisc_DivideByZeroMessage = "Divide by zero error encountered.";

	public const string SqlMisc_NullValueMessage = "Data is Null. This method or property cannot be called on Null values.";

	public const string SqlMisc_TruncationMessage = "Numeric arithmetic causes truncation.";

	public const string SqlMisc_DateTimeOverflowMessage = "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59

BepInEx/core/System.Diagnostics.DiagnosticSource.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using FxResources.System.Diagnostics.DiagnosticSource;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Diagnostics.DiagnosticSource")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides Classes that allow you to decouple code logging rich (unserializable) diagnostics/telemetry (e.g. framework) from code that consumes it (e.g. tools)\r\n\r\nCommonly Used Types:\r\nSystem.Diagnostics.DiagnosticListener\r\nSystem.Diagnostics.DiagnosticSource")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Diagnostics.DiagnosticSource")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("10.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.System.Diagnostics.DiagnosticSource
{
	internal static class SR
	{
	}
}
namespace Internal
{
	internal static class PaddingHelpers
	{
		internal const int CACHE_LINE_SIZE = 128;
	}
	[StructLayout(LayoutKind.Explicit, Size = 124)]
	internal struct PaddingFor32
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		private ref struct SpanCasingPair
		{
			public ReadOnlySpan<byte> Bytes { get; set; }

			public Casing Casing { get; set; }
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf8(ReadOnlySpan<byte> source, Span<byte> utf8Destination, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < source.Length; i++)
			{
				ToBytesBuffer(source[i], utf8Destination, i * 2, casing);
			}
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> source, Span<char> destination, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < source.Length; i++)
			{
				ToCharsBuffer(source[i], destination, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf8(ReadOnlySpan<byte> utf8Source, Span<byte> destination, out int bytesProcessed)
		{
			return TryDecodeFromUtf8_Scalar(utf8Source, destination, out bytesProcessed);
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> source, Span<byte> destination, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(source, destination, out charsProcessed);
		}

		private static bool TryDecodeFromUtf8_Scalar(ReadOnlySpan<byte> utf8Source, Span<byte> destination, out int bytesProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < destination.Length)
			{
				num3 = FromChar(utf8Source[num + 1]);
				num4 = FromChar(utf8Source[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				destination[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			bytesProcessed = num;
			return (num3 | num4) != 255;
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> source, Span<byte> destination, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < destination.Length)
			{
				num3 = FromChar(source[num + 1]);
				num4 = FromChar(source[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				destination[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ActivityIdFormatInvalid => GetResourceString("ActivityIdFormatInvalid");

		internal static string ActivityNotRunning => GetResourceString("ActivityNotRunning");

		internal static string ActivityNotStarted => GetResourceString("ActivityNotStarted");

		internal static string ActivityStartAlreadyStarted => GetResourceString("ActivityStartAlreadyStarted");

		internal static string ActivitySetParentAlreadyStarted => GetResourceString("ActivitySetParentAlreadyStarted");

		internal static string EndTimeNotUtc => GetResourceString("EndTimeNotUtc");

		internal static string OperationNameInvalid => GetResourceString("OperationNameInvalid");

		internal static string ParentIdAlreadySet => GetResourceString("ParentIdAlreadySet");

		internal static string ParentIdInvalid => GetResourceString("ParentIdInvalid");

		internal static string SetFormatOnStartedActivity => GetResourceString("SetFormatOnStartedActivity");

		internal static string SetParentIdOnActivityWithParent => GetResourceString("SetParentIdOnActivityWithParent");

		internal static string StartTimeNotUtc => GetResourceString("StartTimeNotUtc");

		internal static string KeyAlreadyExist => GetResourceString("KeyAlreadyExist");

		internal static string InvalidTraceParent => GetResourceString("InvalidTraceParent");

		internal static string UnableAccessServicePointTable => GetResourceString("UnableAccessServicePointTable");

		internal static string UnableToInitialize => GetResourceString("UnableToInitialize");

		internal static string UnsupportedType => GetResourceString("UnsupportedType");

		internal static string Arg_BufferTooSmall => GetResourceString("Arg_BufferTooSmall");

		internal static string InvalidInstrumentType => GetResourceString("InvalidInstrumentType");

		internal static string InvalidHistogramExplicitBucketBoundaries => GetResourceString("InvalidHistogramExplicitBucketBoundaries");

		internal static string InvalidHistogramScale => GetResourceString("InvalidHistogramScale");

		internal static string InvalidHistogramMaxBuckets => GetResourceString("InvalidHistogramMaxBuckets");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Runtime.Versioning
{
	internal abstract class OSPlatformAttribute : Attribute
	{
		public string PlatformName { get; }

		private protected OSPlatformAttribute(string platformName)
		{
			PlatformName = platformName;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
	internal sealed class TargetPlatformAttribute : OSPlatformAttribute
	{
		public TargetPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public string Message { get; }

		public UnsupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}

		public UnsupportedOSPlatformAttribute(string platformName, string message)
			: base(platformName)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public ObsoletedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}

		public ObsoletedOSPlatformAttribute(string platformName, string message)
			: base(platformName)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public UnsupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class, Inherited = false)]
	internal sealed class CompilerLoweringPreserveAttribute : Attribute
	{
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	internal static class IsExternalInit
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace System.Diagnostics
{
	public readonly struct ActivityChangedEventArgs
	{
		public Activity? Previous { get; init; }

		public Activity? Current { get; init; }

		internal ActivityChangedEventArgs(Activity previous, Activity current)
		{
			Previous = previous;
			Current = current;
		}
	}
	public class Activity : IDisposable
	{
		public struct Enumerator<T>
		{
			private static readonly DiagNode<T> s_Empty = new DiagNode<T>(default(T));

			private DiagNode<T> _nextNode;

			private DiagNode<T> _currentNode;

			public readonly ref T Current => ref _currentNode.Value;

			internal Enumerator(DiagNode<T> head)
			{
				_nextNode = head;
				_currentNode = s_Empty;
			}

			[EditorBrowsable(EditorBrowsableState.Never)]
			public readonly Enumerator<T> GetEnumerator()
			{
				return this;
			}

			public bool MoveNext()
			{
				if (_nextNode == null)
				{
					_currentNode = s_Empty;
					return false;
				}
				_currentNode = _nextNode;
				_nextNode = _nextNode.Next;
				return true;
			}
		}

		private sealed class BaggageLinkedList : IEnumerable<KeyValuePair<string, string>>, IEnumerable
		{
			private DiagNode<KeyValuePair<string, string>> _first;

			public DiagNode<KeyValuePair<string, string>> First => _first;

			public BaggageLinkedList(KeyValuePair<string, string> firstValue, bool set = false)
			{
				_first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, string>>(firstValue));
			}

			public void Add(KeyValuePair<string, string> value)
			{
				DiagNode<KeyValuePair<string, string>> diagNode = new DiagNode<KeyValuePair<string, string>>(value);
				lock (this)
				{
					diagNode.Next = _first;
					_first = diagNode;
				}
			}

			public void Set(KeyValuePair<string, string> value)
			{
				if (value.Value == null)
				{
					Remove(value.Key);
					return;
				}
				lock (this)
				{
					for (DiagNode<KeyValuePair<string, string>> diagNode = _first; diagNode != null; diagNode = diagNode.Next)
					{
						if (diagNode.Value.Key == value.Key)
						{
							diagNode.Value = value;
							return;
						}
					}
					DiagNode<KeyValuePair<string, string>> diagNode2 = new DiagNode<KeyValuePair<string, string>>(value);
					diagNode2.Next = _first;
					_first = diagNode2;
				}
			}

			public void Remove(string key)
			{
				lock (this)
				{
					if (_first == null)
					{
						return;
					}
					if (_first.Value.Key == key)
					{
						_first = _first.Next;
						return;
					}
					DiagNode<KeyValuePair<string, string>> diagNode = _first;
					while (diagNode.Next != null)
					{
						if (diagNode.Next.Value.Key == key)
						{
							diagNode.Next = diagNode.Next.Next;
							break;
						}
						diagNode = diagNode.Next;
					}
				}
			}

			public DiagEnumerator<KeyValuePair<string, string>> GetEnumerator()
			{
				return new DiagEnumerator<KeyValuePair<string, string>>(_first);
			}

			IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()
			{
				return GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}
		}

		internal sealed class TagsLinkedList : IEnumerable<KeyValuePair<string, object>>, IEnumerable
		{
			[CompilerGenerated]
			private sealed class <EnumerateStringValues>d__16 : IEnumerable<KeyValuePair<string, string>>, IEnumerable, IEnumerator<KeyValuePair<string, string>>, IEnumerator, IDisposable
			{
				private int <>1__state;

				private KeyValuePair<string, string> <>2__current;

				private int <>l__initialThreadId;

				public TagsLinkedList <>4__this;

				private DiagNode<KeyValuePair<string, object>> <current>5__2;

				KeyValuePair<string, string> IEnumerator<KeyValuePair<string, string>>.Current
				{
					[DebuggerHidden]
					get
					{
						return <>2__current;
					}
				}

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

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

				[DebuggerHidden]
				void IDisposable.Dispose()
				{
					<current>5__2 = null;
					<>1__state = -2;
				}

				private bool MoveNext()
				{
					int num = <>1__state;
					TagsLinkedList tagsLinkedList = <>4__this;
					if (num != 0)
					{
						if (num != 1)
						{
							return false;
						}
						<>1__state = -1;
						goto IL_0095;
					}
					<>1__state = -1;
					<current>5__2 = tagsLinkedList._first;
					goto IL_00a6;
					IL_0095:
					<current>5__2 = <current>5__2.Next;
					goto IL_00a6;
					IL_00a6:
					if (<current>5__2 != null)
					{
						if (<current>5__2.Value.Value is string || <current>5__2.Value.Value == null)
						{
							<>2__current = new KeyValuePair<string, string>(<current>5__2.Value.Key, (string)<current>5__2.Value.Value);
							<>1__state = 1;
							return true;
						}
						goto IL_0095;
					}
					return false;
				}

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

				[DebuggerHidden]
				void IEnumerator.Reset()
				{
					throw new NotSupportedException();
				}

				[DebuggerHidden]
				IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()
				{
					<EnumerateStringValues>d__16 result;
					if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
					{
						<>1__state = 0;
						result = this;
					}
					else
					{
						result = new <EnumerateStringValues>d__16(0)
						{
							<>4__this = <>4__this
						};
					}
					return result;
				}

				[DebuggerHidden]
				IEnumerator IEnumerable.GetEnumerator()
				{
					return ((IEnumerable<KeyValuePair<string, string>>)this).GetEnumerator();
				}
			}

			private DiagNode<KeyValuePair<string, object>> _first;

			private DiagNode<KeyValuePair<string, object>> _last;

			private StringBuilder _stringBuilder;

			public DiagNode<KeyValuePair<string, object>> First => _first;

			public TagsLinkedList(KeyValuePair<string, object> firstValue, bool set = false)
			{
				_last = (_first = ((set && firstValue.Value == null) ? null : new DiagNode<KeyValuePair<string, object>>(firstValue)));
			}

			public TagsLinkedList(IEnumerator<KeyValuePair<string, object>> e)
			{
				_last = (_first = new DiagNode<KeyValuePair<string, object>>(e.Current));
				while (e.MoveNext())
				{
					_last.Next = new DiagNode<KeyValuePair<string, object>>(e.Current);
					_last = _last.Next;
				}
			}

			public TagsLinkedList(IEnumerable<KeyValuePair<string, object>> list)
			{
				Add(list);
			}

			public void Add(IEnumerable<KeyValuePair<string, object>> list)
			{
				IEnumerator<KeyValuePair<string, object>> enumerator = list.GetEnumerator();
				if (enumerator.MoveNext())
				{
					if (_first == null)
					{
						_last = (_first = new DiagNode<KeyValuePair<string, object>>(enumerator.Current));
					}
					else
					{
						_last.Next = new DiagNode<KeyValuePair<string, object>>(enumerator.Current);
						_last = _last.Next;
					}
					while (enumerator.MoveNext())
					{
						_last.Next = new DiagNode<KeyValuePair<string, object>>(enumerator.Current);
						_last = _last.Next;
					}
				}
			}

			public void Add(KeyValuePair<string, object> value)
			{
				DiagNode<KeyValuePair<string, object>> diagNode = new DiagNode<KeyValuePair<string, object>>(value);
				lock (this)
				{
					if (_first == null)
					{
						_first = (_last = diagNode);
						return;
					}
					_last.Next = diagNode;
					_last = diagNode;
				}
			}

			public object Get(string key)
			{
				for (DiagNode<KeyValuePair<string, object>> diagNode = _first; diagNode != null; diagNode = diagNode.Next)
				{
					if (diagNode.Value.Key == key)
					{
						return diagNode.Value.Value;
					}
				}
				return null;
			}

			public void Remove(string key)
			{
				lock (this)
				{
					if (_first == null)
					{
						return;
					}
					if (_first.Value.Key == key)
					{
						_first = _first.Next;
						if (_first == null)
						{
							_last = null;
						}
						return;
					}
					DiagNode<KeyValuePair<string, object>> diagNode = _first;
					while (diagNode.Next != null)
					{
						if (diagNode.Next.Value.Key == key)
						{
							if (_last == diagNode.Next)
							{
								_last = diagNode;
							}
							diagNode.Next = diagNode.Next.Next;
							break;
						}
						diagNode = diagNode.Next;
					}
				}
			}

			public void Set(KeyValuePair<string, object> value)
			{
				if (value.Value == null)
				{
					Remove(value.Key);
					return;
				}
				lock (this)
				{
					for (DiagNode<KeyValuePair<string, object>> diagNode = _first; diagNode != null; diagNode = diagNode.Next)
					{
						if (diagNode.Value.Key == value.Key)
						{
							diagNode.Value = value;
							return;
						}
					}
					DiagNode<KeyValuePair<string, object>> diagNode2 = new DiagNode<KeyValuePair<string, object>>(value);
					if (_first == null)
					{
						_first = (_last = diagNode2);
						return;
					}
					_last.Next = diagNode2;
					_last = diagNode2;
				}
			}

			public DiagEnumerator<KeyValuePair<string, object>> GetEnumerator()
			{
				return new DiagEnumerator<KeyValuePair<string, object>>(_first);
			}

			IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
			{
				return GetEnumerator();
			}

			IEnumerator IEnumerable.GetEnumerator()
			{
				return GetEnumerator();
			}

			[IteratorStateMachine(typeof(<EnumerateStringValues>d__16))]
			public IEnumerable<KeyValuePair<string, string>> EnumerateStringValues()
			{
				//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
				return new <EnumerateStringValues>d__16(-2)
				{
					<>4__this = this
				};
			}

			public override string ToString()
			{
				lock (this)
				{
					if (_first == null)
					{
						return string.Empty;
					}
					if (_stringBuilder == null)
					{
						_stringBuilder = new StringBuilder();
					}
					_stringBuilder.Append(_first.Value.Key);
					_stringBuilder.Append(':');
					_stringBuilder.Append(_first.Value.Value);
					for (DiagNode<KeyValuePair<string, object>> next = _first.Next; next != null; next = next.Next)
					{
						_stringBuilder.Append(", ");
						_stringBuilder.Append(next.Value.Key);
						_stringBuilder.Append(':');
						_stringBuilder.Append(next.Value.Value);
					}
					string result = _stringBuilder.ToString();
					_stringBuilder.Clear();
					return result;
				}
			}
		}

		[Flags]
		private enum State : byte
		{
			None = 0,
			FormatUnknown = 0,
			FormatHierarchical = 1,
			FormatW3C = 2,
			FormatFlags = 3,
			IsStopped = 0x80
		}

		[CompilerGenerated]
		private sealed class <<get_Baggage>g__Iterate|91_0>d : IEnumerable<KeyValuePair<string, string>>, IEnumerable, IEnumerator<KeyValuePair<string, string>>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private KeyValuePair<string, string> <>2__current;

			private int <>l__initialThreadId;

			private Activity activity;

			public Activity <>3__activity;

			private DiagNode<KeyValuePair<string, string>> <current>5__2;

			KeyValuePair<string, string> IEnumerator<KeyValuePair<string, string>>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

			[DebuggerHidden]
			public <<get_Baggage>g__Iterate|91_0>d(int <>1__state)
			{
				this.<>1__state = <>1__state;
				<>l__initialThreadId = Environment.CurrentManagedThreadId;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<current>5__2 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				int num = <>1__state;
				if (num != 0)
				{
					if (num != 1)
					{
						return false;
					}
					<>1__state = -1;
					<current>5__2 = <current>5__2.Next;
					goto IL_006e;
				}
				<>1__state = -1;
				goto IL_0017;
				IL_0017:
				if (activity._baggage != null)
				{
					<current>5__2 = activity._baggage.First;
					goto IL_006e;
				}
				goto IL_007d;
				IL_007d:
				activity = activity.Parent;
				if (activity == null)
				{
					return false;
				}
				goto IL_0017;
				IL_006e:
				if (<current>5__2 != null)
				{
					<>2__current = <current>5__2.Value;
					<>1__state = 1;
					return true;
				}
				<current>5__2 = null;
				goto IL_007d;
			}

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

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}

			[DebuggerHidden]
			IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()
			{
				<<get_Baggage>g__Iterate|91_0>d <<get_Baggage>g__Iterate|91_0>d;
				if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId)
				{
					<>1__state = 0;
					<<get_Baggage>g__Iterate|91_0>d = this;
				}
				else
				{
					<<get_Baggage>g__Iterate|91_0>d = new <<get_Baggage>g__Iterate|91_0>d(0);
				}
				<<get_Baggage>g__Iterate|91_0>d.activity = <>3__activity;
				return <<get_Baggage>g__Iterate|91_0>d;
			}

			[DebuggerHidden]
			IEnumerator IEnumerable.GetEnumerator()
			{
				return ((IEnumerable<KeyValuePair<string, string>>)this).GetEnumerator();
			}
		}

		private static readonly IEnumerable<KeyValuePair<string, string>> s_emptyBaggageTags = new KeyValuePair<string, string>[0];

		private static readonly IEnumerable<KeyValuePair<string, object>> s_emptyTagObjects = new KeyValuePair<string, object>[0];

		private static readonly IEnumerable<ActivityLink> s_emptyLinks = new DiagLinkedList<ActivityLink>();

		private static readonly IEnumerable<ActivityEvent> s_emptyEvents = new DiagLinkedList<ActivityEvent>();

		private static readonly ActivitySource s_defaultSource = new ActivitySource(string.Empty);

		private static readonly AsyncLocal<Activity> s_current = new AsyncLocal<Activity>();

		private const byte ActivityTraceFlagsIsSet = 128;

		private const int RequestIdMaxLength = 1024;

		private static readonly string s_uniqSuffix = $"-{GetRandomNumber():x}.";

		private static long s_currentRootId = (uint)GetRandomNumber();

		private static ActivityIdFormat s_defaultIdFormat;

		private string _traceState;

		private State _state;

		private int _currentChildId;

		private string _id;

		private string _rootId;

		private string _parentId;

		private string _parentSpanId;

		private string _traceId;

		private string _spanId;

		private byte _w3CIdFlags;

		private byte _parentTraceFlags;

		private TagsLinkedList _tags;

		private BaggageLinkedList _baggage;

		private DiagLinkedList<ActivityLink> _links;

		private DiagLinkedList<ActivityEvent> _events;

		private Dictionary<string, object> _customProperties;

		private string _displayName;

		private ActivityStatusCode _statusCode;

		private string _statusDescription;

		private Activity _previousActiveActivity;

		public static bool ForceDefaultIdFormat { get; set; }

		public ActivityStatusCode Status => _statusCode;

		public string? StatusDescription => _statusDescription;

		public bool HasRemoteParent { get; private set; }

		public static Activity? Current
		{
			get
			{
				return s_current.Value;
			}
			set
			{
				if (ValidateSetCurrent(value))
				{
					SetCurrent(value);
				}
			}
		}

		public ActivityKind Kind { get; private set; }

		public string OperationName { get; }

		public string DisplayName
		{
			get
			{
				return _displayName ?? OperationName;
			}
			set
			{
				_displayName = value ?? throw new ArgumentNullException("value");
			}
		}

		public ActivitySource Source { get; private set; }

		public Activity? Parent { get; private set; }

		public TimeSpan Duration { get; private set; }

		public DateTime StartTimeUtc { get; private set; }

		public string? Id
		{
			get
			{
				if (_id == null && _spanId != null)
				{
					Span<char> buffer = stackalloc char[2];
					System.HexConverter.ToCharsBuffer((byte)(0xFFFFFF7Fu & _w3CIdFlags), buffer, 0, System.HexConverter.Casing.Lower);
					string value = "00-" + _traceId + "-" + _spanId + "-" + buffer;
					Interlocked.CompareExchange(ref _id, value, null);
				}
				return _id;
			}
		}

		public string? ParentId
		{
			get
			{
				if (_parentId == null)
				{
					if (_parentSpanId != null)
					{
						Span<char> buffer = stackalloc char[2];
						System.HexConverter.ToCharsBuffer((byte)(0xFFFFFF7Fu & _parentTraceFlags), buffer, 0, System.HexConverter.Casing.Lower);
						string value = "00-" + _traceId + "-" + _parentSpanId + "-" + buffer;
						Interlocked.CompareExchange(ref _parentId, value, null);
					}
					else if (Parent != null)
					{
						Interlocked.CompareExchange(ref _parentId, Parent.Id, null);
					}
				}
				return _parentId;
			}
		}

		public string? RootId
		{
			get
			{
				if (_rootId == null)
				{
					string text = null;
					if (Id != null)
					{
						text = GetRootId(Id);
					}
					else if (ParentId != null)
					{
						text = GetRootId(ParentId);
					}
					if (text != null)
					{
						Interlocked.CompareExchange(ref _rootId, text, null);
					}
				}
				return _rootId;
			}
		}

		public IEnumerable<KeyValuePair<string, string?>> Tags => _tags?.EnumerateStringValues() ?? s_emptyBaggageTags;

		public IEnumerable<KeyValuePair<string, object?>> TagObjects
		{
			get
			{
				IEnumerable<KeyValuePair<string, object>> tags = _tags;
				return tags ?? s_emptyTagObjects;
			}
		}

		public IEnumerable<ActivityEvent> Events
		{
			get
			{
				IEnumerable<ActivityEvent> events = _events;
				return events ?? s_emptyEvents;
			}
		}

		public IEnumerable<ActivityLink> Links
		{
			get
			{
				IEnumerable<ActivityLink> links = _links;
				return links ?? s_emptyLinks;
			}
		}

		public IEnumerable<KeyValuePair<string, string?>> Baggage
		{
			get
			{
				for (Activity activity2 = this; activity2 != null; activity2 = activity2.Parent)
				{
					if (activity2._baggage != null)
					{
						return Iterate(activity2);
					}
				}
				return s_emptyBaggageTags;
				[IteratorStateMachine(typeof(<<get_Baggage>g__Iterate|91_0>d))]
				static IEnumerable<KeyValuePair<string, string>> Iterate(Activity activity)
				{
					//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
					return new <<get_Baggage>g__Iterate|91_0>d(-2)
					{
						<>3__activity = activity
					};
				}
			}
		}

		public ActivityContext Context => new ActivityContext(TraceId, SpanId, ActivityTraceFlags, TraceStateString);

		public string? TraceStateString
		{
			get
			{
				for (Activity activity = this; activity != null; activity = activity.Parent)
				{
					string traceState = activity._traceState;
					if (traceState != null)
					{
						return traceState;
					}
				}
				return null;
			}
			set
			{
				_traceState = value;
			}
		}

		public ActivitySpanId SpanId
		{
			get
			{
				if (_spanId == null && _id != null && IdFormat == ActivityIdFormat.W3C)
				{
					string value = ActivitySpanId.CreateFromString(_id.AsSpan(36, 16)).ToHexString();
					Interlocked.CompareExchange(ref _spanId, value, null);
				}
				return new ActivitySpanId(_spanId);
			}
		}

		public ActivityTraceId TraceId
		{
			get
			{
				if (_traceId == null)
				{
					TrySetTraceIdFromParent();
				}
				return new ActivityTraceId(_traceId);
			}
		}

		public bool Recorded => (ActivityTraceFlags & ActivityTraceFlags.Recorded) != 0;

		public bool IsAllDataRequested { get; set; }

		public ActivityTraceFlags ActivityTraceFlags
		{
			get
			{
				if (!W3CIdFlagsSet)
				{
					TrySetTraceFlagsFromParent();
				}
				return (ActivityTraceFlags)(-129 & (int)_w3CIdFlags);
			}
			set
			{
				_w3CIdFlags = (byte)(0x80u | (byte)value);
			}
		}

		public ActivitySpanId ParentSpanId
		{
			get
			{
				if (_parentSpanId == null)
				{
					string text = null;
					if (_parentId != null && IsW3CId(_parentId))
					{
						try
						{
							text = ActivitySpanId.CreateFromString(_parentId.AsSpan(36, 16)).ToHexString();
						}
						catch
						{
						}
					}
					else if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C)
					{
						text = Parent.SpanId.ToHexString();
					}
					if (text != null)
					{
						Interlocked.CompareExchange(ref _parentSpanId, text, null);
					}
				}
				return new ActivitySpanId(_parentSpanId);
			}
		}

		public static Func<ActivityTraceId>? TraceIdGenerator { get; set; }

		public static ActivityIdFormat DefaultIdFormat
		{
			get
			{
				if (s_defaultIdFormat == ActivityIdFormat.Unknown)
				{
					s_defaultIdFormat = ActivityIdFormat.Hierarchical;
				}
				return s_defaultIdFormat;
			}
			set
			{
				if (ActivityIdFormat.Hierarchical > value || value > ActivityIdFormat.W3C)
				{
					throw new ArgumentException(System.SR.ActivityIdFormatInvalid);
				}
				s_defaultIdFormat = value;
			}
		}

		private bool W3CIdFlagsSet => (_w3CIdFlags & 0x80) != 0;

		public bool IsStopped
		{
			get
			{
				return (_state & State.IsStopped) != 0;
			}
			private set
			{
				if (value)
				{
					_state |= State.IsStopped;
				}
				else
				{
					_state &= ~State.IsStopped;
				}
			}
		}

		public ActivityIdFormat IdFormat
		{
			get
			{
				return (ActivityIdFormat)(_state & State.FormatFlags);
			}
			private set
			{
				_state = (_state & ~State.FormatFlags) | (State)((byte)value & 3u);
			}
		}

		public static event EventHandler<ActivityChangedEventArgs>? CurrentChanged;

		public Activity SetStatus(ActivityStatusCode code, string? description = null)
		{
			_statusCode = code;
			_statusDescription = ((code == ActivityStatusCode.Error) ? description : null);
			return this;
		}

		public Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects()
		{
			return new Enumerator<KeyValuePair<string, object>>(_tags?.First);
		}

		public Enumerator<ActivityEvent> EnumerateEvents()
		{
			return new Enumerator<ActivityEvent>(_events?.First);
		}

		public Enumerator<ActivityLink> EnumerateLinks()
		{
			return new Enumerator<ActivityLink>(_links?.First);
		}

		public string? GetBaggageItem(string key)
		{
			foreach (KeyValuePair<string, string> item in Baggage)
			{
				if (key == item.Key)
				{
					return item.Value;
				}
			}
			return null;
		}

		public object? GetTagItem(string key)
		{
			return _tags?.Get(key) ?? null;
		}

		public Activity(string operationName)
		{
			Source = s_defaultSource;
			IsAllDataRequested = true;
			if (string.IsNullOrEmpty(operationName))
			{
				NotifyError(new ArgumentException(System.SR.OperationNameInvalid));
			}
			OperationName = operationName ?? string.Empty;
		}

		public Activity AddTag(string key, string? value)
		{
			return AddTag(key, (object?)value);
		}

		public Activity AddTag(string key, object? value)
		{
			KeyValuePair<string, object> keyValuePair = new KeyValuePair<string, object>(key, value);
			if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(keyValuePair), null) != null)
			{
				_tags.Add(keyValuePair);
			}
			return this;
		}

		public Activity SetTag(string key, object? value)
		{
			KeyValuePair<string, object> keyValuePair = new KeyValuePair<string, object>(key, value);
			if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(keyValuePair, set: true), null) != null)
			{
				_tags.Set(keyValuePair);
			}
			return this;
		}

		public Activity AddEvent(ActivityEvent e)
		{
			if (_events != null || Interlocked.CompareExchange(ref _events, new DiagLinkedList<ActivityEvent>(e), null) != null)
			{
				_events.Add(e);
			}
			return this;
		}

		public Activity AddException(Exception exception, in TagList tags = default(TagList), DateTimeOffset timestamp = default(DateTimeOffset))
		{
			ExceptionPolyfills.ThrowIfNull(exception, "exception");
			TagList tags2 = tags;
			Source.NotifyActivityAddException(this, exception, ref tags2);
			bool flag = false;
			bool flag2 = false;
			bool flag3 = false;
			for (int i = 0; i < tags2.Count; i++)
			{
				if (tags2[i].Key == "exception.message")
				{
					flag = true;
				}
				else if (tags2[i].Key == "exception.stacktrace")
				{
					flag2 = true;
				}
				else if (tags2[i].Key == "exception.type")
				{
					flag3 = true;
				}
			}
			if (!flag)
			{
				tags2.Add(new KeyValuePair<string, object>("exception.message", exception.Message));
			}
			if (!flag2)
			{
				tags2.Add(new KeyValuePair<string, object>("exception.stacktrace", exception.ToString()));
			}
			if (!flag3)
			{
				tags2.Add(new KeyValuePair<string, object>("exception.type", exception.GetType().ToString()));
			}
			return AddEvent(new ActivityEvent("exception", timestamp, ref tags2));
		}

		public Activity AddLink(ActivityLink link)
		{
			if (_links != null || Interlocked.CompareExchange(ref _links, new DiagLinkedList<ActivityLink>(link), null) != null)
			{
				_links.Add(link);
			}
			return this;
		}

		public Activity AddBaggage(string key, string? value)
		{
			KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(key, value);
			if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(keyValuePair), null) != null)
			{
				_baggage.Add(keyValuePair);
			}
			return this;
		}

		public Activity SetBaggage(string key, string? value)
		{
			KeyValuePair<string, string> keyValuePair = new KeyValuePair<string, string>(key, value);
			if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(keyValuePair, set: true), null) != null)
			{
				_baggage.Set(keyValuePair);
			}
			return this;
		}

		public Activity SetParentId(string parentId)
		{
			if (_id != null || _spanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ActivitySetParentAlreadyStarted));
			}
			else if (Parent != null)
			{
				NotifyError(new InvalidOperationException(System.SR.SetParentIdOnActivityWithParent));
			}
			else if (ParentId != null || _parentSpanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ParentIdAlreadySet));
			}
			else if (string.IsNullOrEmpty(parentId))
			{
				NotifyError(new ArgumentException(System.SR.ParentIdInvalid));
			}
			else
			{
				_parentId = parentId;
			}
			return this;
		}

		public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags activityTraceFlags = ActivityTraceFlags.None)
		{
			if (_id != null || _spanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ActivitySetParentAlreadyStarted));
			}
			else if (Parent != null)
			{
				NotifyError(new InvalidOperationException(System.SR.SetParentIdOnActivityWithParent));
			}
			else if (ParentId != null || _parentSpanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ParentIdAlreadySet));
			}
			else
			{
				_traceId = traceId.ToHexString();
				_parentSpanId = spanId.ToHexString();
				ActivityTraceFlags = activityTraceFlags;
				_parentTraceFlags = (byte)activityTraceFlags;
			}
			return this;
		}

		public Activity SetStartTime(DateTime startTimeUtc)
		{
			if (startTimeUtc.Kind != DateTimeKind.Utc)
			{
				NotifyError(new InvalidOperationException(System.SR.StartTimeNotUtc));
			}
			else
			{
				StartTimeUtc = startTimeUtc;
			}
			return this;
		}

		public Activity SetEndTime(DateTime endTimeUtc)
		{
			if (endTimeUtc.Kind != DateTimeKind.Utc)
			{
				NotifyError(new InvalidOperationException(System.SR.EndTimeNotUtc));
			}
			else
			{
				Duration = endTimeUtc - StartTimeUtc;
				if (Duration.Ticks <= 0)
				{
					Duration = new TimeSpan(1L);
				}
			}
			return this;
		}

		public Activity Start()
		{
			if (_id != null || _spanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.ActivityStartAlreadyStarted));
			}
			else
			{
				_previousActiveActivity = Current;
				if (_parentId == null && _parentSpanId == null && _previousActiveActivity != null)
				{
					Parent = _previousActiveActivity;
				}
				if (StartTimeUtc == default(DateTime))
				{
					StartTimeUtc = GetUtcNow();
				}
				if (IdFormat == ActivityIdFormat.Unknown)
				{
					IdFormat = (ForceDefaultIdFormat ? DefaultIdFormat : ((Parent != null) ? Parent.IdFormat : ((_parentSpanId != null) ? ActivityIdFormat.W3C : ((_parentId == null) ? DefaultIdFormat : ((!IsW3CId(_parentId)) ? ActivityIdFormat.Hierarchical : ActivityIdFormat.W3C)))));
				}
				if (IdFormat == ActivityIdFormat.W3C)
				{
					GenerateW3CId();
				}
				else
				{
					_id = GenerateHierarchicalId();
				}
				SetCurrent(this);
				Source.NotifyActivityStart(this);
			}
			return this;
		}

		public void Stop()
		{
			if (_id == null && _spanId == null)
			{
				NotifyError(new InvalidOperationException(System.SR.ActivityNotStarted));
			}
			else if (!IsStopped)
			{
				IsStopped = true;
				if (Duration == TimeSpan.Zero)
				{
					SetEndTime(GetUtcNow());
				}
				Source.NotifyActivityStop(this);
				SetCurrent(_previousActiveActivity);
			}
		}

		public Activity SetIdFormat(ActivityIdFormat format)
		{
			if (_id != null || _spanId != null)
			{
				NotifyError(new InvalidOperationException(System.SR.SetFormatOnStartedActivity));
			}
			else
			{
				IdFormat = format;
			}
			return this;
		}

		private static bool IsW3CId(string id)
		{
			if (id.Length == 55 && (('0' <= id[0] && id[0] <= '9') || ('a' <= id[0] && id[0] <= 'f')) && (('0' <= id[1] && id[1] <= '9') || ('a' <= id[1] && id[1] <= 'f')))
			{
				if (id[0] == 'f')
				{
					return id[1] != 'f';
				}
				return true;
			}
			return false;
		}

		internal static bool TryConvertIdToContext(string traceParent, string traceState, bool isRemote, out ActivityContext context)
		{
			context = default(ActivityContext);
			if (!IsW3CId(traceParent))
			{
				return false;
			}
			ReadOnlySpan<char> idData = traceParent.AsSpan(3, 32);
			ReadOnlySpan<char> idData2 = traceParent.AsSpan(36, 16);
			if (!ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData) || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData2) || !System.HexConverter.IsHexLowerChar(traceParent[53]) || !System.HexConverter.IsHexLowerChar(traceParent[54]))
			{
				return false;
			}
			context = new ActivityContext(new ActivityTraceId(idData.ToString()), new ActivitySpanId(idData2.ToString()), (ActivityTraceFlags)ActivityTraceId.HexByteFromChars(traceParent[53], traceParent[54]), traceState, isRemote);
			return true;
		}

		public void Dispose()
		{
			if (!IsStopped)
			{
				Stop();
			}
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
		}

		public void SetCustomProperty(string propertyName, object? propertyValue)
		{
			if (_customProperties == null)
			{
				Interlocked.CompareExchange(ref _customProperties, new Dictionary<string, object>(), null);
			}
			lock (_customProperties)
			{
				if (propertyValue == null)
				{
					_customProperties.Remove(propertyName);
				}
				else
				{
					_customProperties[propertyName] = propertyValue;
				}
			}
		}

		public object? GetCustomProperty(string propertyName)
		{
			if (_customProperties == null)
			{
				return null;
			}
			lock (_customProperties)
			{
				object value;
				return _customProperties.TryGetValue(propertyName, out value) ? value : null;
			}
		}

		internal static Activity Create(ActivitySource source, string name, ActivityKind kind, string parentId, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, DateTimeOffset startTime, ActivityTagsCollection samplerTags, ActivitySamplingResult request, bool startIt, ActivityIdFormat idFormat, string traceState)
		{
			Activity activity = new Activity(name);
			activity.Source = source;
			activity.Kind = kind;
			activity.IdFormat = idFormat;
			activity._traceState = traceState;
			if (links != null)
			{
				using IEnumerator<ActivityLink> enumerator = links.GetEnumerator();
				if (enumerator.MoveNext())
				{
					activity._links = new DiagLinkedList<ActivityLink>(enumerator);
				}
			}
			if (tags != null)
			{
				using IEnumerator<KeyValuePair<string, object>> enumerator2 = tags.GetEnumerator();
				if (enumerator2.MoveNext())
				{
					activity._tags = new TagsLinkedList(enumerator2);
				}
			}
			if (samplerTags != null)
			{
				if (activity._tags == null)
				{
					activity._tags = new TagsLinkedList(samplerTags);
				}
				else
				{
					activity._tags.Add(samplerTags);
				}
			}
			if (parentId != null)
			{
				activity._parentId = parentId;
			}
			else if (parentContext != default(ActivityContext))
			{
				activity._traceId = parentContext.TraceId.ToString();
				if (parentContext.SpanId != default(ActivitySpanId))
				{
					activity._parentSpanId = parentContext.SpanId.ToString();
				}
				activity.ActivityTraceFlags = parentContext.TraceFlags & ~ActivityTraceFlags.Recorded;
				activity._parentTraceFlags = (byte)parentContext.TraceFlags;
				activity.HasRemoteParent = parentContext.IsRemote;
			}
			activity.IsAllDataRequested = request == ActivitySamplingResult.AllData || request == ActivitySamplingResult.AllDataAndRecorded;
			if (request == ActivitySamplingResult.AllDataAndRecorded)
			{
				activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded;
			}
			if (startTime != default(DateTimeOffset))
			{
				activity.StartTimeUtc = startTime.UtcDateTime;
			}
			if (startIt)
			{
				activity.Start();
			}
			return activity;
		}

		private static void SetCurrent(Activity activity)
		{
			EventHandler<ActivityChangedEventArgs> currentChanged = Activity.CurrentChanged;
			if (currentChanged == null)
			{
				s_current.Value = activity;
				return;
			}
			Activity value = s_current.Value;
			s_current.Value = activity;
			currentChanged(null, new ActivityChangedEventArgs(value, activity));
		}

		private void GenerateW3CId()
		{
			if (_traceId == null && !TrySetTraceIdFromParent())
			{
				_traceId = (TraceIdGenerator?.Invoke() ?? ActivityTraceId.CreateRandom()).ToHexString();
			}
			if (!W3CIdFlagsSet)
			{
				TrySetTraceFlagsFromParent();
			}
			_spanId = ActivitySpanId.CreateRandom().ToHexString();
		}

		private static void NotifyError(Exception exception)
		{
			try
			{
				throw exception;
			}
			catch
			{
			}
		}

		private string GenerateHierarchicalId()
		{
			if (Parent != null)
			{
				return AppendSuffix(Parent.Id, Interlocked.Increment(ref Parent._currentChildId).ToString(), '.');
			}
			if (ParentId != null)
			{
				string text = ((ParentId[0] == '|') ? ParentId : ("|" + ParentId));
				char c = text[text.Length - 1];
				if (c != '.' && c != '_')
				{
					text += ".";
				}
				return AppendSuffix(text, Interlocked.Increment(ref s_currentRootId).ToString("x"), '_');
			}
			return GenerateRootId();
		}

		private string GetRootId(string id)
		{
			if (IdFormat == ActivityIdFormat.W3C)
			{
				return id.Substring(3, 32);
			}
			int num = id.IndexOf('.');
			if (num < 0)
			{
				num = id.Length;
			}
			int num2 = ((id[0] == '|') ? 1 : 0);
			return id.Substring(num2, num - num2);
		}

		private string AppendSuffix(string parentId, string suffix, char delimiter)
		{
			if (parentId.Length + suffix.Length < 1024)
			{
				return parentId + suffix + delimiter;
			}
			int num = 1015;
			while (num > 1 && parentId[num - 1] != '.' && parentId[num - 1] != '_')
			{
				num--;
			}
			if (num == 1)
			{
				return GenerateRootId();
			}
			string text = ((int)GetRandomNumber()).ToString("x8");
			return parentId.Substring(0, num) + text + "#";
		}

		private unsafe static long GetRandomNumber()
		{
			Guid guid = Guid.NewGuid();
			return *(long*)(&guid);
		}

		private static bool ValidateSetCurrent(Activity activity)
		{
			int num;
			if (activity != null)
			{
				if (activity.Id != null)
				{
					num = ((!activity.IsStopped) ? 1 : 0);
					if (num != 0)
					{
						goto IL_002c;
					}
				}
				else
				{
					num = 0;
				}
				NotifyError(new InvalidOperationException(System.SR.ActivityNotRunning));
			}
			else
			{
				num = 1;
			}
			goto IL_002c;
			IL_002c:
			return (byte)num != 0;
		}

		private bool TrySetTraceIdFromParent()
		{
			if (Parent != null && Parent.IdFormat == ActivityIdFormat.W3C)
			{
				_traceId = Parent.TraceId.ToHexString();
			}
			else if (_parentId != null && IsW3CId(_parentId))
			{
				try
				{
					_traceId = ActivityTraceId.CreateFromString(_parentId.AsSpan(3, 32)).ToHexString();
				}
				catch
				{
				}
			}
			return _traceId != null;
		}

		private void TrySetTraceFlagsFromParent()
		{
			if (W3CIdFlagsSet)
			{
				return;
			}
			if (Parent != null)
			{
				ActivityTraceFlags = Parent.ActivityTraceFlags;
			}
			else if (_parentId != null && IsW3CId(_parentId))
			{
				if (System.HexConverter.IsHexLowerChar(_parentId[53]) && System.HexConverter.IsHexLowerChar(_parentId[54]))
				{
					_w3CIdFlags = (byte)(ActivityTraceId.HexByteFromChars(_parentId[53], _parentId[54]) | 0x80u);
				}
				else
				{
					_w3CIdFlags = 128;
				}
			}
		}

		private static string GenerateRootId()
		{
			return $"|{Interlocked.Increment(ref s_currentRootId):x}{s_uniqSuffix}";
		}

		internal static DateTime GetUtcNow()
		{
			return DateTime.UtcNow;
		}
	}
	[Flags]
	public enum ActivityTraceFlags
	{
		None = 0,
		Recorded = 1
	}
	public enum ActivityIdFormat
	{
		Unknown,
		Hierarchical,
		W3C
	}
	public readonly struct ActivityTraceId : IEquatable<ActivityTraceId>
	{
		private readonly string _hexString;

		internal ActivityTraceId(string hexString)
		{
			_hexString = hexString;
		}

		public static ActivityTraceId CreateRandom()
		{
			Span<byte> obj = stackalloc byte[16];
			SetToRandomBytes(obj);
			return CreateFromBytes(obj);
		}

		public static ActivityTraceId CreateFromBytes(ReadOnlySpan<byte> idData)
		{
			if (idData.Length != 16)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return new ActivityTraceId(System.HexConverter.ToString(idData, System.HexConverter.Casing.Lower));
		}

		public static ActivityTraceId CreateFromUtf8String(ReadOnlySpan<byte> idData)
		{
			return new ActivityTraceId(idData);
		}

		public static ActivityTraceId CreateFromString(ReadOnlySpan<char> idData)
		{
			if (idData.Length != 32 || !IsLowerCaseHexAndNotAllZeros(idData))
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return new ActivityTraceId(idData.ToString());
		}

		public string ToHexString()
		{
			return _hexString ?? "00000000000000000000000000000000";
		}

		public override string ToString()
		{
			return ToHexString();
		}

		public static bool operator ==(ActivityTraceId traceId1, ActivityTraceId traceId2)
		{
			return traceId1._hexString == traceId2._hexString;
		}

		public static bool operator !=(ActivityTraceId traceId1, ActivityTraceId traceId2)
		{
			return traceId1._hexString != traceId2._hexString;
		}

		public bool Equals(ActivityTraceId traceId)
		{
			return _hexString == traceId._hexString;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ActivityTraceId activityTraceId)
			{
				return _hexString == activityTraceId._hexString;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return ToHexString().GetHashCode();
		}

		private ActivityTraceId(ReadOnlySpan<byte> idData)
		{
			if (idData.Length != 32)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			Span<ulong> span = stackalloc ulong[2];
			if (!Utf8Parser.TryParse(idData.Slice(0, 16), out span[0], out int bytesConsumed, 'x'))
			{
				_hexString = CreateRandom()._hexString;
				return;
			}
			if (!Utf8Parser.TryParse(idData.Slice(16, 16), out span[1], out bytesConsumed, 'x'))
			{
				_hexString = CreateRandom()._hexString;
				return;
			}
			if (BitConverter.IsLittleEndian)
			{
				span[0] = BinaryPrimitives.ReverseEndianness(span[0]);
				span[1] = BinaryPrimitives.ReverseEndianness(span[1]);
			}
			_hexString = System.HexConverter.ToString(MemoryMarshal.AsBytes(span), System.HexConverter.Casing.Lower);
		}

		public void CopyTo(Span<byte> destination)
		{
			SetSpanFromHexChars(ToHexString().AsSpan(), destination);
		}

		internal static void SetToRandomBytes(Span<byte> outBytes)
		{
			RandomNumberGenerator current = RandomNumberGenerator.Current;
			Unsafe.WriteUnaligned(ref outBytes[0], current.Next());
			if (outBytes.Length == 16)
			{
				Unsafe.WriteUnaligned(ref outBytes[8], current.Next());
			}
		}

		internal static void SetSpanFromHexChars(ReadOnlySpan<char> charData, Span<byte> outBytes)
		{
			for (int i = 0; i < outBytes.Length; i++)
			{
				outBytes[i] = HexByteFromChars(charData[i * 2], charData[i * 2 + 1]);
			}
		}

		internal static byte HexByteFromChars(char char1, char char2)
		{
			int num = System.HexConverter.FromLowerChar(char1);
			int num2 = System.HexConverter.FromLowerChar(char2);
			if ((num | num2) == 255)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return (byte)((num << 4) | num2);
		}

		internal static bool IsLowerCaseHexAndNotAllZeros(ReadOnlySpan<char> idData)
		{
			bool result = false;
			for (int i = 0; i < idData.Length; i++)
			{
				char c = idData[i];
				if (!System.HexConverter.IsHexLowerChar(c))
				{
					return false;
				}
				if (c != '0')
				{
					result = true;
				}
			}
			return result;
		}
	}
	public readonly struct ActivitySpanId : IEquatable<ActivitySpanId>
	{
		private readonly string _hexString;

		internal ActivitySpanId(string hexString)
		{
			_hexString = hexString;
		}

		public unsafe static ActivitySpanId CreateRandom()
		{
			ulong num = default(ulong);
			ActivityTraceId.SetToRandomBytes(new Span<byte>(&num, 8));
			return new ActivitySpanId(System.HexConverter.ToString(new ReadOnlySpan<byte>(&num, 8), System.HexConverter.Casing.Lower));
		}

		public static ActivitySpanId CreateFromBytes(ReadOnlySpan<byte> idData)
		{
			if (idData.Length != 8)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return new ActivitySpanId(System.HexConverter.ToString(idData, System.HexConverter.Casing.Lower));
		}

		public static ActivitySpanId CreateFromUtf8String(ReadOnlySpan<byte> idData)
		{
			return new ActivitySpanId(idData);
		}

		public static ActivitySpanId CreateFromString(ReadOnlySpan<char> idData)
		{
			if (idData.Length != 16 || !ActivityTraceId.IsLowerCaseHexAndNotAllZeros(idData))
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			return new ActivitySpanId(idData.ToString());
		}

		public string ToHexString()
		{
			return _hexString ?? "0000000000000000";
		}

		public override string ToString()
		{
			return ToHexString();
		}

		public static bool operator ==(ActivitySpanId spanId1, ActivitySpanId spandId2)
		{
			return spanId1._hexString == spandId2._hexString;
		}

		public static bool operator !=(ActivitySpanId spanId1, ActivitySpanId spandId2)
		{
			return spanId1._hexString != spandId2._hexString;
		}

		public bool Equals(ActivitySpanId spanId)
		{
			return _hexString == spanId._hexString;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ActivitySpanId activitySpanId)
			{
				return _hexString == activitySpanId._hexString;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return ToHexString().GetHashCode();
		}

		private unsafe ActivitySpanId(ReadOnlySpan<byte> idData)
		{
			if (idData.Length != 16)
			{
				throw new ArgumentOutOfRangeException("idData");
			}
			if (!Utf8Parser.TryParse(idData, out ulong value, out int _, 'x'))
			{
				_hexString = CreateRandom()._hexString;
				return;
			}
			if (BitConverter.IsLittleEndian)
			{
				value = BinaryPrimitives.ReverseEndianness(value);
			}
			_hexString = System.HexConverter.ToString(new ReadOnlySpan<byte>(&value, 8), System.HexConverter.Casing.Lower);
		}

		public void CopyTo(Span<byte> destination)
		{
			ActivityTraceId.SetSpanFromHexChars(ToHexString().AsSpan(), destination);
		}
	}
	public enum ActivityStatusCode
	{
		Unset,
		Ok,
		Error
	}
	public class ActivityTagsCollection : IDictionary<string, object?>, ICollection<KeyValuePair<string, object?>>, IEnumerable<KeyValuePair<string, object?>>, IEnumerable
	{
		public struct Enumerator : IEnumerator<KeyValuePair<string, object?>>, IEnumerator, IDisposable
		{
			private List<KeyValuePair<string, object>>.Enumerator _enumerator;

			public KeyValuePair<string, object?> Current => _enumerator.Current;

			object IEnumerator.Current => ((IEnumerator)_enumerator).Current;

			internal Enumerator(List<KeyValuePair<string, object>> list)
			{
				_enumerator = list.GetEnumerator();
			}

			public void Dispose()
			{
				_enumerator.Dispose();
			}

			public bool MoveNext()
			{
				return _enumerator.MoveNext();
			}

			void IEnumerator.Reset()
			{
				((IEnumerator)_enumerator).Reset();
			}
		}

		private readonly List<KeyValuePair<string, object>> _list = new List<KeyValuePair<string, object>>();

		public object? this[string key]
		{
			get
			{
				int num = FindIndex(key);
				if (num >= 0)
				{
					return _list[num].Value;
				}
				return null;
			}
			set
			{
				ExceptionPolyfills.ThrowIfNull(key, "key");
				int num = FindIndex(key);
				if (value == null)
				{
					if (num >= 0)
					{
						_list.RemoveAt(num);
					}
				}
				else if (num >= 0)
				{
					_list[num] = new KeyValuePair<string, object>(key, value);
				}
				else
				{
					_list.Add(new KeyValuePair<string, object>(key, value));
				}
			}
		}

		public ICollection<string> Keys
		{
			get
			{
				List<string> list = new List<string>(_list.Count);
				foreach (KeyValuePair<string, object> item in _list)
				{
					list.Add(item.Key);
				}
				return list;
			}
		}

		public ICollection<object?> Values
		{
			get
			{
				List<object> list = new List<object>(_list.Count);
				foreach (KeyValuePair<string, object> item in _list)
				{
					list.Add(item.Value);
				}
				return list;
			}
		}

		public bool IsReadOnly => false;

		public int Count => _list.Count;

		public ActivityTagsCollection()
		{
		}

		public ActivityTagsCollection(IEnumerable<KeyValuePair<string, object?>> list)
		{
			ExceptionPolyfills.ThrowIfNull(list, "list");
			foreach (KeyValuePair<string, object> item in list)
			{
				if (item.Key != null)
				{
					this[item.Key] = item.Value;
				}
			}
		}

		public void Add(string key, object? value)
		{
			ExceptionPolyfills.ThrowIfNull(key, "key");
			if (FindIndex(key) >= 0)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.KeyAlreadyExist, key));
			}
			_list.Add(new KeyValuePair<string, object>(key, value));
		}

		public void Add(KeyValuePair<string, object?> item)
		{
			if (item.Key == null)
			{
				throw new ArgumentNullException("item");
			}
			if (FindIndex(item.Key) >= 0)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.KeyAlreadyExist, item.Key));
			}
			_list.Add(item);
		}

		public void Clear()
		{
			_list.Clear();
		}

		public bool Contains(KeyValuePair<string, object?> item)
		{
			return _list.Contains(item);
		}

		public bool ContainsKey(string key)
		{
			return FindIndex(key) >= 0;
		}

		public void CopyTo(KeyValuePair<string, object?>[] array, int arrayIndex)
		{
			_list.CopyTo(array, arrayIndex);
		}

		IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator()
		{
			return new Enumerator(_list);
		}

		public Enumerator GetEnumerator()
		{
			return new Enumerator(_list);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new Enumerator(_list);
		}

		public bool Remove(string key)
		{
			ExceptionPolyfills.ThrowIfNull(key, "key");
			int num = FindIndex(key);
			if (num >= 0)
			{
				_list.RemoveAt(num);
				return true;
			}
			return false;
		}

		public bool Remove(KeyValuePair<string, object?> item)
		{
			return _list.Remove(item);
		}

		public bool TryGetValue(string key, out object? value)
		{
			int num = FindIndex(key);
			if (num >= 0)
			{
				value = _list[num].Value;
				return true;
			}
			value = null;
			return false;
		}

		private int FindIndex(string key)
		{
			for (int i = 0; i < _list.Count; i++)
			{
				if (_list[i].Key == key)
				{
					return i;
				}
			}
			return -1;
		}
	}
	public readonly struct ActivityContext : IEquatable<ActivityContext>
	{
		public ActivityTraceId TraceId { get; }

		public ActivitySpanId SpanId { get; }

		public ActivityTraceFlags TraceFlags { get; }

		public string? TraceState { get; }

		public bool IsRemote { get; }

		public ActivityContext(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags traceFlags, string? traceState = null, bool isRemote = false)
		{
			TraceId = traceId;
			SpanId = spanId;
			TraceFlags = traceFlags;
			TraceState = traceState;
			IsRemote = isRemote;
		}

		public static bool TryParse(string? traceParent, string? traceState, bool isRemote, out ActivityContext context)
		{
			if (traceParent == null)
			{
				context = default(ActivityContext);
				return false;
			}
			return Activity.TryConvertIdToContext(traceParent, traceState, isRemote, out context);
		}

		public static bool TryParse(string? traceParent, string? traceState, out ActivityContext context)
		{
			return TryParse(traceParent, traceState, isRemote: false, out context);
		}

		public static ActivityContext Parse(string traceParent, string? traceState)
		{
			ExceptionPolyfills.ThrowIfNull(traceParent, "traceParent");
			if (!Activity.TryConvertIdToContext(traceParent, traceState, isRemote: false, out var context))
			{
				throw new ArgumentException(System.SR.InvalidTraceParent);
			}
			return context;
		}

		public bool Equals(ActivityContext value)
		{
			if (SpanId.Equals(value.SpanId) && TraceId.Equals(value.TraceId) && TraceFlags == value.TraceFlags && TraceState == value.TraceState)
			{
				return IsRemote == value.IsRemote;
			}
			return false;
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (!(obj is ActivityContext value))
			{
				return false;
			}
			return Equals(value);
		}

		public static bool operator ==(ActivityContext left, ActivityContext right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ActivityContext left, ActivityContext right)
		{
			return !(left == right);
		}

		public override int GetHashCode()
		{
			if (this == default(ActivityContext))
			{
				return 0;
			}
			int num = 5381;
			num = (num << 5) + num + TraceId.GetHashCode();
			num = (num << 5) + num + SpanId.GetHashCode();
			num = (int)((num << 5) + num + TraceFlags);
			return (num << 5) + num + ((TraceState != null) ? TraceState.GetHashCode() : 0);
		}
	}
	public readonly struct ActivityCreationOptions<T>
	{
		private readonly ActivityTagsCollection _samplerTags;

		private readonly ActivityContext _context;

		private readonly string _traceState;

		public ActivitySource Source { get; }

		public string Name { get; }

		public ActivityKind Kind { get; }

		public T Parent { get; }

		public IEnumerable<KeyValuePair<string, object?>>? Tags { get; }

		public IEnumerable<ActivityLink>? Links { get; }

		public ActivityTagsCollection SamplingTags
		{
			get
			{
				if (_samplerTags == null)
				{
					Unsafe.AsRef(in _samplerTags) = new ActivityTagsCollection();
				}
				return _samplerTags;
			}
		}

		public ActivityTraceId TraceId
		{
			get
			{
				if (Parent is ActivityContext && IdFormat == ActivityIdFormat.W3C && _context == default(ActivityContext))
				{
					ActivityTraceId traceId = Activity.TraceIdGenerator?.Invoke() ?? ActivityTraceId.CreateRandom();
					Unsafe.AsRef(in _context) = new ActivityContext(traceId, default(ActivitySpanId), ActivityTraceFlags.None);
				}
				return _context.TraceId;
			}
		}

		public string? TraceState
		{
			get
			{
				return _traceState;
			}
			init
			{
				_traceState = value;
			}
		}

		internal ActivityIdFormat IdFormat { get; }

		internal ActivityCreationOptions(ActivitySource source, string name, T parent, ActivityKind kind, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, ActivityIdFormat idFormat)
		{
			Source = source;
			Name = name;
			Kind = kind;
			Parent = parent;
			Tags = tags;
			Links = links;
			IdFormat = idFormat;
			if (IdFormat == ActivityIdFormat.Unknown && Activity.ForceDefaultIdFormat)
			{
				IdFormat = Activity.DefaultIdFormat;
			}
			_samplerTags = null;
			_traceState = null;
			if (parent is ActivityContext)
			{
				object obj = parent;
				ActivityContext activityContext = (ActivityContext)((obj is ActivityContext) ? obj : null);
				if (activityContext != default(ActivityContext))
				{
					_context = activityContext;
					if (IdFormat == ActivityIdFormat.Unknown)
					{
						IdFormat = ActivityIdFormat.W3C;
					}
					_traceState = activityContext.TraceState;
					return;
				}
			}
			if ((object)parent is string traceParent)
			{
				if (IdFormat != ActivityIdFormat.Hierarchical)
				{
					if (ActivityContext.TryParse(traceParent, null, out _context))
					{
						IdFormat = ActivityIdFormat.W3C;
					}
					if (IdFormat == ActivityIdFormat.Unknown)
					{
						IdFormat = ActivityIdFormat.Hierarchical;
					}
				}
				else
				{
					_context = default(ActivityContext);
				}
			}
			else
			{
				_context = default(ActivityContext);
				if (IdFormat == ActivityIdFormat.Unknown)
				{
					IdFormat = ((Activity.Current != null) ? Activity.Current.IdFormat : Activity.DefaultIdFormat);
				}
			}
		}

		internal void SetTraceState(string traceState)
		{
			Unsafe.AsRef(in _traceState) = traceState;
		}

		internal ActivityTagsCollection GetSamplingTags()
		{
			return _samplerTags;
		}

		internal ActivityContext GetContext()
		{
			return _context;
		}
	}
	public enum ActivitySamplingResult
	{
		None,
		PropagationData,
		AllData,
		AllDataAndRecorded
	}
	public readonly struct ActivityEvent
	{
		private static readonly IEnumerable<KeyValuePair<string, object>> s_emptyTags = Array.Empty<KeyValuePair<string, object>>();

		private readonly Activity.TagsLinkedList _tags;

		public string Name { get; }

		public DateTimeOffset Timestamp { get; }

		public IEnumerable<KeyValuePair<string, object?>> Tags
		{
			get
			{
				IEnumerable<KeyValuePair<string, object>> tags = _tags;
				return tags ?? s_emptyTags;
			}
		}

		public ActivityEvent(string name)
			: this(name, DateTimeOffset.UtcNow)
		{
		}

		public ActivityEvent(string name, DateTimeOffset timestamp = default(DateTimeOffset), ActivityTagsCollection? tags = null)
			: this(name, timestamp, tags, tags?.Count ?? 0)
		{
		}

		internal ActivityEvent(string name, DateTimeOffset timestamp, ref TagList tags)
			: this(name, timestamp, tags, tags.Count)
		{
		}

		private ActivityEvent(string name, DateTimeOffset timestamp, IEnumerable<KeyValuePair<string, object>> tags, int tagsCount)
		{
			Name = name ?? string.Empty;
			Timestamp = ((timestamp != default(DateTimeOffset)) ? timestamp : DateTimeOffset.UtcNow);
			_tags = ((tagsCount > 0) ? new Activity.TagsLinkedList(tags) : null);
		}

		public Activity.Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects()
		{
			return new Activity.Enumerator<KeyValuePair<string, object>>(_tags?.First);
		}
	}
	public enum ActivityKind
	{
		Internal,
		Server,
		Client,
		Producer,
		Consumer
	}
	public readonly struct ActivityLink : IEquatable<ActivityLink>
	{
		private readonly Activity.TagsLinkedList _tags;

		public ActivityContext Context { get; }

		public IEnumerable<KeyValuePair<string, object?>>? Tags => _tags;

		public ActivityLink(ActivityContext context, ActivityTagsCollection? tags = null)
		{
			Context = context;
			_tags = ((tags != null && tags.Count > 0) ? new Activity.TagsLinkedList(tags) : null);
		}

		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			if (obj is ActivityLink value)
			{
				return Equals(value);
			}
			return false;
		}

		public bool Equals(ActivityLink value)
		{
			if (Context == value.Context)
			{
				return value.Tags == Tags;
			}
			return false;
		}

		public static bool operator ==(ActivityLink left, ActivityLink right)
		{
			return left.Equals(right);
		}

		public static bool operator !=(ActivityLink left, ActivityLink right)
		{
			return !left.Equals(right);
		}

		public Activity.Enumerator<KeyValuePair<string, object?>> EnumerateTagObjects()
		{
			return new Activity.Enumerator<KeyValuePair<string, object>>(_tags?.First);
		}

		public override int GetHashCode()
		{
			if (this == default(ActivityLink))
			{
				return 0;
			}
			int num = 5381;
			num = (num << 5) + num + Context.GetHashCode();
			if (Tags != null)
			{
				foreach (KeyValuePair<string, object> tag in Tags)
				{
					num = (num << 5) + num + tag.Key.GetHashCode();
					if (tag.Value != null)
					{
						num = (num << 5) + num + tag.Value.GetHashCode();
					}
				}
			}
			return num;
		}
	}
	public delegate ActivitySamplingResult SampleActivity<T>(ref ActivityCreationOptions<T> options);
	public delegate void ExceptionRecorder(Activity activity, Exception exception, ref TagList tags);
	public sealed class ActivityListener : IDisposable
	{
		public Action<Activity>? ActivityStarted { get; set; }

		public Action<Activity>? ActivityStopped { get; set; }

		public ExceptionRecorder? ExceptionRecorder { get; set; }

		public Func<ActivitySource, bool>? ShouldListenTo { get; set; }

		public SampleActivity<string>? SampleUsingParentId { get; set; }

		public SampleActivity<ActivityContext>? Sample { get; set; }

		public void Dispose()
		{
			ActivitySource.DetachListener(this);
		}
	}
	public sealed class ActivitySource : IDisposable
	{
		internal delegate void Function<T, TParent>(T item, ref ActivityCreationOptions<TParent> data, ref ActivitySamplingResult samplingResult, ref ActivityCreationOptions<ActivityContext> dataWithContext);

		private static readonly SynchronizedList<ActivitySource> s_activeSources = new SynchronizedList<ActivitySource>();

		private static readonly SynchronizedList<ActivityListener> s_allListeners = new SynchronizedList<ActivityListener>();

		private SynchronizedList<ActivityListener> _listeners;

		public string Name { get; }

		public string? Version { get; }

		public IEnumerable<KeyValuePair<string, object?>>? Tags { get; }

		public string? TelemetrySchemaUrl { get; }

		public ActivitySource(string name)
			: this(name, "", null, null)
		{
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public ActivitySource(string name, string? version = "")
			: this(name, version, null, null)
		{
		}

		public ActivitySource(string name, string? version = "", IEnumerable<KeyValuePair<string, object?>>? tags = null)
			: this(name, version, tags, null)
		{
		}

		public ActivitySource(ActivitySourceOptions options)
			: this((options ?? throw new ArgumentNullException("options")).Name, options.Version, options.Tags, options.TelemetrySchemaUrl)
		{
		}

		private ActivitySource(string name, string version, IEnumerable<KeyValuePair<string, object>> tags, string telemetrySchemaUrl)
		{
			Name = name ?? throw new ArgumentNullException("name");
			Version = version;
			TelemetrySchemaUrl = telemetrySchemaUrl;
			if (tags != null)
			{
				List<KeyValuePair<string, object>> list = new List<KeyValuePair<string, object>>(tags);
				list.Sort((KeyValuePair<string, object> left, KeyValuePair<string, object> right) => string.Compare(left.Key, right.Key, StringComparison.Ordinal));
				Tags = list.AsReadOnly();
			}
			s_activeSources.Add(this);
			s_allListeners.EnumWithAction(delegate(ActivityListener listener, object source)
			{
				Func<ActivitySource, bool> shouldListenTo = listener.ShouldListenTo;
				if (shouldListenTo != null)
				{
					ActivitySource activitySource = (ActivitySource)source;
					if (shouldListenTo(activitySource))
					{
						activitySource.AddListener(listener);
					}
				}
			}, this);
			GC.KeepAlive(DiagnosticSourceEventSource.Log);
		}

		public bool HasListeners()
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners != null)
			{
				return listeners.Count > 0;
			}
			return false;
		}

		public Activity? CreateActivity(string name, ActivityKind kind)
		{
			return CreateActivity(name, kind, default(ActivityContext), null, null, null, default(DateTimeOffset), startIt: false);
		}

		public Activity? CreateActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, ActivityIdFormat idFormat = ActivityIdFormat.Unknown)
		{
			return CreateActivity(name, kind, parentContext, null, tags, links, default(DateTimeOffset), startIt: false, idFormat);
		}

		public Activity? CreateActivity(string name, ActivityKind kind, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, ActivityIdFormat idFormat = ActivityIdFormat.Unknown)
		{
			return CreateActivity(name, kind, default(ActivityContext), parentId, tags, links, default(DateTimeOffset), startIt: false, idFormat);
		}

		public Activity? StartActivity([CallerMemberName] string name = "", ActivityKind kind = ActivityKind.Internal)
		{
			return CreateActivity(name, kind, default(ActivityContext), null, null, null, default(DateTimeOffset));
		}

		public Activity? StartActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset))
		{
			return CreateActivity(name, kind, parentContext, null, tags, links, startTime);
		}

		public Activity? StartActivity(string name, ActivityKind kind, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset))
		{
			return CreateActivity(name, kind, default(ActivityContext), parentId, tags, links, startTime);
		}

		public Activity? StartActivity(ActivityKind kind, ActivityContext parentContext = default(ActivityContext), IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default(DateTimeOffset), [CallerMemberName] string name = "")
		{
			return CreateActivity(name, kind, parentContext, null, tags, links, startTime);
		}

		private Activity CreateActivity(string name, ActivityKind kind, ActivityContext context, string parentId, IEnumerable<KeyValuePair<string, object>> tags, IEnumerable<ActivityLink> links, DateTimeOffset startTime, bool startIt = true, ActivityIdFormat idFormat = ActivityIdFormat.Unknown)
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners == null || listeners.Count == 0)
			{
				return null;
			}
			Activity result2 = null;
			ActivitySamplingResult samplingResult = ActivitySamplingResult.None;
			ActivityTagsCollection activityTagsCollection;
			string traceState;
			if (parentId != null)
			{
				ActivityCreationOptions<string> activityCreationOptions = default(ActivityCreationOptions<string>);
				ActivityCreationOptions<ActivityContext> dataWithContext2 = default(ActivityCreationOptions<ActivityContext>);
				activityCreationOptions = new ActivityCreationOptions<string>(this, name, parentId, kind, tags, links, idFormat);
				if (activityCreationOptions.IdFormat == ActivityIdFormat.W3C)
				{
					dataWithContext2 = new ActivityCreationOptions<ActivityContext>(this, name, activityCreationOptions.GetContext(), kind, tags, links, ActivityIdFormat.W3C);
				}
				listeners.EnumWithFunc(delegate(ActivityListener listener, ref ActivityCreationOptions<string> data, ref ActivitySamplingResult result, ref ActivityCreationOptions<ActivityContext> dataWithContext)
				{
					SampleActivity<string> sampleUsingParentId = listener.SampleUsingParentId;
					if (sampleUsingParentId != null)
					{
						ActivitySamplingResult activitySamplingResult2 = sampleUsingParentId(ref data);
						dataWithContext.SetTraceState(data.TraceState);
						if (activitySamplingResult2 > result)
						{
							result = activitySamplingResult2;
						}
					}
					else if (data.IdFormat == ActivityIdFormat.W3C)
					{
						SampleActivity<ActivityContext> sample2 = listener.Sample;
						if (sample2 != null)
						{
							ActivitySamplingResult activitySamplingResult3 = sample2(ref dataWithContext);
							data.SetTraceState(dataWithContext.TraceState);
							if (activitySamplingResult3 > result)
							{
								result = activitySamplingResult3;
							}
						}
					}
				}, ref activityCreationOptions, ref samplingResult, ref dataWithContext2);
				if (context == default(ActivityContext))
				{
					if (activityCreationOptions.GetContext() != default(ActivityContext))
					{
						context = activityCreationOptions.GetContext();
						parentId = null;
					}
					else if (dataWithContext2.GetContext() != default(ActivityContext))
					{
						context = dataWithContext2.GetContext();
						parentId = null;
					}
				}
				activityTagsCollection = activityCreationOptions.GetSamplingTags();
				ActivityTagsCollection samplingTags = dataWithContext2.GetSamplingTags();
				if (samplingTags != null)
				{
					if (activityTagsCollection == null)
					{
						activityTagsCollection = samplingTags;
					}
					else
					{
						foreach (KeyValuePair<string, object?> item in samplingTags)
						{
							activityTagsCollection.Add(item);
						}
					}
				}
				idFormat = activityCreationOptions.IdFormat;
				traceState = activityCreationOptions.TraceState;
			}
			else
			{
				bool flag = context == default(ActivityContext) && Activity.Current != null;
				ActivityCreationOptions<ActivityContext> data2 = new ActivityCreationOptions<ActivityContext>(this, name, flag ? Activity.Current.Context : context, kind, tags, links, idFormat);
				listeners.EnumWithFunc(delegate(ActivityListener listener, ref ActivityCreationOptions<ActivityContext> data, ref ActivitySamplingResult result, ref ActivityCreationOptions<ActivityContext> unused)
				{
					SampleActivity<ActivityContext> sample = listener.Sample;
					if (sample != null)
					{
						ActivitySamplingResult activitySamplingResult = sample(ref data);
						if (activitySamplingResult > result)
						{
							result = activitySamplingResult;
						}
					}
				}, ref data2, ref samplingResult, ref data2);
				if (!flag)
				{
					context = data2.GetContext();
				}
				activityTagsCollection = data2.GetSamplingTags();
				idFormat = data2.IdFormat;
				traceState = data2.TraceState;
			}
			if (samplingResult != 0)
			{
				result2 = Activity.Create(this, name, kind, parentId, context, tags, links, startTime, activityTagsCollection, samplingResult, startIt, idFormat, traceState);
			}
			return result2;
		}

		public void Dispose()
		{
			_listeners = null;
			s_activeSources.Remove(this);
		}

		public static void AddActivityListener(ActivityListener listener)
		{
			ExceptionPolyfills.ThrowIfNull(listener, "listener");
			if (!s_allListeners.AddIfNotExist(listener))
			{
				return;
			}
			s_activeSources.EnumWithAction(delegate(ActivitySource source, object obj)
			{
				Func<ActivitySource, bool> shouldListenTo = ((ActivityListener)obj).ShouldListenTo;
				if (shouldListenTo != null && shouldListenTo(source))
				{
					source.AddListener((ActivityListener)obj);
				}
			}, listener);
		}

		internal void AddListener(ActivityListener listener)
		{
			if (_listeners == null)
			{
				Interlocked.CompareExchange(ref _listeners, new SynchronizedList<ActivityListener>(), null);
			}
			_listeners.AddIfNotExist(listener);
		}

		internal static void DetachListener(ActivityListener listener)
		{
			s_allListeners.Remove(listener);
			s_activeSources.EnumWithAction(delegate(ActivitySource source, object obj)
			{
				source._listeners?.Remove((ActivityListener)obj);
			}, listener);
		}

		internal void NotifyActivityStart(Activity activity)
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners != null && listeners.Count > 0)
			{
				listeners.EnumWithAction(delegate(ActivityListener listener, object obj)
				{
					listener.ActivityStarted?.Invoke((Activity)obj);
				}, activity);
			}
		}

		internal void NotifyActivityStop(Activity activity)
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners != null && listeners.Count > 0)
			{
				listeners.EnumWithAction(delegate(ActivityListener listener, object obj)
				{
					listener.ActivityStopped?.Invoke((Activity)obj);
				}, activity);
			}
		}

		internal void NotifyActivityAddException(Activity activity, Exception exception, ref TagList tags)
		{
			SynchronizedList<ActivityListener> listeners = _listeners;
			if (listeners != null && listeners.Count > 0)
			{
				listeners.EnumWithExceptionNotification(activity, exception, ref tags);
			}
		}
	}
	internal sealed class SynchronizedList<T>
	{
		private readonly object _writeLock;

		private T[] _volatileArray;

		public int Count => _volatileArray.Length;

		public SynchronizedList()
		{
			_volatileArray = Array.Empty<T>();
			_writeLock = new object();
		}

		public void Add(T item)
		{
			lock (_writeLock)
			{
				T[] array = new T[_volatileArray.Length + 1];
				Array.Copy(_volatileArray, array, _volatileArray.Length);
				array[_volatileArray.Length] = item;
				_volatileArray = array;
			}
		}

		public bool AddIfNotExist(T item)
		{
			lock (_writeLock)
			{
				if (Array.IndexOf(_volatileArray, item) >= 0)
				{
					return false;
				}
				T[] array = new T[_volatileArray.Length + 1];
				Array.Copy(_volatileArray, array, _volatileArray.Length);
				array[_volatileArray.Length] = item;
				_volatileArray = array;
				return true;
			}
		}

		public bool Remove(T item)
		{
			lock (_writeLock)
			{
				int num = Array.IndexOf(_volatileArray, item);
				if (num < 0)
				{
					return false;
				}
				T[] array = new T[_volatileArray.Length - 1];
				Array.Copy(_volatileArray, array, num);
				Array.Copy(_volatileArray, num + 1, array, num, _volatileArray.Length - num - 1);
				_volatileArray = array;
				return true;
			}
		}

		public void EnumWithFunc<TParent>(ActivitySource.Function<T, TParent> func, ref ActivityCreationOptions<TParent> data, ref ActivitySamplingResult samplingResult, ref ActivityCreationOptions<ActivityContext> dataWithContext)
		{
			T[] volatileArray = _volatileArray;
			foreach (T item in volatileArray)
			{
				func(item, ref data, ref samplingResult, ref dataWithContext);
			}
		}

		public void EnumWithAction(Action<T, object> action, object arg)
		{
			T[] volatileArray = _volatileArray;
			foreach (T arg2 in volatileArray)
			{
				action(arg2, arg);
			}
		}

		public void EnumWithExceptionNotification(Activity activity, Exception exception, ref TagList tags)
		{
			if (!(typeof(T) != typeof(ActivityListener)))
			{
				T[] volatileArray = _volatileArray;
				for (int i = 0; i < volatileArray.Length; i++)
				{
					(volatileArray[i] as ActivityListener).ExceptionRecorder?.Invoke(activity, exception, ref tags);
				}
			}
		}
	}
	public class ActivitySourceOptions
	{
		private string _name;

		public string Name
		{
			get
			{
				return _name;
			}
			set
			{
				_name = value ?? throw new ArgumentNullException("value");
			}
		}

		public string? Version { get; set; } = string.Empty;


		public IEnumerable<KeyValuePair<string, object?>>? Tags { get; set; }

		public string? TelemetrySchemaUrl { get; set; }

		public ActivitySourceOptions(string name)
		{
			_name = name ?? throw new ArgumentNullException("name");
		}
	}
	public abstract class DiagnosticSource
	{
		internal const string WriteRequiresUnreferencedCode = "The type of object being written to DiagnosticSource cannot be discovered statically.";

		internal const string WriteOfTRequiresUnreferencedCode = "Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.";

		[RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")]
		public abstract void Write(string name, object? value);

		[RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of referenced types and properties of derived types may be trimmed.")]
		public void Write<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T>(string name, T value)
		{
			Write(name, (object?)value);
		}

		public abstract bool IsEnabled(string name);

		public virtual bool IsEnabled(string name, object? arg1, object? arg2 = null)
		{
			return IsEnabled(name);
		}

		[RequiresUnreferencedCode("The type of object being written to DiagnosticSource cannot be discovered statically.")]
		public Activity StartActivity(Activity activity, object? args)
		{
			activity.Start();
			Write(activity.OperationName + ".Start", args);
			return activity;
		}

		[RequiresUnreferencedCode("Only the properties of the T type will be preserved. Properties of ref

BepInEx/core/System.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Configuration;
using System.Configuration.Internal;
using System.Configuration.Provider;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.IO.CoreFX;
using System.IO.Enumeration;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Net.Configuration;
using System.Net.Http;
using System.Net.Mail;
using System.Net.Mime;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.AccessControl;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using System.Timers;
using System.Web.Util;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.XPath;
using Internal.Cryptography;
using Internal.Cryptography.Pal;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using Mono;
using Mono.Audio;
using Mono.Btls;
using Mono.Http;
using Mono.Net;
using Mono.Net.Dns;
using Mono.Net.Security;
using Mono.Net.Security.Private;
using Mono.Security;
using Mono.Security.Authenticode;
using Mono.Security.Cryptography;
using Mono.Security.Interface;
using Mono.Security.Protocol.Ntlm;
using Mono.Security.X509;
using Mono.Security.X509.Extensions;
using Mono.Unity;
using Mono.Util;
using ObjCRuntimeInternal;
using Unity;

[assembly: InternalsVisibleTo("System.Web, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.dll")]
[assembly: AssemblyDescription("System.dll")]
[assembly: AssemblyDefaultAlias("System.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: CompilationRelaxations(8)]
[assembly: CLSCompliant(true)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyKeyFile("../ecma.pub")]
[assembly: InternalsVisibleTo("System.ComponentModel.DataAnnotations, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.Data, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Net.Http, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("System.Net.Http.WebRequest, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: InternalsVisibleTo("Mono.Btls.Interface, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
[assembly: InternalsVisibleTo("Mono.Security, PublicKey=002400000480000094000000060200000024000052534131000400000100010079159977d2d03a8e6bea7a2e74e8d1afcc93e8851974952bb480a12c9134474d04062447c37e0e68c080536fcf3c3fbe2ff9c979ce998475e506e8ce82dd5b0f350dc10e93bf2eeecf874b24770c5081dbea7447fddafa277b22de47d6ffea449674a4f9fccf84d15069089380284dbdd35f46cdff12a1bd78e4ef0065d016df")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: TypeForwardedTo(typeof(Queue<>))]
[assembly: TypeForwardedTo(typeof(Stack<>))]
[assembly: TypeForwardedTo(typeof(FileSystemName))]
[assembly: TypeForwardedTo(typeof(CryptographicOperations))]
[module: UnverifiableCode]
internal static class Interop
{
	internal static class Crypt32
	{
		internal struct CRYPT_OID_INFO
		{
			public int cbSize;

			public IntPtr pszOID;

			public IntPtr pwszName;

			public OidGroup dwGroupId;

			public int AlgId;

			public int cbData;

			public IntPtr pbData;

			public string OID => Marshal.PtrToStringAnsi(pszOID);

			public string Name => Marshal.PtrToStringUni(pwszName);
		}

		internal enum CryptOidInfoKeyType
		{
			CRYPT_OID_INFO_OID_KEY = 1,
			CRYPT_OID_INFO_NAME_KEY,
			CRYPT_OID_INFO_ALGID_KEY,
			CRYPT_OID_INFO_SIGN_KEY,
			CRYPT_OID_INFO_CNG_ALGID_KEY,
			CRYPT_OID_INFO_CNG_SIGN_KEY
		}

		internal static class AuthType
		{
			internal const uint AUTHTYPE_CLIENT = 1u;

			internal const uint AUTHTYPE_SERVER = 2u;
		}

		internal static class CertChainPolicyIgnoreFlags
		{
			internal const uint CERT_CHAIN_POLICY_IGNORE_NOT_TIME_VALID_FLAG = 1u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_CTL_NOT_TIME_VALID_FLAG = 2u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_NOT_TIME_NESTED_FLAG = 4u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_INVALID_BASIC_CONSTRAINTS_FLAG = 8u;

			internal const uint CERT_CHAIN_POLICY_ALLOW_UNKNOWN_CA_FLAG = 16u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_WRONG_USAGE_FLAG = 32u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG = 64u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_INVALID_POLICY_FLAG = 128u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_END_REV_UNKNOWN_FLAG = 256u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_CTL_SIGNER_REV_UNKNOWN_FLAG = 512u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_CA_REV_UNKNOWN_FLAG = 1024u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_ROOT_REV_UNKNOWN_FLAG = 2048u;

			internal const uint CERT_CHAIN_POLICY_IGNORE_ALL = 4095u;
		}

		internal static class CertChainPolicy
		{
			internal const int CERT_CHAIN_POLICY_BASE = 1;

			internal const int CERT_CHAIN_POLICY_AUTHENTICODE = 2;

			internal const int CERT_CHAIN_POLICY_AUTHENTICODE_TS = 3;

			internal const int CERT_CHAIN_POLICY_SSL = 4;

			internal const int CERT_CHAIN_POLICY_BASIC_CONSTRAINTS = 5;

			internal const int CERT_CHAIN_POLICY_NT_AUTH = 6;

			internal const int CERT_CHAIN_POLICY_MICROSOFT_ROOT = 7;

			internal const int CERT_CHAIN_POLICY_EV = 8;
		}

		internal static class CertChainPolicyErrors
		{
			internal const uint TRUST_E_CERT_SIGNATURE = 2148098052u;

			internal const uint CRYPT_E_REVOKED = 2148081680u;

			internal const uint CERT_E_UNTRUSTEDROOT = 2148204809u;

			internal const uint CERT_E_UNTRUSTEDTESTROOT = 2148204813u;

			internal const uint CERT_E_CHAINING = 2148204810u;

			internal const uint CERT_E_WRONG_USAGE = 2148204816u;

			internal const uint CERT_E_EXPIRE = 2148204801u;

			internal const uint CERT_E_INVALID_NAME = 2148204820u;

			internal const uint CERT_E_INVALID_POLICY = 2148204819u;

			internal const uint TRUST_E_BASIC_CONSTRAINTS = 2148098073u;

			internal const uint CERT_E_CRITICAL = 2148204805u;

			internal const uint CERT_E_VALIDITYPERIODNESTING = 2148204802u;

			internal const uint CRYPT_E_NO_REVOCATION_CHECK = 2148081682u;

			internal const uint CRYPT_E_REVOCATION_OFFLINE = 2148081683u;

			internal const uint CERT_E_PURPOSE = 2148204806u;

			internal const uint CERT_E_REVOKED = 2148204812u;

			internal const uint CERT_E_REVOCATION_FAILURE = 2148204814u;

			internal const uint CERT_E_CN_NO_MATCH = 2148204815u;

			internal const uint CERT_E_ROLE = 2148204803u;
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct CERT_CONTEXT
		{
			internal uint dwCertEncodingType;

			internal IntPtr pbCertEncoded;

			internal uint cbCertEncoded;

			internal IntPtr pCertInfo;

			internal IntPtr hCertStore;
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct SSL_EXTRA_CERT_CHAIN_POLICY_PARA
		{
			internal uint cbSize;

			internal uint dwAuthType;

			internal uint fdwChecks;

			internal unsafe char* pwszServerName;
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct CERT_CHAIN_POLICY_PARA
		{
			public uint cbSize;

			public uint dwFlags;

			public unsafe SSL_EXTRA_CERT_CHAIN_POLICY_PARA* pvExtraPolicyPara;
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct CERT_CHAIN_POLICY_STATUS
		{
			public uint cbSize;

			public uint dwError;

			public int lChainIndex;

			public int lElementIndex;

			public unsafe void* pvExtraPolicyStatus;
		}

		internal static CRYPT_OID_INFO FindOidInfo(CryptOidInfoKeyType keyType, string key, OidGroup group, bool fallBackToAllGroups)
		{
			IntPtr intPtr = IntPtr.Zero;
			try
			{
				intPtr = keyType switch
				{
					CryptOidInfoKeyType.CRYPT_OID_INFO_OID_KEY => Marshal.StringToCoTaskMemAnsi(key), 
					CryptOidInfoKeyType.CRYPT_OID_INFO_NAME_KEY => Marshal.StringToCoTaskMemUni(key), 
					_ => throw new NotSupportedException(), 
				};
				if (!OidGroupWillNotUseActiveDirectory(group))
				{
					OidGroup group2 = group | (OidGroup)(-2147483648);
					IntPtr intPtr2 = CryptFindOIDInfo(keyType, intPtr, group2);
					if (intPtr2 != IntPtr.Zero)
					{
						return Marshal.PtrToStructure<CRYPT_OID_INFO>(intPtr2);
					}
				}
				IntPtr intPtr3 = CryptFindOIDInfo(keyType, intPtr, group);
				if (intPtr3 != IntPtr.Zero)
				{
					return Marshal.PtrToStructure<CRYPT_OID_INFO>(intPtr3);
				}
				if (fallBackToAllGroups && group != 0)
				{
					IntPtr intPtr4 = CryptFindOIDInfo(keyType, intPtr, OidGroup.All);
					if (intPtr4 != IntPtr.Zero)
					{
						return Marshal.PtrToStructure<CRYPT_OID_INFO>(intPtr4);
					}
				}
				CRYPT_OID_INFO result = default(CRYPT_OID_INFO);
				result.AlgId = -1;
				return result;
			}
			finally
			{
				if (intPtr != IntPtr.Zero)
				{
					Marshal.FreeCoTaskMem(intPtr);
				}
			}
		}

		private static bool OidGroupWillNotUseActiveDirectory(OidGroup group)
		{
			if (group != OidGroup.HashAlgorithm && group != OidGroup.EncryptionAlgorithm && group != OidGroup.PublicKeyAlgorithm && group != OidGroup.SignatureAlgorithm && group != OidGroup.Attribute && group != OidGroup.ExtensionOrAttribute)
			{
				return group == OidGroup.KeyDerivationFunction;
			}
			return true;
		}

		[DllImport("crypt32.dll", CharSet = CharSet.Unicode)]
		private static extern IntPtr CryptFindOIDInfo(CryptOidInfoKeyType dwKeyType, IntPtr pvKey, OidGroup group);

		[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CertFreeCertificateContext(IntPtr pCertContext);

		[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CertVerifyCertificateChainPolicy(IntPtr pszPolicyOID, SafeX509ChainHandle pChainContext, [In] ref CERT_CHAIN_POLICY_PARA pPolicyPara, [In][Out] ref CERT_CHAIN_POLICY_STATUS pPolicyStatus);
	}

	internal enum BOOL
	{
		FALSE,
		TRUE
	}

	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 enum SECURITY_STATUS
	{
		OK = 0,
		ContinueNeeded = 590610,
		CompleteNeeded = 590611,
		CompAndContinue = 590612,
		ContextExpired = 590615,
		CredentialsNeeded = 590624,
		Renegotiate = 590625,
		OutOfMemory = -2146893056,
		InvalidHandle = -2146893055,
		Unsupported = -2146893054,
		TargetUnknown = -2146893053,
		InternalError = -2146893052,
		PackageNotFound = -2146893051,
		NotOwner = -2146893050,
		CannotInstall = -2146893049,
		InvalidToken = -2146893048,
		CannotPack = -2146893047,
		QopNotSupported = -2146893046,
		NoImpersonation = -2146893045,
		LogonDenied = -2146893044,
		UnknownCredentials = -2146893043,
		NoCredentials = -2146893042,
		MessageAltered = -2146893041,
		OutOfSequence = -2146893040,
		NoAuthenticatingAuthority = -2146893039,
		IncompleteMessage = -2146893032,
		IncompleteCredentials = -2146893024,
		BufferNotEnough = -2146893023,
		WrongPrincipal = -2146893022,
		TimeSkew = -2146893020,
		UntrustedRoot = -2146893019,
		IllegalMessage = -2146893018,
		CertUnknown = -2146893017,
		CertExpired = -2146893016,
		AlgorithmMismatch = -2146893007,
		SecurityQosFailed = -2146893006,
		SmartcardLogonRequired = -2146892994,
		UnsupportedPreauth = -2146892989,
		BadBinding = -2146892986,
		DowngradeDetected = -2146892976,
		ApplicationProtocolMismatch = -2146892953
	}

	internal enum ApplicationProtocolNegotiationStatus
	{
		None,
		Success,
		SelectedClientOnly
	}

	internal enum ApplicationProtocolNegotiationExt
	{
		None,
		NPN,
		ALPN
	}

	[StructLayout(LayoutKind.Sequential)]
	internal class SecPkgContext_ApplicationProtocol
	{
		private const int MaxProtocolIdSize = 255;

		public ApplicationProtocolNegotiationStatus ProtoNegoStatus;

		public ApplicationProtocolNegotiationExt ProtoNegoExt;

		public byte ProtocolIdSize;

		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 255)]
		public byte[] ProtocolId;

		public byte[] Protocol => new Span<byte>(ProtocolId, 0, (int)ProtocolIdSize).ToArray();
	}

	internal class Kernel32
	{
		internal class IOReparseOptions
		{
			internal const uint IO_REPARSE_TAG_FILE_PLACEHOLDER = 2147483669u;

			internal const uint IO_REPARSE_TAG_MOUNT_POINT = 2684354563u;
		}

		internal class FileOperations
		{
			internal const int OPEN_EXISTING = 3;

			internal const int COPY_FILE_FAIL_IF_EXISTS = 1;

			internal const int FILE_ACTION_ADDED = 1;

			internal const int FILE_ACTION_REMOVED = 2;

			internal const int FILE_ACTION_MODIFIED = 3;

			internal const int FILE_ACTION_RENAMED_OLD_NAME = 4;

			internal const int FILE_ACTION_RENAMED_NEW_NAME = 5;

			internal const int FILE_FLAG_BACKUP_SEMANTICS = 33554432;

			internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 524288;

			internal const int FILE_FLAG_OVERLAPPED = 1073741824;

			internal const int FILE_LIST_DIRECTORY = 1;
		}

		internal struct SECURITY_ATTRIBUTES
		{
			internal uint nLength;

			internal IntPtr lpSecurityDescriptor;

			internal BOOL bInheritHandle;
		}

		internal const uint SEM_FAILCRITICALERRORS = 1u;

		[DllImport("kernel32.dll", SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CloseHandle(IntPtr handle);

		[DllImport("kernel32.dll", BestFitMapping = false, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW", ExactSpelling = true, SetLastError = true)]
		private unsafe static extern IntPtr CreateFilePrivate(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES* securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);

		internal unsafe static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, ref SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile)
		{
			lpFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName);
			fixed (SECURITY_ATTRIBUTES* securityAttrs2 = &securityAttrs)
			{
				IntPtr intPtr = CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, securityAttrs2, dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
				try
				{
					return new SafeFileHandle(intPtr, ownsHandle: true);
				}
				catch
				{
					CloseHandle(intPtr);
					throw;
				}
			}
		}

		internal static SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes)
		{
			IntPtr intPtr = CreateFile_IntPtr(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, dwFlagsAndAttributes);
			try
			{
				return new SafeFileHandle(intPtr, ownsHandle: true);
			}
			catch
			{
				CloseHandle(intPtr);
				throw;
			}
		}

		internal unsafe static IntPtr CreateFile_IntPtr(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, FileMode dwCreationDisposition, int dwFlagsAndAttributes)
		{
			lpFileName = System.IO.PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName);
			return CreateFilePrivate(lpFileName, dwDesiredAccess, dwShareMode, null, dwCreationDisposition, dwFlagsAndAttributes, IntPtr.Zero);
		}

		[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		internal unsafe static extern bool ReadDirectoryChangesW(SafeFileHandle hDirectory, byte[] lpBuffer, uint nBufferLength, [MarshalAs(UnmanagedType.Bool)] bool bWatchSubtree, int dwNotifyFilter, out int lpBytesReturned, NativeOverlapped* lpOverlapped, IntPtr lpCompletionRoutine);
	}

	internal static class SspiCli
	{
		[StructLayout(LayoutKind.Sequential, Pack = 1)]
		internal struct CredHandle
		{
			private IntPtr dwLower;

			private IntPtr dwUpper;

			public bool IsZero
			{
				get
				{
					if (dwLower == IntPtr.Zero)
					{
						return dwUpper == IntPtr.Zero;
					}
					return false;
				}
			}

			internal void SetToInvalid()
			{
				dwLower = IntPtr.Zero;
				dwUpper = IntPtr.Zero;
			}

			public override string ToString()
			{
				return dwLower.ToString("x") + ":" + dwUpper.ToString("x");
			}
		}

		internal enum ContextAttribute
		{
			SECPKG_ATTR_SIZES = 0,
			SECPKG_ATTR_NAMES = 1,
			SECPKG_ATTR_LIFESPAN = 2,
			SECPKG_ATTR_DCE_INFO = 3,
			SECPKG_ATTR_STREAM_SIZES = 4,
			SECPKG_ATTR_AUTHORITY = 6,
			SECPKG_ATTR_PACKAGE_INFO = 10,
			SECPKG_ATTR_NEGOTIATION_INFO = 12,
			SECPKG_ATTR_UNIQUE_BINDINGS = 25,
			SECPKG_ATTR_ENDPOINT_BINDINGS = 26,
			SECPKG_ATTR_CLIENT_SPECIFIED_TARGET = 27,
			SECPKG_ATTR_APPLICATION_PROTOCOL = 35,
			SECPKG_ATTR_REMOTE_CERT_CONTEXT = 83,
			SECPKG_ATTR_LOCAL_CERT_CONTEXT = 84,
			SECPKG_ATTR_ROOT_STORE = 85,
			SECPKG_ATTR_ISSUER_LIST_EX = 89,
			SECPKG_ATTR_CONNECTION_INFO = 90,
			SECPKG_ATTR_UI_INFO = 104
		}

		[Flags]
		internal enum ContextFlags
		{
			Zero = 0,
			Delegate = 1,
			MutualAuth = 2,
			ReplayDetect = 4,
			SequenceDetect = 8,
			Confidentiality = 0x10,
			UseSessionKey = 0x20,
			AllocateMemory = 0x100,
			Connection = 0x800,
			InitExtendedError = 0x4000,
			AcceptExtendedError = 0x8000,
			InitStream = 0x8000,
			AcceptStream = 0x10000,
			InitIntegrity = 0x10000,
			AcceptIntegrity = 0x20000,
			InitManualCredValidation = 0x80000,
			InitUseSuppliedCreds = 0x80,
			InitIdentify = 0x20000,
			AcceptIdentify = 0x80000,
			ProxyBindings = 0x4000000,
			AllowMissingBindings = 0x10000000,
			UnverifiedTargetName = 0x20000000
		}

		internal enum Endianness
		{
			SECURITY_NETWORK_DREP = 0,
			SECURITY_NATIVE_DREP = 0x10
		}

		internal enum CredentialUse
		{
			SECPKG_CRED_INBOUND = 1,
			SECPKG_CRED_OUTBOUND,
			SECPKG_CRED_BOTH
		}

		internal struct CERT_CHAIN_ELEMENT
		{
			public uint cbSize;

			public IntPtr pCertContext;
		}

		internal struct SecPkgContext_IssuerListInfoEx
		{
			public SafeHandle aIssuers;

			public uint cIssuers;

			public unsafe SecPkgContext_IssuerListInfoEx(SafeHandle handle, byte[] nativeBuffer)
			{
				aIssuers = handle;
				fixed (byte* ptr = nativeBuffer)
				{
					cIssuers = *(uint*)(ptr + IntPtr.Size);
				}
			}
		}

		internal struct SCHANNEL_CRED
		{
			[Flags]
			public enum Flags
			{
				Zero = 0,
				SCH_CRED_NO_SYSTEM_MAPPER = 2,
				SCH_CRED_NO_SERVERNAME_CHECK = 4,
				SCH_CRED_MANUAL_CRED_VALIDATION = 8,
				SCH_CRED_NO_DEFAULT_CREDS = 0x10,
				SCH_CRED_AUTO_CRED_VALIDATION = 0x20,
				SCH_SEND_AUX_RECORD = 0x200000,
				SCH_USE_STRONG_CRYPTO = 0x400000
			}

			public const int CurrentVersion = 4;

			public int dwVersion;

			public int cCreds;

			public IntPtr paCred;

			public IntPtr hRootStore;

			public int cMappers;

			public IntPtr aphMappers;

			public int cSupportedAlgs;

			public IntPtr palgSupportedAlgs;

			public int grbitEnabledProtocols;

			public int dwMinimumCipherStrength;

			public int dwMaximumCipherStrength;

			public int dwSessionLifespan;

			public Flags dwFlags;

			public int reserved;
		}

		internal struct SecBuffer
		{
			public int cbBuffer;

			public SecurityBufferType BufferType;

			public IntPtr pvBuffer;

			public unsafe static readonly int Size = sizeof(SecBuffer);
		}

		internal struct SecBufferDesc
		{
			public readonly int ulVersion;

			public readonly int cBuffers;

			public unsafe void* pBuffers;

			public unsafe SecBufferDesc(int count)
			{
				ulVersion = 0;
				cBuffers = count;
				pBuffers = null;
			}
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
		internal struct SEC_WINNT_AUTH_IDENTITY_W
		{
			internal string User;

			internal int UserLength;

			internal string Domain;

			internal int DomainLength;

			internal string Password;

			internal int PasswordLength;

			internal int Flags;
		}

		internal const uint SECQOP_WRAP_NO_ENCRYPT = 2147483649u;

		internal const int SEC_I_RENEGOTIATE = 590625;

		internal const int SECPKG_NEGOTIATION_COMPLETE = 0;

		internal const int SECPKG_NEGOTIATION_OPTIMISTIC = 1;

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern int EncryptMessage(ref CredHandle contextHandle, [In] uint qualityOfProtection, [In][Out] ref SecBufferDesc inputOutput, [In] uint sequenceNumber);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int DecryptMessage([In] ref CredHandle contextHandle, [In][Out] ref SecBufferDesc inputOutput, [In] uint sequenceNumber, uint* qualityOfProtection);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern int QuerySecurityContextToken(ref CredHandle phContext, out SecurityContextTokenHandle handle);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern int FreeContextBuffer([In] IntPtr contextBuffer);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern int FreeCredentialsHandle(ref CredHandle handlePtr);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern int DeleteSecurityContext(ref CredHandle handlePtr);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int AcceptSecurityContext(ref CredHandle credentialHandle, [In] void* inContextPtr, [In] SecBufferDesc* inputBuffer, [In] ContextFlags inFlags, [In] Endianness endianness, ref CredHandle outContextPtr, [In][Out] ref SecBufferDesc outputBuffer, [In][Out] ref ContextFlags attributes, out long timeStamp);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int QueryContextAttributesW(ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] void* buffer);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern int SetContextAttributesW(ref CredHandle contextHandle, [In] ContextAttribute attribute, [In] byte[] buffer, [In] int bufferSize);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern int EnumerateSecurityPackagesW(out int pkgnum, out SafeFreeContextBuffer_SECURITY handle);

		[DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int AcquireCredentialsHandleW([In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] ref SEC_WINNT_AUTH_IDENTITY_W authdata, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, out long timeStamp);

		[DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int AcquireCredentialsHandleW([In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] IntPtr zero, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, out long timeStamp);

		[DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int AcquireCredentialsHandleW([In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] SafeSspiAuthDataHandle authdata, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, out long timeStamp);

		[DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int AcquireCredentialsHandleW([In] string principal, [In] string moduleName, [In] int usage, [In] void* logonID, [In] ref SCHANNEL_CRED authData, [In] void* keyCallback, [In] void* keyArgument, ref CredHandle handlePtr, out long timeStamp);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int InitializeSecurityContextW(ref CredHandle credentialHandle, [In] void* inContextPtr, [In] byte* targetName, [In] ContextFlags inFlags, [In] int reservedI, [In] Endianness endianness, [In] SecBufferDesc* inputBuffer, [In] int reservedII, ref CredHandle outContextPtr, [In][Out] ref SecBufferDesc outputBuffer, [In][Out] ref ContextFlags attributes, out long timeStamp);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int CompleteAuthToken([In] void* inContextPtr, [In][Out] ref SecBufferDesc inputBuffers);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal unsafe static extern int ApplyControlToken([In] void* inContextPtr, [In][Out] ref SecBufferDesc inputBuffers);

		[DllImport("sspicli.dll", ExactSpelling = true, SetLastError = true)]
		internal static extern SECURITY_STATUS SspiFreeAuthIdentity([In] IntPtr authData);

		[DllImport("sspicli.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)]
		internal static extern SECURITY_STATUS SspiEncodeStringsAsAuthIdentity([In] string userName, [In] string domainName, [In] string password, out SafeSspiAuthDataHandle authData);
	}
}
namespace Mono
{
	internal class CFType
	{
		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", EntryPoint = "CFGetTypeID")]
		public static extern IntPtr GetTypeID(IntPtr typeRef);
	}
	internal class CFObject : IDisposable, INativeObject
	{
		public const string CoreFoundationLibrary = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation";

		private const string SystemLibrary = "/usr/lib/libSystem.dylib";

		public IntPtr Handle { get; private set; }

		[DllImport("/usr/lib/libSystem.dylib")]
		public static extern IntPtr dlopen(string path, int mode);

		[DllImport("/usr/lib/libSystem.dylib")]
		private static extern IntPtr dlsym(IntPtr handle, string symbol);

		[DllImport("/usr/lib/libSystem.dylib")]
		public static extern void dlclose(IntPtr handle);

		public static IntPtr GetIndirect(IntPtr handle, string symbol)
		{
			return dlsym(handle, symbol);
		}

		public static CFString GetStringConstant(IntPtr handle, string symbol)
		{
			IntPtr intPtr = dlsym(handle, symbol);
			if (intPtr == IntPtr.Zero)
			{
				return null;
			}
			IntPtr intPtr2 = Marshal.ReadIntPtr(intPtr);
			if (intPtr2 == IntPtr.Zero)
			{
				return null;
			}
			return new CFString(intPtr2, own: false);
		}

		public static IntPtr GetIntPtr(IntPtr handle, string symbol)
		{
			IntPtr intPtr = dlsym(handle, symbol);
			if (intPtr == IntPtr.Zero)
			{
				return IntPtr.Zero;
			}
			return Marshal.ReadIntPtr(intPtr);
		}

		public static IntPtr GetCFObjectHandle(IntPtr handle, string symbol)
		{
			IntPtr intPtr = dlsym(handle, symbol);
			if (intPtr == IntPtr.Zero)
			{
				return IntPtr.Zero;
			}
			return Marshal.ReadIntPtr(intPtr);
		}

		public CFObject(IntPtr handle, bool own)
		{
			Handle = handle;
			if (!own)
			{
				Retain();
			}
		}

		~CFObject()
		{
			Dispose(disposing: false);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		internal static extern IntPtr CFRetain(IntPtr handle);

		private void Retain()
		{
			CFRetain(Handle);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		internal static extern void CFRelease(IntPtr handle);

		private void Release()
		{
			CFRelease(Handle);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (Handle != IntPtr.Zero)
			{
				Release();
				Handle = IntPtr.Zero;
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}
	}
	internal class CFArray : CFObject
	{
		private static readonly IntPtr kCFTypeArrayCallbacks;

		public int Count => (int)CFArrayGetCount(base.Handle);

		public IntPtr this[int index] => CFArrayGetValueAtIndex(base.Handle, (IntPtr)index);

		public CFArray(IntPtr handle, bool own)
			: base(handle, own)
		{
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFArrayCreate(IntPtr allocator, IntPtr values, IntPtr numValues, IntPtr callbacks);

		static CFArray()
		{
			IntPtr intPtr = CFObject.dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", 0);
			if (intPtr == IntPtr.Zero)
			{
				return;
			}
			try
			{
				kCFTypeArrayCallbacks = CFObject.GetIndirect(intPtr, "kCFTypeArrayCallBacks");
			}
			finally
			{
				CFObject.dlclose(intPtr);
			}
		}

		public static CFArray FromNativeObjects(params INativeObject[] values)
		{
			return new CFArray(Create(values), own: true);
		}

		public unsafe static IntPtr Create(params IntPtr[] values)
		{
			if (values == null)
			{
				throw new ArgumentNullException("values");
			}
			fixed (IntPtr* ptr = values)
			{
				return CFArrayCreate(IntPtr.Zero, (IntPtr)ptr, (IntPtr)values.Length, kCFTypeArrayCallbacks);
			}
		}

		internal unsafe static CFArray CreateArray(params IntPtr[] values)
		{
			if (values == null)
			{
				throw new ArgumentNullException("values");
			}
			fixed (IntPtr* ptr = values)
			{
				return new CFArray(CFArrayCreate(IntPtr.Zero, (IntPtr)ptr, (IntPtr)values.Length, kCFTypeArrayCallbacks), own: false);
			}
		}

		public static CFArray CreateArray(params INativeObject[] values)
		{
			return new CFArray(Create(values), own: true);
		}

		public static IntPtr Create(params INativeObject[] values)
		{
			if (values == null)
			{
				throw new ArgumentNullException("values");
			}
			IntPtr[] array = new IntPtr[values.Length];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = values[i].Handle;
			}
			return Create(array);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFArrayGetCount(IntPtr handle);

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFArrayGetValueAtIndex(IntPtr handle, IntPtr index);

		public static T[] ArrayFromHandle<T>(IntPtr handle, Func<IntPtr, T> creation) where T : class, INativeObject
		{
			if (handle == IntPtr.Zero)
			{
				return null;
			}
			IntPtr intPtr = CFArrayGetCount(handle);
			T[] array = new T[(int)intPtr];
			for (uint num = 0u; num < (uint)(int)intPtr; num++)
			{
				array[num] = creation(CFArrayGetValueAtIndex(handle, (IntPtr)num));
			}
			return array;
		}
	}
	internal class CFNumber : CFObject
	{
		public CFNumber(IntPtr handle, bool own)
			: base(handle, own)
		{
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		[return: MarshalAs(UnmanagedType.I1)]
		private static extern bool CFNumberGetValue(IntPtr handle, IntPtr type, [MarshalAs(UnmanagedType.I1)] out bool value);

		public static bool AsBool(IntPtr handle)
		{
			if (handle == IntPtr.Zero)
			{
				return false;
			}
			CFNumberGetValue(handle, (IntPtr)1, out bool value);
			return value;
		}

		public static implicit operator bool(CFNumber number)
		{
			return AsBool(number.Handle);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		[return: MarshalAs(UnmanagedType.I1)]
		private static extern bool CFNumberGetValue(IntPtr handle, IntPtr type, out int value);

		public static int AsInt32(IntPtr handle)
		{
			if (handle == IntPtr.Zero)
			{
				return 0;
			}
			CFNumberGetValue(handle, (IntPtr)9, out int value);
			return value;
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFNumberCreate(IntPtr allocator, IntPtr theType, IntPtr valuePtr);

		public static CFNumber FromInt32(int number)
		{
			return new CFNumber(CFNumberCreate(IntPtr.Zero, (IntPtr)9, (IntPtr)number), own: true);
		}

		public static implicit operator int(CFNumber number)
		{
			return AsInt32(number.Handle);
		}
	}
	internal struct CFRange
	{
		public IntPtr Location;

		public IntPtr Length;

		public CFRange(int loc, int len)
		{
			Location = (IntPtr)loc;
			Length = (IntPtr)len;
		}
	}
	internal class CFString : CFObject
	{
		private string str;

		public int Length
		{
			get
			{
				if (str != null)
				{
					return str.Length;
				}
				return (int)CFStringGetLength(base.Handle);
			}
		}

		public CFString(IntPtr handle, bool own)
			: base(handle, own)
		{
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFStringCreateWithCharacters(IntPtr alloc, IntPtr chars, IntPtr length);

		public unsafe static CFString Create(string value)
		{
			IntPtr intPtr;
			fixed (char* ptr = value)
			{
				intPtr = CFStringCreateWithCharacters(IntPtr.Zero, (IntPtr)ptr, (IntPtr)value.Length);
			}
			if (intPtr == IntPtr.Zero)
			{
				return null;
			}
			return new CFString(intPtr, own: true);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFStringGetLength(IntPtr handle);

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern int CFStringCompare(IntPtr theString1, IntPtr theString2, int compareOptions);

		public static int Compare(IntPtr string1, IntPtr string2, int compareOptions = 0)
		{
			return CFStringCompare(string1, string2, compareOptions);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFStringGetCharactersPtr(IntPtr handle);

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFStringGetCharacters(IntPtr handle, CFRange range, IntPtr buffer);

		public unsafe static string AsString(IntPtr handle)
		{
			if (handle == IntPtr.Zero)
			{
				return null;
			}
			int num = (int)CFStringGetLength(handle);
			if (num == 0)
			{
				return string.Empty;
			}
			IntPtr intPtr = CFStringGetCharactersPtr(handle);
			IntPtr intPtr2 = IntPtr.Zero;
			if (intPtr == IntPtr.Zero)
			{
				CFRange range = new CFRange(0, num);
				intPtr2 = Marshal.AllocHGlobal(num * 2);
				CFStringGetCharacters(handle, range, intPtr2);
				intPtr = intPtr2;
			}
			string result = new string((char*)(void*)intPtr, 0, num);
			if (intPtr2 != IntPtr.Zero)
			{
				Marshal.FreeHGlobal(intPtr2);
			}
			return result;
		}

		public override string ToString()
		{
			if (str == null)
			{
				str = AsString(base.Handle);
			}
			return str;
		}

		public static implicit operator string(CFString str)
		{
			return str.ToString();
		}

		public static implicit operator CFString(string str)
		{
			return Create(str);
		}
	}
	internal class CFData : CFObject
	{
		public IntPtr Length => CFDataGetLength(base.Handle);

		public IntPtr Bytes => CFDataGetBytePtr(base.Handle);

		public byte this[long idx]
		{
			get
			{
				if (idx < 0 || (ulong)idx > (ulong)(long)Length)
				{
					throw new ArgumentException("idx");
				}
				return Marshal.ReadByte(new IntPtr(Bytes.ToInt64() + idx));
			}
			set
			{
				throw new NotImplementedException("NSData arrays can not be modified, use an NSMutableData instead");
			}
		}

		public CFData(IntPtr handle, bool own)
			: base(handle, own)
		{
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFDataCreate(IntPtr allocator, IntPtr bytes, IntPtr length);

		public unsafe static CFData FromData(byte[] buffer)
		{
			fixed (byte* ptr = buffer)
			{
				return FromData((IntPtr)ptr, (IntPtr)buffer.Length);
			}
		}

		public static CFData FromData(IntPtr buffer, IntPtr length)
		{
			return new CFData(CFDataCreate(IntPtr.Zero, buffer, length), own: true);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		internal static extern IntPtr CFDataGetLength(IntPtr theData);

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		internal static extern IntPtr CFDataGetBytePtr(IntPtr theData);
	}
	internal class CFDictionary : CFObject
	{
		private static readonly IntPtr KeyCallbacks;

		private static readonly IntPtr ValueCallbacks;

		public IntPtr this[IntPtr key] => GetValue(key);

		static CFDictionary()
		{
			IntPtr intPtr = CFObject.dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", 0);
			if (intPtr == IntPtr.Zero)
			{
				return;
			}
			try
			{
				KeyCallbacks = CFObject.GetIndirect(intPtr, "kCFTypeDictionaryKeyCallBacks");
				ValueCallbacks = CFObject.GetIndirect(intPtr, "kCFTypeDictionaryValueCallBacks");
			}
			finally
			{
				CFObject.dlclose(intPtr);
			}
		}

		public CFDictionary(IntPtr handle, bool own)
			: base(handle, own)
		{
		}

		public static CFDictionary FromObjectAndKey(IntPtr obj, IntPtr key)
		{
			return new CFDictionary(CFDictionaryCreate(IntPtr.Zero, new IntPtr[1] { key }, new IntPtr[1] { obj }, (IntPtr)1, KeyCallbacks, ValueCallbacks), own: true);
		}

		public static CFDictionary FromKeysAndObjects(IList<Tuple<IntPtr, IntPtr>> items)
		{
			IntPtr[] array = new IntPtr[items.Count];
			IntPtr[] array2 = new IntPtr[items.Count];
			for (int i = 0; i < items.Count; i++)
			{
				array[i] = items[i].Item1;
				array2[i] = items[i].Item2;
			}
			return new CFDictionary(CFDictionaryCreate(IntPtr.Zero, array, array2, (IntPtr)items.Count, KeyCallbacks, ValueCallbacks), own: true);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFDictionaryCreate(IntPtr allocator, IntPtr[] keys, IntPtr[] vals, IntPtr len, IntPtr keyCallbacks, IntPtr valCallbacks);

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFDictionaryGetValue(IntPtr handle, IntPtr key);

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFDictionaryCreateCopy(IntPtr allocator, IntPtr handle);

		public CFDictionary Copy()
		{
			return new CFDictionary(CFDictionaryCreateCopy(IntPtr.Zero, base.Handle), own: true);
		}

		public CFMutableDictionary MutableCopy()
		{
			return new CFMutableDictionary(CFDictionaryCreateMutableCopy(IntPtr.Zero, IntPtr.Zero, base.Handle), own: true);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFDictionaryCreateMutableCopy(IntPtr allocator, IntPtr capacity, IntPtr theDict);

		public IntPtr GetValue(IntPtr key)
		{
			return CFDictionaryGetValue(base.Handle, key);
		}
	}
	internal class CFMutableDictionary : CFDictionary
	{
		public CFMutableDictionary(IntPtr handle, bool own)
			: base(handle, own)
		{
		}

		public void SetValue(IntPtr key, IntPtr val)
		{
			CFDictionarySetValue(base.Handle, key, val);
		}

		public static CFMutableDictionary Create()
		{
			IntPtr intPtr = CFDictionaryCreateMutable(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
			if (intPtr == IntPtr.Zero)
			{
				throw new InvalidOperationException();
			}
			return new CFMutableDictionary(intPtr, own: true);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern void CFDictionarySetValue(IntPtr handle, IntPtr key, IntPtr val);

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFDictionaryCreateMutable(IntPtr allocator, IntPtr capacity, IntPtr keyCallback, IntPtr valueCallbacks);
	}
	internal class CFBoolean : INativeObject, IDisposable
	{
		private IntPtr handle;

		public static readonly CFBoolean True;

		public static readonly CFBoolean False;

		public IntPtr Handle => handle;

		public bool Value => CFBooleanGetValue(handle);

		static CFBoolean()
		{
			IntPtr intPtr = CFObject.dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", 0);
			if (intPtr == IntPtr.Zero)
			{
				return;
			}
			try
			{
				True = new CFBoolean(CFObject.GetCFObjectHandle(intPtr, "kCFBooleanTrue"), owns: false);
				False = new CFBoolean(CFObject.GetCFObjectHandle(intPtr, "kCFBooleanFalse"), owns: false);
			}
			finally
			{
				CFObject.dlclose(intPtr);
			}
		}

		internal CFBoolean(IntPtr handle, bool owns)
		{
			this.handle = handle;
			if (!owns)
			{
				CFObject.CFRetain(handle);
			}
		}

		~CFBoolean()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (handle != IntPtr.Zero)
			{
				CFObject.CFRelease(handle);
				handle = IntPtr.Zero;
			}
		}

		public static implicit operator bool(CFBoolean value)
		{
			return value.Value;
		}

		public static explicit operator CFBoolean(bool value)
		{
			return FromBoolean(value);
		}

		public static CFBoolean FromBoolean(bool value)
		{
			if (!value)
			{
				return False;
			}
			return True;
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		[return: MarshalAs(UnmanagedType.I1)]
		private static extern bool CFBooleanGetValue(IntPtr boolean);

		public static bool GetValue(IntPtr boolean)
		{
			return CFBooleanGetValue(boolean);
		}
	}
	internal class CFDate : INativeObject, IDisposable
	{
		private IntPtr handle;

		public IntPtr Handle => handle;

		internal CFDate(IntPtr handle, bool owns)
		{
			this.handle = handle;
			if (!owns)
			{
				CFObject.CFRetain(handle);
			}
		}

		~CFDate()
		{
			Dispose(disposing: false);
		}

		[DllImport("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")]
		private static extern IntPtr CFDateCreate(IntPtr allocator, double at);

		public static CFDate Create(DateTime date)
		{
			DateTime dateTime = new DateTime(2001, 1, 1);
			double totalSeconds = (date - dateTime).TotalSeconds;
			IntPtr intPtr = CFDateCreate(IntPtr.Zero, totalSeconds);
			if (intPtr == IntPtr.Zero)
			{
				throw new NotSupportedException();
			}
			return new CFDate(intPtr, owns: true);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (handle != IntPtr.Zero)
			{
				CFObject.CFRelease(handle);
				handle = IntPtr.Zero;
			}
		}
	}
	internal class SystemCertificateProvider : ISystemCertificateProvider
	{
		private static MonoTlsProvider provider;

		private static int initialized;

		private static X509PalImpl x509pal;

		private static object syncRoot = new object();

		public MonoTlsProvider Provider
		{
			get
			{
				EnsureInitialized();
				return provider;
			}
		}

		public X509PalImpl X509Pal
		{
			get
			{
				EnsureInitialized();
				return x509pal;
			}
		}

		private static X509PalImpl GetX509Pal()
		{
			MonoTlsProvider obj = provider;
			if (((obj != null) ? new Guid?(obj.ID) : null) == MonoTlsProviderFactory.BtlsId)
			{
				return new X509PalImplBtls(provider);
			}
			return new X509PalImplMono();
		}

		private static void EnsureInitialized()
		{
			lock (syncRoot)
			{
				if (Interlocked.CompareExchange(ref initialized, 1, 0) == 0)
				{
					provider = MonoTlsProviderFactory.GetProvider();
					x509pal = GetX509Pal();
				}
			}
		}

		public X509CertificateImpl Import(byte[] data, CertificateImportFlags importFlags = 0)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (data == null || data.Length == 0)
			{
				return null;
			}
			X509CertificateImpl val = null;
			if ((importFlags & 1) == 0)
			{
				val = X509Pal.Import(data);
				if (val != null)
				{
					return val;
				}
			}
			if ((importFlags & 2) != 0)
			{
				return null;
			}
			return (X509CertificateImpl)(object)X509Pal.ImportFallback(data);
		}

		X509CertificateImpl ISystemCertificateProvider.Import(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags, CertificateImportFlags importFlags)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			return (X509CertificateImpl)(object)Import(data, password, keyStorageFlags, importFlags);
		}

		public X509Certificate2Impl Import(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags, CertificateImportFlags importFlags = 0)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			if (data == null || data.Length == 0)
			{
				return null;
			}
			X509Certificate2Impl x509Certificate2Impl = null;
			if ((importFlags & 1) == 0)
			{
				x509Certificate2Impl = X509Pal.Import(data, password, keyStorageFlags);
				if (x509Certificate2Impl != null)
				{
					return x509Certificate2Impl;
				}
			}
			if ((importFlags & 2) != 0)
			{
				return null;
			}
			return X509Pal.ImportFallback(data, password, keyStorageFlags);
		}

		X509CertificateImpl ISystemCertificateProvider.Import(X509Certificate cert, CertificateImportFlags importFlags)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return (X509CertificateImpl)(object)Import(cert, importFlags);
		}

		public X509Certificate2Impl Import(X509Certificate cert, CertificateImportFlags importFlags = 0)
		{
			//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)
			//IL_003c: 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)
			if (cert.Impl == null)
			{
				return null;
			}
			if (cert.Impl is X509Certificate2Impl x509Certificate2Impl)
			{
				return (X509Certificate2Impl)(object)((X509CertificateImpl)x509Certificate2Impl).Clone();
			}
			if ((importFlags & 1) == 0)
			{
				X509Certificate2Impl x509Certificate2Impl2 = X509Pal.Import(cert);
				if (x509Certificate2Impl2 != null)
				{
					return x509Certificate2Impl2;
				}
			}
			if ((importFlags & 2) != 0)
			{
				return null;
			}
			return X509Pal.ImportFallback(cert.GetRawCertData());
		}
	}
	internal class SystemDependencyProvider : ISystemDependencyProvider
	{
		private static SystemDependencyProvider instance;

		private static object syncRoot = new object();

		public static SystemDependencyProvider Instance
		{
			get
			{
				Initialize();
				return instance;
			}
		}

		ISystemCertificateProvider ISystemDependencyProvider.CertificateProvider => (ISystemCertificateProvider)(object)CertificateProvider;

		public SystemCertificateProvider CertificateProvider { get; }

		public X509PalImpl X509Pal => CertificateProvider.X509Pal;

		internal static void Initialize()
		{
			lock (syncRoot)
			{
				if (instance == null)
				{
					instance = new SystemDependencyProvider();
				}
			}
		}

		private SystemDependencyProvider()
		{
			CertificateProvider = new SystemCertificateProvider();
			DependencyInjector.Register((ISystemDependencyProvider)(object)this);
		}
	}
	internal static class X509Pal
	{
		public static X509PalImpl Instance => SystemDependencyProvider.Instance.X509Pal;
	}
	internal class X509PalImplMono : X509PalImpl
	{
		public override X509CertificateImpl Import(byte[] data)
		{
			return (X509CertificateImpl)(object)ImportFallback(data);
		}

		public override X509Certificate2Impl Import(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
		{
			return ImportFallback(data, password, keyStorageFlags);
		}

		public override X509Certificate2Impl Import(X509Certificate cert)
		{
			return null;
		}
	}
	internal abstract class X509PalImpl
	{
		private static byte[] signedData = new byte[9] { 42, 134, 72, 134, 247, 13, 1, 7, 2 };

		public bool SupportsLegacyBasicConstraintsExtension => false;

		public abstract X509CertificateImpl Import(byte[] data);

		public abstract X509Certificate2Impl Import(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags);

		public abstract X509Certificate2Impl Import(X509Certificate cert);

		private static byte[] PEM(string type, byte[] data)
		{
			string @string = Encoding.ASCII.GetString(data);
			string text = $"-----BEGIN {type}-----";
			string value = $"-----END {type}-----";
			int num = @string.IndexOf(text) + text.Length;
			int num2 = @string.IndexOf(value, num);
			return Convert.FromBase64String(@string.Substring(num, num2 - num));
		}

		protected static byte[] ConvertData(byte[] data)
		{
			if (data == null || data.Length == 0)
			{
				return data;
			}
			if (data[0] != 48)
			{
				try
				{
					return PEM("CERTIFICATE", data);
				}
				catch
				{
				}
			}
			return data;
		}

		internal X509Certificate2Impl ImportFallback(byte[] data)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Expected O, but got Unknown
			data = ConvertData(data);
			SafePasswordHandle val = new SafePasswordHandle((string)null);
			try
			{
				return new X509Certificate2ImplMono(data, val, X509KeyStorageFlags.DefaultKeySet);
			}
			finally
			{
				((IDisposable)val)?.Dispose();
			}
		}

		internal X509Certificate2Impl ImportFallback(byte[] data, SafePasswordHandle password, X509KeyStorageFlags keyStorageFlags)
		{
			return new X509Certificate2ImplMono(data, password, keyStorageFlags);
		}

		public X509ContentType GetCertContentType(byte[] rawData)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			if (rawData == null || rawData.Length == 0)
			{
				throw new ArgumentException("rawData");
			}
			if (rawData[0] == 48)
			{
				try
				{
					ASN1 val = new ASN1(rawData);
					if (val.Count == 3 && val[0].Tag == 48 && val[1].Tag == 48 && val[2].Tag == 3)
					{
						return X509ContentType.Cert;
					}
					if (val.Count == 3 && val[0].Tag == 2 && val[1].Tag == 48 && val[2].Tag == 48)
					{
						return X509ContentType.Pfx;
					}
					if (val.Count > 0 && val[0].Tag == 6 && val[0].CompareValue(signedData))
					{
						return X509ContentType.Pkcs7;
					}
					return X509ContentType.Unknown;
				}
				catch (Exception)
				{
					return X509ContentType.Unknown;
				}
			}
			if (Encoding.ASCII.GetString(rawData).IndexOf("-----BEGIN CERTIFICATE-----") >= 0)
			{
				return X509ContentType.Cert;
			}
			try
			{
				new AuthenticodeDeformatter(rawData);
				return X509ContentType.Authenticode;
			}
			catch
			{
				return X509ContentType.Unknown;
			}
		}

		public X509ContentType GetCertContentType(string fileName)
		{
			if (fileName == null)
			{
				throw new ArgumentNullException("fileName");
			}
			if (fileName.Length == 0)
			{
				throw new ArgumentException("fileName");
			}
			byte[] rawData = File.ReadAllBytes(fileName);
			return GetCertContentType(rawData);
		}
	}
}
namespace Mono.Audio
{
	internal abstract class AudioData
	{
		protected const int buffer_size = 4096;

		private bool stopped;

		public abstract int Channels { get; }

		public abstract int Rate { get; }

		public abstract AudioFormat Format { get; }

		public virtual bool IsStopped
		{
			get
			{
				return stopped;
			}
			set
			{
				stopped = value;
			}
		}

		public virtual void Setup(AudioDevice dev)
		{
			dev.SetFormat(Format, Channels, Rate);
		}

		public abstract void Play(AudioDevice dev);
	}
	internal class WavData : AudioData
	{
		private Stream stream;

		private short channels;

		private ushort frame_divider;

		private int sample_rate;

		private int data_len;

		private long data_offset;

		private AudioFormat format;

		public override int Channels => channels;

		public override int Rate => sample_rate;

		public override AudioFormat Format => format;

		public WavData(Stream data)
		{
			stream = data;
			byte[] array = new byte[44];
			int num = stream.Read(array, 0, 12);
			if (num != 12 || array[0] != 82 || array[1] != 73 || array[2] != 70 || array[3] != 70 || array[8] != 87 || array[9] != 65 || array[10] != 86 || array[11] != 69)
			{
				throw new Exception("incorrect format" + num);
			}
			num = stream.Read(array, 0, 8);
			if (num == 8 && array[0] == 102 && array[1] == 109 && array[2] == 116 && array[3] == 32)
			{
				int num2 = array[4];
				num2 |= array[5] << 8;
				num2 |= array[6] << 16;
				num2 |= array[7] << 24;
				num = stream.Read(array, 0, num2);
				if (num2 == num)
				{
					int num3 = 0;
					if ((array[num3++] | (array[num3++] << 8)) != 1)
					{
						throw new Exception("incorrect format (not PCM)");
					}
					channels = (short)(array[num3++] | (array[num3++] << 8));
					sample_rate = array[num3++];
					sample_rate |= array[num3++] << 8;
					sample_rate |= array[num3++] << 16;
					sample_rate |= array[num3++] << 24;
					_ = array[num3++] | (array[num3++] << 8) | (array[num3++] << 16);
					_ = array[num3++];
					num3 += 2;
					switch (array[num3++] | (array[num3++] << 8))
					{
					case 8:
						frame_divider = 1;
						format = AudioFormat.U8;
						break;
					case 16:
						frame_divider = 2;
						format = AudioFormat.S16_LE;
						break;
					default:
						throw new Exception("bits per sample");
					}
					num = stream.Read(array, 0, 8);
					if (num == 8)
					{
						if (array[0] == 102 && array[1] == 97 && array[2] == 99 && array[3] == 116)
						{
							int num4 = array[4];
							num4 |= array[5] << 8;
							num4 |= array[6] << 16;
							num4 |= array[7] << 24;
							num = stream.Read(array, 0, num4);
							num = stream.Read(array, 0, 8);
						}
						if (array[0] != 100 || array[1] != 97 || array[2] != 116 || array[3] != 97)
						{
							throw new Exception("incorrect format (data/fact chunck)");
						}
						int num5 = array[4];
						num5 |= array[5] << 8;
						num5 |= array[6] << 16;
						num5 |= array[7] << 24;
						data_len = num5;
						data_offset = stream.Position;
					}
					return;
				}
				throw new Exception("Error: Can't Read " + num2 + " bytes from stream (" + num + " bytes read");
			}
			throw new Exception("incorrect format (fmt)");
		}

		public override void Play(AudioDevice dev)
		{
			int num = 0;
			int num2 = 0;
			int chunkSize = (int)dev.ChunkSize;
			int num3 = data_len;
			byte[] array = new byte[data_len];
			byte[] array2 = new byte[chunkSize];
			stream.Position = data_offset;
			stream.Read(array, 0, data_len);
			while (!IsStopped && num3 >= 0)
			{
				Buffer.BlockCopy(array, num2, array2, 0, chunkSize);
				num = dev.PlaySample(array2, chunkSize / (frame_divider * channels));
				if (num > 0)
				{
					num2 += num * frame_divider * channels;
					num3 -= num * frame_divider * channels;
				}
			}
		}
	}
	internal class AuData : AudioData
	{
		private Stream stream;

		private short channels;

		private ushort frame_divider;

		private int sample_rate;

		private int data_len;

		private AudioFormat format;

		public override int Channels => channels;

		public override int Rate => sample_rate;

		public override AudioFormat Format => format;

		public AuData(Stream data)
		{
			stream = data;
			byte[] array = new byte[24];
			int num = stream.Read(array, 0, 24);
			if (num != 24 || array[0] != 46 || array[1] != 115 || array[2] != 110 || array[3] != 100)
			{
				throw new Exception("incorrect format" + num);
			}
			int num2 = array[7];
			num2 |= array[6] << 8;
			num2 |= array[5] << 16;
			num2 |= array[4] << 24;
			data_len = array[11];
			data_len |= array[10] << 8;
			data_len |= array[9] << 16;
			data_len |= array[8] << 24;
			int num3 = array[15];
			num3 |= array[14] << 8;
			num3 |= array[13] << 16;
			num3 |= array[12] << 24;
			sample_rate = array[19];
			sample_rate |= array[18] << 8;
			sample_rate |= array[17] << 16;
			sample_rate |= array[16] << 24;
			int num4 = array[23];
			num4 |= array[22] << 8;
			num4 |= array[21] << 16;
			num4 |= array[20] << 24;
			channels = (short)num4;
			if (num2 < 24 || (num4 != 1 && num4 != 2))
			{
				throw new Exception("incorrect format offset" + num2);
			}
			if (num2 != 24)
			{
				for (int i = 24; i < num2; i++)
				{
					stream.ReadByte();
				}
			}
			if (num3 == 1)
			{
				frame_divider = 1;
				format = AudioFormat.MU_LAW;
				if (data_len == -1)
				{
					data_len = (int)stream.Length - num2;
				}
				return;
			}
			throw new Exception("incorrect format encoding" + num3);
		}

		public override void Play(AudioDevice dev)
		{
			int num = 0;
			int num2 = 0;
			int chunkSize = (int)dev.ChunkSize;
			int num3 = data_len;
			byte[] array = new byte[data_len];
			byte[] array2 = new byte[chunkSize];
			stream.Position = 0L;
			stream.Read(array, 0, data_len);
			while (!IsStopped && num3 >= 0)
			{
				Buffer.BlockCopy(array, num2, array2, 0, chunkSize);
				num = dev.PlaySample(array2, chunkSize / (frame_divider * channels));
				if (num > 0)
				{
					num2 += num * frame_divider * channels;
					num3 -= num * frame_divider * channels;
				}
			}
		}
	}
	internal enum AudioFormat
	{
		S8,
		U8,
		S16_LE,
		S16_BE,
		U16_LE,
		U16_BE,
		S24_LE,
		S24_BE,
		U24_LE,
		U24_BE,
		S32_LE,
		S32_BE,
		U32_LE,
		U32_BE,
		FLOAT_LE,
		FLOAT_BE,
		FLOAT64_LE,
		FLOAT64_BE,
		IEC958_SUBFRAME_LE,
		IEC958_SUBFRAME_BE,
		MU_LAW,
		A_LAW,
		IMA_ADPCM,
		MPEG,
		GSM
	}
	internal class AudioDevice
	{
		protected uint chunk_size;

		public uint ChunkSize => chunk_size;

		private static AudioDevice TryAlsa(string name)
		{
			try
			{
				return new AlsaDevice(name);
			}
			catch
			{
				return null;
			}
		}

		public static AudioDevice CreateDevice(string name)
		{
			AudioDevice audioDevice = TryAlsa(name);
			if (audioDevice == null)
			{
				audioDevice = new AudioDevice();
			}
			return audioDevice;
		}

		public virtual bool SetFormat(AudioFormat format, int channels, int rate)
		{
			return true;
		}

		public virtual int PlaySample(byte[] buffer, int num_frames)
		{
			return num_frames;
		}

		public virtual int XRunRecovery(int err)
		{
			return err;
		}

		public virtual void Wait()
		{
		}
	}
	internal class AlsaDevice : AudioDevice, IDisposable
	{
		private IntPtr handle;

		private IntPtr hw_param;

		private IntPtr sw_param;

		[DllImport("libasound")]
		private static extern int snd_pcm_open(ref IntPtr handle, string pcm_name, int stream, int mode);

		[DllImport("libasound")]
		private static extern int snd_pcm_close(IntPtr handle);

		[DllImport("libasound")]
		private static extern int snd_pcm_drain(IntPtr handle);

		[DllImport("libasound")]
		private static extern int snd_pcm_writei(IntPtr handle, byte[] buf, int size);

		[DllImport("libasound")]
		private static extern int snd_pcm_set_params(IntPtr handle, int format, int access, int channels, int rate, int soft_resample, int latency);

		[DllImport("libasound")]
		private static extern int snd_pcm_state(IntPtr handle);

		[DllImport("libasound")]
		private static extern int snd_pcm_prepare(IntPtr handle);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params(IntPtr handle, IntPtr param);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_malloc(ref IntPtr param);

		[DllImport("libasound")]
		private static extern void snd_pcm_hw_params_free(IntPtr param);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_any(IntPtr handle, IntPtr param);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_set_access(IntPtr handle, IntPtr param, int access);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_set_format(IntPtr handle, IntPtr param, int format);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_set_channels(IntPtr handle, IntPtr param, uint channel);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_set_rate_near(IntPtr handle, IntPtr param, ref uint rate, ref int dir);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_set_period_time_near(IntPtr handle, IntPtr param, ref uint period, ref int dir);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_get_period_size(IntPtr param, ref uint period, ref int dir);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_set_buffer_size_near(IntPtr handle, IntPtr param, ref uint buff_size);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_get_buffer_time_max(IntPtr param, ref uint buffer_time, ref int dir);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_set_buffer_time_near(IntPtr handle, IntPtr param, ref uint BufferTime, ref int dir);

		[DllImport("libasound")]
		private static extern int snd_pcm_hw_params_get_buffer_size(IntPtr param, ref uint BufferSize);

		[DllImport("libasound")]
		private static extern int snd_pcm_sw_params(IntPtr handle, IntPtr param);

		[DllImport("libasound")]
		private static extern int snd_pcm_sw_params_malloc(ref IntPtr param);

		[DllImport("libasound")]
		private static extern void snd_pcm_sw_params_free(IntPtr param);

		[DllImport("libasound")]
		private static extern int snd_pcm_sw_params_current(IntPtr handle, IntPtr param);

		[DllImport("libasound")]
		private static extern int snd_pcm_sw_params_set_avail_min(IntPtr handle, IntPtr param, uint frames);

		[DllImport("libasound")]
		private static extern int snd_pcm_sw_params_set_start_threshold(IntPtr handle, IntPtr param, uint StartThreshold);

		public AlsaDevice(string name)
		{
			if (name == null)
			{
				name = "default";
			}
			int num = snd_pcm_open(ref handle, name, 0, 0);
			if (num < 0)
			{
				throw new Exception("no open " + num);
			}
		}

		~AlsaDevice()
		{
			Dispose(disposing: false);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (sw_param != IntPtr.Zero)
			{
				snd_pcm_sw_params_free(sw_param);
			}
			if (hw_param != IntPtr.Zero)
			{
				snd_pcm_hw_params_free(hw_param);
			}
			if (handle != IntPtr.Zero)
			{
				snd_pcm_close(handle);
			}
			sw_param = IntPtr.Zero;
			hw_param = IntPtr.Zero;
			handle = IntPtr.Zero;
		}

		public override bool SetFormat(AudioFormat format, int channels, int rate)
		{
			uint period = 0u;
			uint period2 = 0u;
			uint BufferSize = 0u;
			uint buffer_time = 0u;
			int num = 0;
			uint rate2 = (uint)rate;
			if (snd_pcm_hw_params_malloc(ref hw_param) == 0)
			{
				snd_pcm_hw_params_any(handle, hw_param);
				snd_pcm_hw_params_set_access(handle, hw_param, 3);
				snd_pcm_hw_params_set_format(handle, hw_param, (int)format);
				snd_pcm_hw_params_set_channels(handle, hw_param, (uint)channels);
				num = 0;
				snd_pcm_hw_params_set_rate_near(handle, hw_param, ref rate2, ref num);
				num = 0;
				snd_pcm_hw_params_get_buffer_time_max(hw_param, ref buffer_time, ref num);
				if (buffer_time > 500000)
				{
					buffer_time = 500000u;
				}
				if (buffer_time != 0)
				{
					period = buffer_time / 4;
				}
				num = 0;
				snd_pcm_hw_params_set_period_time_near(handle, hw_param, ref period, ref num);
				num = 0;
				snd_pcm_hw_params_set_buffer_time_near(handle, hw_param, ref buffer_time, ref num);
				snd_pcm_hw_params_get_period_size(hw_param, ref period2, ref num);
				chunk_size = period2;
				snd_pcm_hw_params_get_buffer_size(hw_param, ref BufferSize);
				snd_pcm_hw_params(handle, hw_param);
			}
			else
			{
				Console.WriteLine("failed to alloc Alsa hw param struct");
			}
			int num2 = snd_pcm_sw_params_malloc(ref sw_param);
			if (num2 == 0)
			{
				snd_pcm_sw_params_current(handle, sw_param);
				snd_pcm_sw_params_set_avail_min(handle, sw_param, chunk_size);
				snd_pcm_sw_params_set_start_threshold(handle, sw_param, BufferSize);
				snd_pcm_sw_params(handle, sw_param);
			}
			else
			{
				Console.WriteLine("failed to alloc Alsa sw param struct");
			}
			if (hw_param != IntPtr.Zero)
			{
				snd_pcm_hw_params_free(hw_param);
				hw_param = IntPtr.Zero;
			}
			if (sw_param != IntPtr.Zero)
			{
				snd_pcm_sw_params_free(sw_param);
				sw_param = IntPtr.Zero;
			}
			return num2 == 0;
		}

		public override int PlaySample(byte[] buffer, int num_frames)
		{
			int num;
			do
			{
				num = snd_pcm_writei(handle, buffer, num_frames);
				if (num < 0)
				{
					XRunRecovery(num);
				}
			}
			while (num < 0);
			return num;
		}

		public override int XRunRecovery(int err)
		{
			int result = 0;
			if (-32 == err)
			{
				result = snd_pcm_prepare(handle);
			}
			return result;
		}

		public override void Wait()
		{
			snd_pcm_drain(handle);
		}
	}
	internal class Win32SoundPlayer : IDisposable
	{
		private enum SoundFlags : uint
		{
			SND_SYNC = 0u,
			SND_ASYNC = 1u,
			SND_NODEFAULT = 2u,
			SND_MEMORY = 4u,
			SND_LOOP = 8u,
			SND_FILENAME = 0x20000u
		}

		private byte[] _buffer;

		private bool _disposed;

		public Stream Stream
		{
			set
			{
				Stop();
				if (value != null)
				{
					_buffer = new byte[value.Length];
					value.Read(_buffer, 0, _buffer.Length);
				}
				else
				{
					_buffer = new byte[0];
				}
			}
		}

		public Win32SoundPlayer(Stream s)
		{
			if (s != null)
			{
				_buffer = new byte[s.Length];
				s.Read(_buffer, 0, _buffer.Length);
			}
			else
			{
				_buffer = new byte[0];
			}
		}

		[DllImport("winmm.dll", SetLastError = true)]
		private static extern bool PlaySound(byte[] ptrToSound, UIntPtr hmod, SoundFlags flags);

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		~Win32SoundPlayer()
		{
			Dispose(disposing: false);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				Stop();
				_disposed = true;
			}
		}

		public void Play()
		{
			PlaySound(_buffer, UIntPtr.Zero, (SoundFlags)5u);
		}

		public void PlayLooping()
		{
			PlaySound(_buffer, UIntPtr.Zero, (SoundFlags)13u);
		}

		public void PlaySync()
		{
			PlaySound(_buffer, UIntPtr.Zero, (SoundFlags)6u);
		}

		public void Stop()
		{
			PlaySound(null, UIntPtr.Zero, SoundFlags.SND_SYNC);
		}
	}
}
namespace Mono.Util
{
	[Conditional("FULL_AOT_RUNTIME")]
	[Conditional("UNITY")]
	[AttributeUsage(AttributeTargets.Method)]
	[Conditional("MONOTOUCH")]
	internal sealed class MonoPInvokeCallbackAttribute : Attribute
	{
		public MonoPInvokeCallbackAttribute(Type t)
		{
		}
	}
}
namespace Mono.Unity
{
	internal static class CertHelper
	{
		public unsafe static void AddCertificatesToNativeChain(UnityTls.unitytls_x509list* nativeCertificateChain, X509CertificateCollection certificates, UnityTls.unitytls_errorstate* errorState)
		{
			foreach (X509Certificate certificate in certificates)
			{
				AddCertificateToNativeChain(nativeCertificateChain, certificate, errorState);
			}
		}

		public unsafe static void AddCertificateToNativeChain(UnityTls.unitytls_x509list* nativeCertificateChain, X509Certificate certificate, UnityTls.unitytls_errorstate* errorState)
		{
			byte[] rawCertData = certificate.GetRawCertData();
			fixed (byte* buffer = rawCertData)
			{
				UnityTls.NativeInterface.unitytls_x509list_append_der(nativeCertificateChain, buffer, (IntPtr)rawCertData.Length, errorState);
			}
			if (!(certificate.Impl is X509Certificate2Impl x509Certificate2Impl))
			{
				return;
			}
			X509CertificateImplCollection intermediateCertificates = x509Certificate2Impl.IntermediateCertificates;
			if (intermediateCertificates != null && intermediateCertificates.Count > 0)
			{
				for (int i = 0; i < intermediateCertificates.Count; i++)
				{
					AddCertificateToNativeChain(nativeCertificateChain, new X509Certificate(intermediateCertificates[i]), errorState);
				}
			}
		}
	}
	internal static class Debug
	{
		public static void CheckAndThrow(UnityTls.unitytls_errorstate errorState, string context, AlertDescription defaultAlert = 80)
		{
			//IL_0020: 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 (errorState.code == UnityTls.unitytls_error_code.UNITYTLS_SUCCESS)
			{
				return;
			}
			string text = $"{context} - error code: {errorState.code}";
			throw new TlsException(defaultAlert, text);
		}

		public static void CheckAndThrow(UnityTls.unitytls_errorstate errorState, UnityTls.unitytls_x509verify_result verifyResult, string context, AlertDescription defaultAlert = 80)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			if (verifyResult == UnityTls.unitytls_x509verify_result.UNITYTLS_X509VERIFY_SUCCESS)
			{
				CheckAndThrow(errorState, context, defaultAlert);
				return;
			}
			AlertDescription val = UnityTlsConversions.VerifyResultToAlertDescription(verifyResult, defaultAlert);
			string text = $"{context} - error code: {errorState.code}, verify result: {verifyResult}";
			throw new TlsException(val, text);
		}
	}
	internal static class UnityTls
	{
		public enum unitytls_error_code : uint
		{
			UNITYTLS_SUCCESS = 0u,
			UNITYTLS_INVALID_ARGUMENT = 1u,
			UNITYTLS_INVALID_FORMAT = 2u,
			UNITYTLS_INVALID_PASSWORD = 3u,
			UNITYTLS_INVALID_STATE = 4u,
			UNITYTLS_BUFFER_OVERFLOW = 5u,
			UNITYTLS_OUT_OF_MEMORY = 6u,
			UNITYTLS_INTERNAL_ERROR = 7u,
			UNITYTLS_NOT_SUPPORTED = 8u,
			UNITYTLS_ENTROPY_SOURCE_FAILED = 9u,
			UNITYTLS_STREAM_CLOSED = 10u,
			UNITYTLS_USER_CUSTOM_ERROR_START = 1048576u,
			UNITYTLS_USER_WOULD_BLOCK = 1048577u,
			UNITYTLS_USER_READ_FAILED = 1048578u,
			UNITYTLS_USER_WRITE_FAILED = 1048579u,
			UNITYTLS_USER_UNKNOWN_ERROR = 1048580u,
			UNITYTLS_USER_CUSTOM_ERROR_END = 2097152u
		}

		public struct unitytls_errorstate
		{
			private uint magic;

			public unitytls_error_code code;

			private ulong reserved;
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct unitytls_key
		{
		}

		public struct unitytls_key_ref
		{
			public ulong handle;
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct unitytls_x509
		{
		}

		public struct unitytls_x509_ref
		{
			public ulong handle;
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct unitytls_x509list
		{
		}

		public struct unitytls_x509list_ref
		{
			public ulong handle;
		}

		[Flags]
		public enum unitytls_x509verify_result : uint
		{
			UNITYTLS_X509VERIFY_SUCCESS = 0u,
			UNITYTLS_X509VERIFY_NOT_DONE = 0x80000000u,
			UNITYTLS_X509VERIFY_FATAL_ERROR = uint.MaxValue,
			UNITYTLS_X509VERIFY_FLAG_EXPIRED = 1u,
			UNITYTLS_X509VERIFY_FLAG_REVOKED = 2u,
			UNITYTLS_X509VERIFY_FLAG_CN_MISMATCH = 4u,
			UNITYTLS_X509VERIFY_FLAG_NOT_TRUSTED = 8u,
			UNITYTLS_X509VERIFY_FLAG_USER_ERROR1 = 0x10000u,
			UNITYTLS_X509VERIFY_FLAG_USER_ERROR2 = 0x20000u,
			UNITYTLS_X509VERIFY_FLAG_USER_ERROR3 = 0x40000u,
			UNITYTLS_X509VERIFY_FLAG_USER_ERROR4 = 0x80000u,
			UNITYTLS_X509VERIFY_FLAG_USER_ERROR5 = 0x100000u,
			UNITYTLS_X509VERIFY_FLAG_USER_ERROR6 = 0x200000u,
			UNITYTLS_X509VERIFY_FLAG_USER_ERROR7 = 0x400000u,
			UNITYTLS_X509VERIFY_FLAG_USER_ERROR8 = 0x800000u,
			UNITYTLS_X509VERIFY_FLAG_UNKNOWN_ERROR = 0x8000000u
		}

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public unsafe delegate unitytls_x509verify_result unitytls_x509verify_callback(void* userData, unitytls_x509_ref cert, unitytls_x509verify_result result, unitytls_errorstate* errorState);

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct unitytls_tlsctx
		{
		}

		public struct unitytls_tlsctx_ref
		{
			public ulong handle;
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		public struct unitytls_x509name
		{
		}

		public enum unitytls_ciphersuite : uint
		{
			UNITYTLS_CIPHERSUITE_INVALID = 16777215u
		}

		public enum unitytls_protocol : uint
		{
			UNITYTLS_PROTOCOL_TLS_1_0,
			UNITYTLS_PROTOCOL_TLS_1_1,
			UNITYTLS_PROTOCOL_TLS_1_2,
			UNITYTLS_PROTOCOL_INVALID
		}

		public struct unitytls_tlsctx_protocolrange
		{
			public unitytls_protocol min;

			public unitytls_protocol max;
		}

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public unsafe delegate IntPtr unitytls_tlsctx_write_callback(void* userData, byte* data, IntPtr bufferLen, unitytls_errorstate* errorState);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public unsafe delegate IntPtr unitytls_tlsctx_read_callback(void* userData, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public unsafe delegate void unitytls_tlsctx_trace_callback(void* userData, unitytls_tlsctx* ctx, byte* traceMessage, IntPtr traceMessageLen);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public unsafe delegate void unitytls_tlsctx_certificate_callback(void* userData, unitytls_tlsctx* ctx, byte* cn, IntPtr cnLen, unitytls_x509name* caList, IntPtr caListLen, unitytls_x509list_ref* chain, unitytls_key_ref* key, unitytls_errorstate* errorState);

		[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
		public unsafe delegate unitytls_x509verify_result unitytls_tlsctx_x509verify_callback(void* userData, unitytls_x509list_ref chain, unitytls_errorstate* errorState);

		public struct unitytls_tlsctx_callbacks
		{
			public unitytls_tlsctx_read_callback read;

			public unitytls_tlsctx_write_callback write;

			public unsafe void* data;
		}

		[StructLayout(LayoutKind.Sequential)]
		public class unitytls_interface_struct
		{
			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public delegate unitytls_errorstate unitytls_errorstate_create_t();

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_errorstate_raise_error_t(unitytls_errorstate* errorState, unitytls_error_code errorCode);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_key_ref unitytls_key_get_ref_t(unitytls_key* key, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_key* unitytls_key_parse_der_t(byte* buffer, IntPtr bufferLen, byte* password, IntPtr passwordLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_key* unitytls_key_parse_pem_t(byte* buffer, IntPtr bufferLen, byte* password, IntPtr passwordLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_key_free_t(unitytls_key* key);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate IntPtr unitytls_x509_export_der_t(unitytls_x509_ref cert, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_x509list_ref unitytls_x509list_get_ref_t(unitytls_x509list* list, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_x509_ref unitytls_x509list_get_x509_t(unitytls_x509list_ref list, IntPtr index, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_x509list* unitytls_x509list_create_t(unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_x509list_append_t(unitytls_x509list* list, unitytls_x509_ref cert, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_x509list_append_der_t(unitytls_x509list* list, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_x509list_append_pem_t(unitytls_x509list* list, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_x509list_free_t(unitytls_x509list* list);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_x509verify_result unitytls_x509verify_default_ca_t(unitytls_x509list_ref chain, byte* cn, IntPtr cnLen, unitytls_x509verify_callback cb, void* userData, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_x509verify_result unitytls_x509verify_explicit_ca_t(unitytls_x509list_ref chain, unitytls_x509list_ref trustCA, byte* cn, IntPtr cnLen, unitytls_x509verify_callback cb, void* userData, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_tlsctx* unitytls_tlsctx_create_server_t(unitytls_tlsctx_protocolrange supportedProtocols, unitytls_tlsctx_callbacks callbacks, ulong certChain, ulong leafCertificateKey, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_tlsctx* unitytls_tlsctx_create_client_t(unitytls_tlsctx_protocolrange supportedProtocols, unitytls_tlsctx_callbacks callbacks, byte* cn, IntPtr cnLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_tlsctx_server_require_client_authentication_t(unitytls_tlsctx* ctx, unitytls_x509list_ref clientAuthCAList, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_tlsctx_set_certificate_callback_t(unitytls_tlsctx* ctx, unitytls_tlsctx_certificate_callback cb, void* userData, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_tlsctx_set_trace_callback_t(unitytls_tlsctx* ctx, unitytls_tlsctx_trace_callback cb, void* userData, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_tlsctx_set_x509verify_callback_t(unitytls_tlsctx* ctx, unitytls_tlsctx_x509verify_callback cb, void* userData, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_tlsctx_set_supported_ciphersuites_t(unitytls_tlsctx* ctx, unitytls_ciphersuite* supportedCiphersuites, IntPtr supportedCiphersuitesLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_ciphersuite unitytls_tlsctx_get_ciphersuite_t(unitytls_tlsctx* ctx, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_protocol unitytls_tlsctx_get_protocol_t(unitytls_tlsctx* ctx, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate unitytls_x509verify_result unitytls_tlsctx_process_handshake_t(unitytls_tlsctx* ctx, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate IntPtr unitytls_tlsctx_read_t(unitytls_tlsctx* ctx, byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate IntPtr unitytls_tlsctx_write_t(unitytls_tlsctx* ctx, byte* data, IntPtr bufferLen, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_tlsctx_notify_close_t(unitytls_tlsctx* ctx, unitytls_errorstate* errorState);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_tlsctx_free_t(unitytls_tlsctx* ctx);

			[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
			public unsafe delegate void unitytls_random_generate_bytes_t(byte* buffer, IntPtr bufferLen, unitytls_errorstate* errorState);

			public readonly ulong UNITYTLS_INVALID_HANDLE;

			public readonly unitytls_tlsctx_protocolrange UNITYTLS_TLSCTX_PROTOCOLRANGE_DEFAULT;

			public unitytls_errorstate_create_t unitytls_errorstate_create;

			public unitytls_errorstate_raise_error_t unitytls_errorstate_raise_error;

			public unitytls_key_get_ref_t unitytls_key_get_ref;

			public unitytls_key_parse_der_t unitytls_key_parse_der;

			public unitytls_key_parse_pem_t unitytls_key_parse_pem;

			public unitytls_key_free_t unitytls_key_free;

			public unitytls_x509_export_der_t unitytls_x509_export_der;

			public unitytls_x509list_get_ref_t unitytls_x509list_get_ref;

			public unitytls_x509list_get_x509_t unitytls_x509list_get_x509;

			public unitytls_x509list_create_t unitytls_x509list_create;

			public unitytls_x509list_append_t unitytls_x509list_append;

			public unitytls_x509list_append_der_t unitytls_x509list_append_der;

			public unitytls_x509list_append_der_t unitytls_x509list_append_pem;

			public unitytls_x509list_free_t unitytls_x509list_free;

			public unitytls_x509verify_default_ca_t unitytls_x509verify_default_ca;

			public unitytls_x509verify_explicit_ca_t unitytls_x509verify_explicit_ca;

			public unitytls_tlsctx_create_server_t unitytls_tlsctx_create_server;

			public unitytls_tlsctx_create_client_t unitytls_tlsctx_create_client;

			public unitytls_tlsctx_server_require_client_authentication_t unitytls_tlsctx_server_require_client_authentication;

			public unitytls_tlsctx_set_certificate_callback_t unitytls_tlsctx_set_certificate_callback;

			public unitytls_tlsctx_set_trace_callback_t unitytls_tlsctx_set_trace_callback;

			public unitytls_tlsctx_set_x509verify_callback_t unitytls_tlsctx_set_x509verify_callback;

			public unitytls_tlsctx_set_supported_ciphersuites_t unitytls_tlsctx_set_supported_ciphersuites;

			public unitytls_tlsctx_get_ciphersuite_t unitytls_tlsctx_get_ciphersuite;

			public unitytls_tlsctx_get_protocol_t unitytls_tlsctx_get_protocol;

			public unitytls_tlsctx_process_handshake_t unitytls_tlsctx_process_handshake;

			public unitytls_tlsctx_read_t unitytls_tlsctx_read;

			public unitytls_tlsctx_write_t unitytls_tlsctx_write;

			public unitytls_tlsctx_notify_close_t unitytls_tlsctx_notify_close;

			public unitytls_tlsctx_free_t unitytls_tlsctx_free;

			public unitytls_random_generate_bytes_t unitytls_random_generate_bytes;
		}

		private static unitytls_interface_struct marshalledInterface;

		public static bool IsSupported => NativeInterface != null;

		public static unitytls_interface_struct NativeInterface
		{
			get
			{
				if (marshalledInterface == null)
				{
					IntPtr unityTlsInterface = GetUnityTlsInterface();
					if (unityTlsInterface == IntPtr.Zero)
					{
						return null;
					}
					marshalledInterface = Marshal.PtrToStructure<unitytls_interface_struct>(unityTlsInterface);
				}
				return marshalledInterface;
			}
		}

		[MethodImpl(MethodImplOptions.InternalCall)]
		private static extern IntPtr GetUnityTlsInterface();
	}
	internal class UnityTlsContext : MobileTlsContext
	{
		private const bool ActivateTracing = false;

		private unsafe UnityTls.unitytls_tlsctx* tlsContext = null;

		private unsafe UnityTls.unitytls_x509list* requestedClientCertChain = null;

		private unsafe UnityTls.unitytls_key* requestedClientKey = null;

		private UnityTls.unitytls_tlsctx_read_callback readCallback;

		private UnityTls.unitytls_tlsctx_write_callback writeCallback;

		private UnityTls.unitytls_tlsctx_trace_callback traceCallback;

		private UnityTls.unitytls_tlsctx_certificate_callback certificateCallback;

		private UnityTls.unitytls_tlsctx_x509verify_callback verifyCallback;

		private X509Certificate localClientCertificate;

		private X509Certificate2 remoteCertificate;

		private MonoTlsConnectionInfo connectioninfo;

		private bool isAuthenticated;

		private bool hasContext;

		private bool closedGraceful;

		private byte[] writeBuffer;

		private byte[] readBuffer;

		private GCHandle handle;

		private Exception lastException;

		public override bool HasContext => hasContext;

		public override bool IsAuthenticated => isAuthenticated;

		public override MonoTlsConnectionInfo ConnectionInfo => connectioninfo;

		internal override bool IsRemoteCertificateAvailable => remoteCertificate != null;

		internal override X509Certificate LocalClientCertificate => localClientCertificate;

		public override X509Certificate2 RemoteCertificate => remoteCertificate;

		public override TlsProtocols NegotiatedProtocol => ConnectionInfo.ProtocolVersion;

		public override bool CanRenegotiate => false;

		public unsafe UnityTlsContext(MobileAuthenticatedStream parent, MonoSslAuthenticationOptions options)
			: base(parent, options)
		{
			handle = GCHandle.Alloc(this);
			UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create();
			UnityTls.unitytls_tlsctx_protocolrange supportedProtocols = new UnityTls.unitytls_tlsctx_protocolrange
			{
				min = UnityTlsConversions.GetMinProtocol(options.EnabledSslProtocols),
				max = UnityTlsConversions.GetMaxProtocol(options.EnabledSslProtocols)
			};
			readCallback = ReadCallback;
			writeCallback = WriteCallback;
			UnityTls.unitytls_tlsctx_callbacks callbacks = new UnityTls.unitytls_tlsctx_callbacks
			{
				write = writeCallback,
				read = readCallback,
				data = (void*)(IntPtr)handle
			};
			if (options.ServerMode)
			{
				ExtractNativeKeyAndChainFromManagedCertificate(options.ServerCertificate, &errorState, out var nativeCertChain, out var nativeKey);
				try
				{
					UnityTls.unitytls_x509list_ref unitytls_x509list_ref = UnityTls.NativeInterface.unitytls_x509list_get_ref(nativeCertChain, &errorState);
					UnityTls.unitytls_key_ref unitytls_key_ref = UnityTls.NativeInterface.unitytls_key_get_ref(nativeKey, &errorState);
					Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to parse server key/certificate", (AlertDescription)80);
					tlsContext = UnityTls.NativeInterface.unitytls_tlsctx_create_server(supportedProtocols, callbacks, unitytls_x509list_ref.handle, unitytls_key_ref.handle, &errorState);
					if (base.AskForClientCertificate)
					{
						UnityTls.unitytls_x509list* list = null;
						try
						{
							list = UnityTls.NativeInterface.unitytls_x509list_create(&errorState);
							UnityTls.unitytls_x509list_ref clientAuthCAList = UnityTls.NativeInterface.unitytls_x509list_get_ref(list, &errorState);
							UnityTls.NativeInterface.unitytls_tlsctx_server_require_client_authentication(tlsContext, clientAuthCAList, &errorState);
						}
						finally
						{
							UnityTls.NativeInterface.unitytls_x509list_free(list);
						}
					}
				}
				finally
				{
					UnityTls.NativeInterface.unitytls_x509list_free(nativeCertChain);
					UnityTls.NativeInterface.unitytls_key_free(nativeKey);
				}
			}
			else
			{
				byte[] bytes = Encoding.UTF8.GetBytes(options.TargetHost);
				fixed (byte* cn = bytes)
				{
					tlsContext = UnityTls.NativeInterface.unitytls_tlsctx_create_client(supportedProtocols, callbacks, cn, (IntPtr)bytes.Length, &errorState);
				}
				certificateCallback = CertificateCallback;
				UnityTls.NativeInterface.unitytls_tlsctx_set_certificate_callback(tlsContext, certificateCallback, (void*)(IntPtr)handle, &errorState);
			}
			verifyCallback = VerifyCallback;
			UnityTls.NativeInterface.unitytls_tlsctx_set_x509verify_callback(tlsContext, verifyCallback, (void*)(IntPtr)handle, &errorState);
			Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to create UnityTls context", (AlertDescription)80);
			hasContext = true;
		}

		private unsafe static void ExtractNativeKeyAndChainFromManagedCertificate(X509Certificate cert, UnityTls.unitytls_errorstate* errorState, out UnityTls.unitytls_x509list* nativeCertChain, out UnityTls.unitytls_key* nativeKey)
		{
			if (cert == null)
			{
				throw new ArgumentNullException("cert");
			}
			if (!(cert is X509Certificate2 x509Certificate) || x509Certificate.PrivateKey == null)
			{
				throw new ArgumentException("Certificate does not have a private key", "cert");
			}
			nativeCertChain = null;
			nativeKey = null;
			try
			{
				nativeCertChain = UnityTls.NativeInterface.unitytls_x509list_create(errorState);
				CertHelper.AddCertificateToNativeChain(nativeCertChain, cert, errorState);
				byte[] array = PrivateKeyInfo.Encode(x509Certificate.PrivateKey);
				fixed (byte* buffer = array)
				{
					nativeKey = UnityTls.NativeInterface.unitytls_key_parse_der(buffer, (IntPtr)array.Length, null, (IntPtr)0, errorState);
				}
			}
			catch
			{
				UnityTls.NativeInterface.unitytls_x509list_free(nativeCertChain);
				UnityTls.NativeInterface.unitytls_key_free(nativeKey);
				throw;
			}
		}

		public override void Flush()
		{
		}

		public unsafe override (int ret, bool wantMore) Read(byte[] buffer, int offset, int count)
		{
			int num = 0;
			lastException = null;
			UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create();
			fixed (byte* ptr = buffer)
			{
				num = (int)UnityTls.NativeInterface.unitytls_tlsctx_read(tlsContext, ptr + offset, (IntPtr)count, &errorState);
			}
			if (lastException != null)
			{
				throw lastException;
			}
			switch (errorState.code)
			{
			case UnityTls.unitytls_error_code.UNITYTLS_SUCCESS:
				return (num, num < count);
			case UnityTls.unitytls_error_code.UNITYTLS_USER_WOULD_BLOCK:
				return (num, true);
			case UnityTls.unitytls_error_code.UNITYTLS_STREAM_CLOSED:
				return (0, false);
			default:
				if (!closedGraceful)
				{
					Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to read data to TLS context", (AlertDescription)80);
				}
				return (0, false);
			}
		}

		public unsafe override (int ret, bool wantMore) Write(byte[] buffer, int offset, int count)
		{
			int num = 0;
			lastException = null;
			UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create();
			fixed (byte* ptr = buffer)
			{
				num = (int)UnityTls.NativeInterface.unitytls_tlsctx_write(tlsContext, ptr + offset, (IntPtr)count, &errorState);
			}
			if (lastException != null)
			{
				throw lastException;
			}
			switch (errorState.code)
			{
			case UnityTls.unitytls_error_code.UNITYTLS_SUCCESS:
				return (num, num < count);
			case UnityTls.unitytls_error_code.UNITYTLS_USER_WOULD_BLOCK:
				return (num, true);
			case UnityTls.unitytls_error_code.UNITYTLS_STREAM_CLOSED:
				return (0, false);
			default:
				Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to write data to TLS context", (AlertDescription)80);
				return (0, false);
			}
		}

		public override void Renegotiate()
		{
			throw new NotSupportedException();
		}

		public override bool PendingRenegotiation()
		{
			return false;
		}

		public unsafe override void Shutdown()
		{
			if (base.Settings != null && base.Settings.SendCloseNotify)
			{
				UnityTls.unitytls_errorstate unitytls_errorstate = UnityTls.NativeInterface.unitytls_errorstate_create();
				UnityTls.NativeInterface.unitytls_tlsctx_notify_close(tlsContext, &unitytls_errorstate);
			}
			UnityTls.NativeInterface.unitytls_x509list_free(requestedClientCertChain);
			UnityTls.NativeInterface.unitytls_key_free(requestedClientKey);
			UnityTls.NativeInterface.unitytls_tlsctx_free(tlsContext);
			tlsContext = null;
			hasContext = false;
		}

		protected override void Dispose(bool disposing)
		{
			try
			{
				if (disposing)
				{
					Shutdown();
					localClientCertificate = null;
					remoteCertificate = null;
					if (localClientCertificate != null)
					{
						localClientCertificate.Dispose();
						localClientCertificate = null;
					}
					if (remoteCertificate != null)
					{
						remoteCertificate.Dispose();
						remoteCertificate = null;
					}
					connectioninfo = null;
					isAuthenticated = false;
					hasContext = false;
				}
				handle.Free();
			}
			finally
			{
				base.Dispose(disposing);
			}
		}

		public unsafe override void StartHandshake()
		{
			if (base.Settings != null && base.Settings.EnabledCiphers != null)
			{
				UnityTls.unitytls_ciphersuite[] array = new UnityTls.unitytls_ciphersuite[base.Settings.EnabledCiphers.Length];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = (UnityTls.unitytls_ciphersuite)base.Settings.EnabledCiphers[i];
				}
				UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create();
				fixed (UnityTls.unitytls_ciphersuite* supportedCiphersuites = array)
				{
					UnityTls.NativeInterface.unitytls_tlsctx_set_supported_ciphersuites(tlsContext, supportedCiphersuites, (IntPtr)array.Length, &errorState);
				}
				Mono.Unity.Debug.CheckAndThrow(errorState, "Failed to set list of supported ciphers", (AlertDescription)40);
			}
		}

		public unsafe override bool ProcessHandshake()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			lastException = null;
			UnityTls.unitytls_errorstate errorState = UnityTls.NativeInterface.unitytls_errorstate_create();
			UnityTls.unitytls_x509verify_result unitytls_x509verify_result = UnityTls.NativeInterface.unitytls_tlsctx_process_handshake(tlsContext, &errorState);
			if (errorState.code == UnityTls.unitytls_error_code.UNITYTLS_USER_WOULD_BLOCK)
			{
				return false;
			}
			if (lastException != null)
			{
				throw lastException;
			}
			if (base.IsServer && unitytls_x509verify_result == UnityTls.unitytls_x509verify_result.UNITYTLS_X509VERIFY_NOT_DONE)
			{
				Mono.Unity.Debug.CheckAndThrow(errorState, "Handshake failed", (AlertDescription)40);
				if (!ValidateCertificate(null, null))
				{
					throw new TlsException((AlertDescription)40, "Verification failure during handshake");
				}
			}
			else
			{
				Mono.Unity.Debug.CheckAndThrow(errorState, unitytls_x509verify_result, "Handshake failed", (AlertDescription)40);
			}
			return true;
		}

		public unsafe override void FinishHandshake()
		{
			//IL_0043: 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_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Expected O, but got Unknown
			UnityTls.unitytls_errorstate unitytls_errorstate = UnityTls.NativeInterface.unitytls_errorstate_create();
			UnityTls.unitytls_ciphersuite unitytls_ciphersuite = UnityTls.NativeInterface.unitytls_tlsctx_get_ciphersuite(tlsContext, &unitytls_errorstate);
			UnityTls.unitytls_protocol protocol = UnityTls.NativeInterface.unitytls_tlsctx_get_protocol(tlsContext, &unitytls_errorstate);
			connectioninfo = new MonoTlsConnectionInfo
			{
				CipherSuiteCode = (CipherSuiteCode)(ushort)unitytls_ciphersuite,
				ProtocolVersion = UnityTlsConversions.ConvertProtocolVersion(protocol),
				PeerDomainName = base.ServerName
			};
			isAuthenticated = true;
		}

		[MonoPInvokeCallback(typeof(UnityTls.unitytls_tlsctx_write_callback))]
		private unsafe static IntPtr WriteCallback(void* userData, byte* data, IntPtr bufferLen, UnityTls.unitytls_errorstate* errorState)
		{
			return ((UnityTlsContext)((GCHandle)(IntPtr)userData).Target).WriteCallback(data, bufferLen, errorState);
		}

		private unsafe IntPtr WriteCallback(byte* data, IntPtr bufferLen, UnityTls.unitytls_errorstate* errorState)
		{
			try
			{
				if (writeBuffer == null || writeBuffer.Length < (int)bufferLen)
				{
					writeBuffer = new byte[(int)bufferLen];
				}
				Marshal.Copy((IntPtr)data, writeBuffer, 0, (int)bufferLen);
				if (!base.Parent.InternalWrite(writeBuffer, 0, (int)bufferLen))
				{
					UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_WRITE_FAILED);
					return (IntPtr)0;
				}
				return bufferLen;
			}
			catch (Exception ex)
			{
				UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_UNKNOWN_ERROR);
				if (lastException == null)
				{
					lastException = ex;
				}
				return (IntPtr)0;
			}
		}

		[MonoPInvokeCallback(typeof(UnityTls.unitytls_tlsctx_read_callback))]
		private unsafe static IntPtr ReadCallback(void* userData, byte* buffer, IntPtr bufferLen, UnityTls.unitytls_errorstate* errorState)
		{
			return ((UnityTlsContext)((GCHandle)(IntPtr)userData).Target).ReadCallback(buffer, bufferLen, errorState);
		}

		private unsafe IntPtr ReadCallback(byte* buffer, IntPtr bufferLen, UnityTls.unitytls_errorstate* errorState)
		{
			try
			{
				if (readBuffer == null || readBuffer.Length < (int)bufferLen)
				{
					readBuffer = new byte[(int)bufferLen];
				}
				bool outWantMore;
				int num = base.Parent.InternalRead(readBuffer, 0, (int)bufferLen, out outWantMore);
				if (num < 0)
				{
					UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_READ_FAILED);
				}
				else if (num > 0)
				{
					Marshal.Copy(readBuffer, 0, (IntPtr)buffer, (int)bufferLen);
				}
				else if (outWantMore)
				{
					UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_WOULD_BLOCK);
				}
				else
				{
					closedGraceful = true;
					UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_READ_FAILED);
				}
				return (IntPtr)num;
			}
			catch (Exception ex)
			{
				UnityTls.NativeInterface.unitytls_errorstate_raise_error(errorState, UnityTls.unitytls_error_code.UNITYTLS_USER_

BepInEx/core/System.Drawing.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
using System.Internal;
using System.Numerics.Hashing;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using Unity;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Drawing.dll")]
[assembly: AssemblyDescription("System.Drawing.dll")]
[assembly: AssemblyDefaultAlias("System.Drawing.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: Dependency("System,", LoadHint.Always)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal sealed class Locale
{
	private Locale()
	{
	}

	public static string GetText(string msg)
	{
		return msg;
	}

	public static string GetText(string fmt, params object[] args)
	{
		return string.Format(fmt, args);
	}
}
internal class SR
{
	public const string CantTellPrinterName = "(printer name protected due to security restrictions)";

	public const string CantChangeImmutableObjects = "Changes cannot be made to {0} because permissions are not valid.";

	public const string CantMakeIconTransparent = "Bitmaps that are icons cannot be made transparent. Icons natively support transparency. Use the Icon constructor to create an icon.";

	public const string ColorNotSystemColor = "The color {0} is not a system color.";

	public const string DotNET_ComponentType = ".NET Component";

	public const string GdiplusAborted = "Function was ended.";

	public const string GdiplusAccessDenied = "File access is denied.";

	public const string GdiplusCannotCreateGraphicsFromIndexedPixelFormat = "A Graphics object cannot be created from an image that has an indexed pixel format.";

	public const string GdiplusCannotSetPixelFromIndexedPixelFormat = "SetPixel is not supported for images with indexed pixel formats.";

	public const string GdiplusDestPointsInvalidParallelogram = "Destination points define a parallelogram which must have a length of 3. These points will represent the upper-left, upper-right, and lower-left coordinates (defined in that order).";

	public const string GdiplusDestPointsInvalidLength = "Destination points must be an array with a length of 3 or 4. A length of 3 defines a parallelogram with the upper-left, upper-right, and lower-left corners. A length of 4 defines a quadrilateral with the fourth element of the array specifying the lower-right coordinate.";

	public const string GdiplusFileNotFound = "File not found.";

	public const string GdiplusFontFamilyNotFound = "Font '{0}' cannot be found.";

	public const string GdiplusFontStyleNotFound = "Font '{0}' does not support style '{1}'.";

	public const string GdiplusGenericError = "A generic error occurred in GDI+.";

	public const string GdiplusInsufficientBuffer = "Buffer is too small (internal GDI+ error).";

	public const string GdiplusInvalidParameter = "Parameter is not valid.";

	public const string GdiplusInvalidRectangle = "Rectangle '{0}' cannot have a width or height equal to 0.";

	public const string GdiplusInvalidSize = "Operation requires a transformation of the image from GDI+ to GDI. GDI does not support images with a width or height greater than 32767.";

	public const string GdiplusOutOfMemory = "Out of memory.";

	public const string GdiplusNotImplemented = "Not implemented.";

	public const string GdiplusNotInitialized = "GDI+ is not properly initialized (internal GDI+ error).";

	public const string GdiplusNotTrueTypeFont = "Only TrueType fonts are supported. '{0}' is not a TrueType font.";

	public const string GdiplusNotTrueTypeFont_NoName = "Only TrueType fonts are supported. This is not a TrueType font.";

	public const string GdiplusObjectBusy = "Object is currently in use elsewhere.";

	public const string GdiplusOverflow = "Overflow error.";

	public const string GdiplusPropertyNotFoundError = "Property cannot be found.";

	public const string GdiplusPropertyNotSupportedError = "Property is not supported.";

	public const string GdiplusUnknown = "Unknown GDI+ error occurred.";

	public const string GdiplusUnknownImageFormat = "Image format is unknown.";

	public const string GdiplusUnsupportedGdiplusVersion = "Current version of GDI+ does not support this feature.";

	public const string GdiplusWrongState = "Bitmap region is already locked.";

	public const string GlobalAssemblyCache = " (Global Assembly Cache)";

	public const string GraphicsBufferCurrentlyBusy = "BufferedGraphicsContext cannot be disposed of because a buffer operation is currently in progress.";

	public const string GraphicsBufferQueryFail = "Screen-compatible bitmap cannot be created. The screen bitmap format cannot be determined.";

	public const string ToolboxItemLocked = "Toolbox item cannot be modified.";

	public const string ToolboxItemInvalidPropertyType = "Property {0} requires an argument of type {1}.";

	public const string ToolboxItemValueNotSerializable = "Data type {0} is not serializable. Items added to a property dictionary must be serializable.";

	public const string ToolboxItemInvalidKey = "Argument should be a non-empty string.";

	public const string IllegalState = "Internal state of the {0} class is invalid.";

	public const string InterpolationColorsColorBlendNotSet = "Property must be set to a valid ColorBlend object to use interpolation colors.";

	public const string InterpolationColorsCommon = "{0}{1} ColorBlend objects must be constructed with the same number of positions and color values. Positions must be between 0.0 and 1.0, 1.0 indicating the last element in the array.";

	public const string InterpolationColorsInvalidColorBlendObject = "ColorBlend object that was set is not valid.";

	public const string InterpolationColorsInvalidStartPosition = "Position's first element must be equal to 0.";

	public const string InterpolationColorsInvalidEndPosition = "Position's last element must be equal to 1.0.";

	public const string InterpolationColorsLength = "Array of colors and positions must contain at least two elements.";

	public const string InterpolationColorsLengthsDiffer = "Colors and positions do not have the same number of elements.";

	public const string InvalidArgument = "Value of '{1}' is not valid for '{0}'.";

	public const string InvalidBoundArgument = "Value of '{1}' is not valid for '{0}'. '{0}' should be greater than {2} and less than or equal to {3}.";

	public const string InvalidClassName = "Class name is not valid.";

	public const string InvalidColor = "Color '{0}' is not valid.";

	public const string InvalidDashPattern = "DashPattern value is not valid.";

	public const string InvalidEx2BoundArgument = "Value of '{1}' is not valid for '{0}'. '{0}' should be greater than or equal to {2} and less than or equal to {3}.";

	public const string InvalidFrame = "Frame is not valid. Frame must be between 0 and FrameCount.";

	public const string InvalidGDIHandle = "Win32 handle that was passed to {0} is not valid or is the wrong type.";

	public const string InvalidImage = "Image type is unknown.";

	public const string InvalidLowBoundArgumentEx = "Value of '{1}' is not valid for '{0}'. '{0}' must be greater than or equal to {2}.";

	public const string InvalidPermissionLevel = "Permission level is not valid.";

	public const string InvalidPermissionState = "Permission state is not valid.";

	public const string InvalidPictureType = "Argument '{0}' must be a picture that can be used as a {1}.";

	public const string InvalidPrinterException_InvalidPrinter = "Settings to access printer '{0}' are not valid.";

	public const string InvalidPrinterException_NoDefaultPrinter = "No printers are installed.";

	public const string InvalidPrinterHandle = "Handle {0} is not valid.";

	public const string ValidRangeX = "Parameter must be positive and < Width.";

	public const string ValidRangeY = "Parameter must be positive and < Height.";

	public const string NativeHandle0 = "Native handle is 0.";

	public const string NoDefaultPrinter = "Default printer is not set.";

	public const string NotImplemented = "Not implemented.";

	public const string PDOCbeginPrintDescr = "Occurs when the document is about to be printed.";

	public const string PDOCdocumentNameDescr = "The name of the document shown to the user.";

	public const string PDOCdocumentPageSettingsDescr = "The page settings of the page currently being printed.";

	public const string PDOCendPrintDescr = "Occurs after the document has been printed.";

	public const string PDOCoriginAtMarginsDescr = "Indicates that the graphics origin is located at the user-specified page margins.";

	public const string PDOCprintControllerDescr = "Retrieves the print controller for this document.";

	public const string PDOCprintPageDescr = "Occurs once for each page to be printed.";

	public const string PDOCprinterSettingsDescr = "Retrieves the settings for the printer the document is currently being printed to.";

	public const string PDOCqueryPageSettingsDescr = "Occurs before each page is printed.  Useful for changing PageSettings for a particular page.";

	public const string PrintDocumentDesc = "Defines an object that sends output to a printer.";

	public const string PrintingPermissionBadXml = "XML is not valid.";

	public const string PrintingPermissionAttributeInvalidPermissionLevel = "Permission level must be between PrintingPermissionLevel.NoPrinting and PrintingPermissionLevel.AllPrinting.";

	public const string PropertyValueInvalidEntry = "IDictionary parameter contains at least one entry that is not valid. Ensure all values are consistent with the object's properties.";

	public const string PSizeNotCustom = "PaperSize cannot be changed unless the Kind property is set to Custom.";

	public const string ResourceNotFound = "Resource '{1}' cannot be found in class '{0}'.";

	public const string TargetNotPrintingPermission = "Target does not have permission to print.";

	public const string TextParseFailedFormat = "Text \"{0}\" cannot be parsed. The expected text format is \"{1}\".";

	public const string TriStateCompareError = "TriState.Default cannot be converted into a Boolean.";

	public const string toStringIcon = "(Icon)";

	public const string toStringNone = "(none)";

	public const string DCTypeInvalid = "GetObjectType on this dc returned an invalid value.";

	public const string InvalidEnumArgument = "The value of argument '{0}' ({1}) is invalid for Enum type '{2}'.";

	public const string ConvertInvalidPrimitive = "{0} is not a valid value for {1}.";

	public const string LibgdiplusNotFound = "The native library \"libgdiplus\" is not installed on the system, or was otherwise unable to be loaded.";

	public static string Format(string format, params object[] args)
	{
		return string.Format(format, args);
	}
}
namespace System
{
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoTODOAttribute : Attribute
	{
		private string comment;

		public string Comment => comment;

		public MonoTODOAttribute()
		{
		}

		public MonoTODOAttribute(string comment)
		{
			this.comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoDocumentationNoteAttribute : MonoTODOAttribute
	{
		public MonoDocumentationNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoExtensionAttribute : MonoTODOAttribute
	{
		public MonoExtensionAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoInternalNoteAttribute : MonoTODOAttribute
	{
		public MonoInternalNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoLimitationAttribute : MonoTODOAttribute
	{
		public MonoLimitationAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoNotSupportedAttribute : MonoTODOAttribute
	{
		public MonoNotSupportedAttribute(string comment)
			: base(comment)
		{
		}
	}
}
namespace System.Internal
{
	internal sealed class HandleCollector
	{
		private class HandleType
		{
			internal readonly string name;

			private int _initialThreshHold;

			private int _threshHold;

			private int _handleCount;

			private readonly int _deltaPercent;

			internal HandleType(string name, int expense, int initialThreshHold)
			{
				this.name = name;
				_initialThreshHold = initialThreshHold;
				_threshHold = initialThreshHold;
				_deltaPercent = 100 - expense;
			}

			internal void Add(IntPtr handle)
			{
				if (!(handle == IntPtr.Zero))
				{
					bool flag = false;
					int currentHandleCount = 0;
					lock (this)
					{
						_handleCount++;
						flag = NeedCollection();
						currentHandleCount = _handleCount;
					}
					lock (s_internalSyncObject)
					{
						HandleCollector.HandleAdded?.Invoke(name, handle, currentHandleCount);
					}
					if (flag && flag)
					{
						GC.Collect();
						Thread.Sleep((100 - _deltaPercent) / 4);
					}
				}
			}

			internal bool NeedCollection()
			{
				if (_handleCount > _threshHold)
				{
					_threshHold = _handleCount + _handleCount * _deltaPercent / 100;
					return true;
				}
				int num = 100 * _threshHold / (100 + _deltaPercent);
				if (num >= _initialThreshHold && _handleCount < (int)((float)num * 0.9f))
				{
					_threshHold = num;
				}
				return false;
			}

			internal IntPtr Remove(IntPtr handle)
			{
				if (handle == IntPtr.Zero)
				{
					return handle;
				}
				int currentHandleCount = 0;
				lock (this)
				{
					_handleCount--;
					if (_handleCount < 0)
					{
						_handleCount = 0;
					}
					currentHandleCount = _handleCount;
				}
				lock (s_internalSyncObject)
				{
					HandleCollector.HandleRemoved?.Invoke(name, handle, currentHandleCount);
				}
				return handle;
			}
		}

		private static HandleType[] s_handleTypes;

		private static int s_handleTypeCount;

		private static object s_internalSyncObject = new object();

		internal static event HandleChangeEventHandler HandleAdded;

		internal static event HandleChangeEventHandler HandleRemoved;

		internal static IntPtr Add(IntPtr handle, int type)
		{
			s_handleTypes[type - 1].Add(handle);
			return handle;
		}

		internal static int RegisterType(string typeName, int expense, int initialThreshold)
		{
			lock (s_internalSyncObject)
			{
				if (s_handleTypeCount == 0 || s_handleTypeCount == s_handleTypes.Length)
				{
					HandleType[] destinationArray = new HandleType[s_handleTypeCount + 10];
					if (s_handleTypes != null)
					{
						Array.Copy(s_handleTypes, 0, destinationArray, 0, s_handleTypeCount);
					}
					s_handleTypes = destinationArray;
				}
				s_handleTypes[s_handleTypeCount++] = new HandleType(typeName, expense, initialThreshold);
				return s_handleTypeCount;
			}
		}

		internal static IntPtr Remove(IntPtr handle, int type)
		{
			return s_handleTypes[type - 1].Remove(handle);
		}
	}
	internal delegate void HandleChangeEventHandler(string handleType, IntPtr handleValue, int currentHandleCount);
}
namespace System.Numerics.Hashing
{
	internal static class HashHelpers
	{
		public static readonly int RandomSeed = Guid.NewGuid().GetHashCode();

		public static int Combine(int h1, int h2)
		{
			return (((h1 << 5) | (h1 >>> 27)) + h1) ^ h2;
		}
	}
}
namespace System.Drawing
{
	internal static class ColorTable
	{
		private static readonly Lazy<Dictionary<string, Color>> s_colorConstants = new Lazy<Dictionary<string, Color>>(GetColors);

		internal static Dictionary<string, Color> Colors => s_colorConstants.Value;

		private static Dictionary<string, Color> GetColors()
		{
			Dictionary<string, Color> dictionary = new Dictionary<string, Color>(StringComparer.OrdinalIgnoreCase);
			FillConstants(dictionary, typeof(Color));
			FillConstants(dictionary, typeof(SystemColors));
			return dictionary;
		}

		private static void FillConstants(Dictionary<string, Color> colors, Type enumType)
		{
			PropertyInfo[] properties = enumType.GetProperties();
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (propertyInfo.PropertyType == typeof(Color))
				{
					colors[propertyInfo.Name] = (Color)propertyInfo.GetValue(null, null);
				}
			}
		}

		internal static bool TryGetNamedColor(string name, out Color result)
		{
			return Colors.TryGetValue(name, out result);
		}

		internal static bool IsKnownNamedColor(string name)
		{
			Color value;
			return Colors.TryGetValue(name, out value);
		}
	}
	internal static class ColorUtil
	{
		public static Color FromKnownColor(KnownColor color)
		{
			return Color.FromKnownColor(color);
		}

		public static bool IsSystemColor(this Color color)
		{
			return color.IsSystemColor;
		}
	}
	public enum KnownColor
	{
		ActiveBorder = 1,
		ActiveCaption,
		ActiveCaptionText,
		AppWorkspace,
		Control,
		ControlDark,
		ControlDarkDark,
		ControlLight,
		ControlLightLight,
		ControlText,
		Desktop,
		GrayText,
		Highlight,
		HighlightText,
		HotTrack,
		InactiveBorder,
		InactiveCaption,
		InactiveCaptionText,
		Info,
		InfoText,
		Menu,
		MenuText,
		ScrollBar,
		Window,
		WindowFrame,
		WindowText,
		Transparent,
		AliceBlue,
		AntiqueWhite,
		Aqua,
		Aquamarine,
		Azure,
		Beige,
		Bisque,
		Black,
		BlanchedAlmond,
		Blue,
		BlueViolet,
		Brown,
		BurlyWood,
		CadetBlue,
		Chartreuse,
		Chocolate,
		Coral,
		CornflowerBlue,
		Cornsilk,
		Crimson,
		Cyan,
		DarkBlue,
		DarkCyan,
		DarkGoldenrod,
		DarkGray,
		DarkGreen,
		DarkKhaki,
		DarkMagenta,
		DarkOliveGreen,
		DarkOrange,
		DarkOrchid,
		DarkRed,
		DarkSalmon,
		DarkSeaGreen,
		DarkSlateBlue,
		DarkSlateGray,
		DarkTurquoise,
		DarkViolet,
		DeepPink,
		DeepSkyBlue,
		DimGray,
		DodgerBlue,
		Firebrick,
		FloralWhite,
		ForestGreen,
		Fuchsia,
		Gainsboro,
		GhostWhite,
		Gold,
		Goldenrod,
		Gray,
		Green,
		GreenYellow,
		Honeydew,
		HotPink,
		IndianRed,
		Indigo,
		Ivory,
		Khaki,
		Lavender,
		LavenderBlush,
		LawnGreen,
		LemonChiffon,
		LightBlue,
		LightCoral,
		LightCyan,
		LightGoldenrodYellow,
		LightGray,
		LightGreen,
		LightPink,
		LightSalmon,
		LightSeaGreen,
		LightSkyBlue,
		LightSlateGray,
		LightSteelBlue,
		LightYellow,
		Lime,
		LimeGreen,
		Linen,
		Magenta,
		Maroon,
		MediumAquamarine,
		MediumBlue,
		MediumOrchid,
		MediumPurple,
		MediumSeaGreen,
		MediumSlateBlue,
		MediumSpringGreen,
		MediumTurquoise,
		MediumVioletRed,
		MidnightBlue,
		MintCream,
		MistyRose,
		Moccasin,
		NavajoWhite,
		Navy,
		OldLace,
		Olive,
		OliveDrab,
		Orange,
		OrangeRed,
		Orchid,
		PaleGoldenrod,
		PaleGreen,
		PaleTurquoise,
		PaleVioletRed,
		PapayaWhip,
		PeachPuff,
		Peru,
		Pink,
		Plum,
		PowderBlue,
		Purple,
		Red,
		RosyBrown,
		RoyalBlue,
		SaddleBrown,
		Salmon,
		SandyBrown,
		SeaGreen,
		SeaShell,
		Sienna,
		Silver,
		SkyBlue,
		SlateBlue,
		SlateGray,
		Snow,
		SpringGreen,
		SteelBlue,
		Tan,
		Teal,
		Thistle,
		Tomato,
		Turquoise,
		Violet,
		Wheat,
		White,
		WhiteSmoke,
		Yellow,
		YellowGreen,
		ButtonFace,
		ButtonHighlight,
		ButtonShadow,
		GradientActiveCaption,
		GradientInactiveCaption,
		MenuBar,
		MenuHighlight
	}
	internal static class KnownColorTable
	{
		private static int[] s_colorTable;

		private static string[] s_colorNameTable;

		private const int AlphaShift = 24;

		private const int RedShift = 16;

		private const int GreenShift = 8;

		private const int BlueShift = 0;

		private const int Win32RedShift = 0;

		private const int Win32GreenShift = 8;

		private const int Win32BlueShift = 16;

		public static Color ArgbToKnownColor(int targetARGB)
		{
			EnsureColorTable();
			for (int i = 0; i < s_colorTable.Length; i++)
			{
				if (s_colorTable[i] == targetARGB)
				{
					Color color = ColorUtil.FromKnownColor((KnownColor)i);
					if (!color.IsSystemColor())
					{
						return color;
					}
				}
			}
			return Color.FromArgb(targetARGB);
		}

		private static void EnsureColorTable()
		{
			if (s_colorTable == null)
			{
				InitColorTable();
			}
		}

		private static void InitColorTable()
		{
			int[] array = new int[175];
			UpdateSystemColors(array);
			array[27] = 16777215;
			array[28] = -984833;
			array[29] = -332841;
			array[30] = -16711681;
			array[31] = -8388652;
			array[32] = -983041;
			array[33] = -657956;
			array[34] = -6972;
			array[35] = -16777216;
			array[36] = -5171;
			array[37] = -16776961;
			array[38] = -7722014;
			array[39] = -5952982;
			array[40] = -2180985;
			array[41] = -10510688;
			array[42] = -8388864;
			array[43] = -2987746;
			array[44] = -32944;
			array[45] = -10185235;
			array[46] = -1828;
			array[47] = -2354116;
			array[48] = -16711681;
			array[49] = -16777077;
			array[50] = -16741493;
			array[51] = -4684277;
			array[52] = -5658199;
			array[53] = -16751616;
			array[54] = -4343957;
			array[55] = -7667573;
			array[56] = -11179217;
			array[57] = -29696;
			array[58] = -6737204;
			array[59] = -7667712;
			array[60] = -1468806;
			array[61] = -7357301;
			array[62] = -12042869;
			array[63] = -13676721;
			array[64] = -16724271;
			array[65] = -7077677;
			array[66] = -60269;
			array[67] = -16728065;
			array[68] = -9868951;
			array[69] = -14774017;
			array[70] = -5103070;
			array[71] = -1296;
			array[72] = -14513374;
			array[73] = -65281;
			array[74] = -2302756;
			array[75] = -460545;
			array[76] = -10496;
			array[77] = -2448096;
			array[78] = -8355712;
			array[79] = -16744448;
			array[80] = -5374161;
			array[81] = -983056;
			array[82] = -38476;
			array[83] = -3318692;
			array[84] = -11861886;
			array[85] = -16;
			array[86] = -989556;
			array[87] = -1644806;
			array[88] = -3851;
			array[89] = -8586240;
			array[90] = -1331;
			array[91] = -5383962;
			array[92] = -1015680;
			array[93] = -2031617;
			array[94] = -329006;
			array[95] = -2894893;
			array[96] = -7278960;
			array[97] = -18751;
			array[98] = -24454;
			array[99] = -14634326;
			array[100] = -7876870;
			array[101] = -8943463;
			array[102] = -5192482;
			array[103] = -32;
			array[104] = -16711936;
			array[105] = -13447886;
			array[106] = -331546;
			array[107] = -65281;
			array[108] = -8388608;
			array[109] = -10039894;
			array[110] = -16777011;
			array[111] = -4565549;
			array[112] = -7114533;
			array[113] = -12799119;
			array[114] = -8689426;
			array[115] = -16713062;
			array[116] = -12004916;
			array[117] = -3730043;
			array[118] = -15132304;
			array[119] = -655366;
			array[120] = -6943;
			array[121] = -6987;
			array[122] = -8531;
			array[123] = -16777088;
			array[124] = -133658;
			array[125] = -8355840;
			array[126] = -9728477;
			array[127] = -23296;
			array[128] = -47872;
			array[129] = -2461482;
			array[130] = -1120086;
			array[131] = -6751336;
			array[132] = -5247250;
			array[133] = -2396013;
			array[134] = -4139;
			array[135] = -9543;
			array[136] = -3308225;
			array[137] = -16181;
			array[138] = -2252579;
			array[139] = -5185306;
			array[140] = -8388480;
			array[141] = -65536;
			array[142] = -4419697;
			array[143] = -12490271;
			array[144] = -7650029;
			array[145] = -360334;
			array[146] = -744352;
			array[147] = -13726889;
			array[148] = -2578;
			array[149] = -6270419;
			array[150] = -4144960;
			array[151] = -7876885;
			array[152] = -9807155;
			array[153] = -9404272;
			array[154] = -1286;
			array[155] = -16711809;
			array[156] = -12156236;
			array[157] = -2968436;
			array[158] = -16744320;
			array[159] = -2572328;
			array[160] = -40121;
			array[161] = -12525360;
			array[162] = -1146130;
			array[163] = -663885;
			array[164] = -1;
			array[165] = -657931;
			array[166] = -256;
			array[167] = -6632142;
			s_colorTable = array;
		}

		private static void EnsureColorNameTable()
		{
			if (s_colorNameTable == null)
			{
				InitColorNameTable();
			}
		}

		private static void InitColorNameTable()
		{
			string[] array = new string[175];
			array[1] = "ActiveBorder";
			array[2] = "ActiveCaption";
			array[3] = "ActiveCaptionText";
			array[4] = "AppWorkspace";
			array[168] = "ButtonFace";
			array[169] = "ButtonHighlight";
			array[170] = "ButtonShadow";
			array[5] = "Control";
			array[6] = "ControlDark";
			array[7] = "ControlDarkDark";
			array[8] = "ControlLight";
			array[9] = "ControlLightLight";
			array[10] = "ControlText";
			array[11] = "Desktop";
			array[171] = "GradientActiveCaption";
			array[172] = "GradientInactiveCaption";
			array[12] = "GrayText";
			array[13] = "Highlight";
			array[14] = "HighlightText";
			array[15] = "HotTrack";
			array[16] = "InactiveBorder";
			array[17] = "InactiveCaption";
			array[18] = "InactiveCaptionText";
			array[19] = "Info";
			array[20] = "InfoText";
			array[21] = "Menu";
			array[173] = "MenuBar";
			array[174] = "MenuHighlight";
			array[22] = "MenuText";
			array[23] = "ScrollBar";
			array[24] = "Window";
			array[25] = "WindowFrame";
			array[26] = "WindowText";
			array[27] = "Transparent";
			array[28] = "AliceBlue";
			array[29] = "AntiqueWhite";
			array[30] = "Aqua";
			array[31] = "Aquamarine";
			array[32] = "Azure";
			array[33] = "Beige";
			array[34] = "Bisque";
			array[35] = "Black";
			array[36] = "BlanchedAlmond";
			array[37] = "Blue";
			array[38] = "BlueViolet";
			array[39] = "Brown";
			array[40] = "BurlyWood";
			array[41] = "CadetBlue";
			array[42] = "Chartreuse";
			array[43] = "Chocolate";
			array[44] = "Coral";
			array[45] = "CornflowerBlue";
			array[46] = "Cornsilk";
			array[47] = "Crimson";
			array[48] = "Cyan";
			array[49] = "DarkBlue";
			array[50] = "DarkCyan";
			array[51] = "DarkGoldenrod";
			array[52] = "DarkGray";
			array[53] = "DarkGreen";
			array[54] = "DarkKhaki";
			array[55] = "DarkMagenta";
			array[56] = "DarkOliveGreen";
			array[57] = "DarkOrange";
			array[58] = "DarkOrchid";
			array[59] = "DarkRed";
			array[60] = "DarkSalmon";
			array[61] = "DarkSeaGreen";
			array[62] = "DarkSlateBlue";
			array[63] = "DarkSlateGray";
			array[64] = "DarkTurquoise";
			array[65] = "DarkViolet";
			array[66] = "DeepPink";
			array[67] = "DeepSkyBlue";
			array[68] = "DimGray";
			array[69] = "DodgerBlue";
			array[70] = "Firebrick";
			array[71] = "FloralWhite";
			array[72] = "ForestGreen";
			array[73] = "Fuchsia";
			array[74] = "Gainsboro";
			array[75] = "GhostWhite";
			array[76] = "Gold";
			array[77] = "Goldenrod";
			array[78] = "Gray";
			array[79] = "Green";
			array[80] = "GreenYellow";
			array[81] = "Honeydew";
			array[82] = "HotPink";
			array[83] = "IndianRed";
			array[84] = "Indigo";
			array[85] = "Ivory";
			array[86] = "Khaki";
			array[87] = "Lavender";
			array[88] = "LavenderBlush";
			array[89] = "LawnGreen";
			array[90] = "LemonChiffon";
			array[91] = "LightBlue";
			array[92] = "LightCoral";
			array[93] = "LightCyan";
			array[94] = "LightGoldenrodYellow";
			array[95] = "LightGray";
			array[96] = "LightGreen";
			array[97] = "LightPink";
			array[98] = "LightSalmon";
			array[99] = "LightSeaGreen";
			array[100] = "LightSkyBlue";
			array[101] = "LightSlateGray";
			array[102] = "LightSteelBlue";
			array[103] = "LightYellow";
			array[104] = "Lime";
			array[105] = "LimeGreen";
			array[106] = "Linen";
			array[107] = "Magenta";
			array[108] = "Maroon";
			array[109] = "MediumAquamarine";
			array[110] = "MediumBlue";
			array[111] = "MediumOrchid";
			array[112] = "MediumPurple";
			array[113] = "MediumSeaGreen";
			array[114] = "MediumSlateBlue";
			array[115] = "MediumSpringGreen";
			array[116] = "MediumTurquoise";
			array[117] = "MediumVioletRed";
			array[118] = "MidnightBlue";
			array[119] = "MintCream";
			array[120] = "MistyRose";
			array[121] = "Moccasin";
			array[122] = "NavajoWhite";
			array[123] = "Navy";
			array[124] = "OldLace";
			array[125] = "Olive";
			array[126] = "OliveDrab";
			array[127] = "Orange";
			array[128] = "OrangeRed";
			array[129] = "Orchid";
			array[130] = "PaleGoldenrod";
			array[131] = "PaleGreen";
			array[132] = "PaleTurquoise";
			array[133] = "PaleVioletRed";
			array[134] = "PapayaWhip";
			array[135] = "PeachPuff";
			array[136] = "Peru";
			array[137] = "Pink";
			array[138] = "Plum";
			array[139] = "PowderBlue";
			array[140] = "Purple";
			array[141] = "Red";
			array[142] = "RosyBrown";
			array[143] = "RoyalBlue";
			array[144] = "SaddleBrown";
			array[145] = "Salmon";
			array[146] = "SandyBrown";
			array[147] = "SeaGreen";
			array[148] = "SeaShell";
			array[149] = "Sienna";
			array[150] = "Silver";
			array[151] = "SkyBlue";
			array[152] = "SlateBlue";
			array[153] = "SlateGray";
			array[154] = "Snow";
			array[155] = "SpringGreen";
			array[156] = "SteelBlue";
			array[157] = "Tan";
			array[158] = "Teal";
			array[159] = "Thistle";
			array[160] = "Tomato";
			array[161] = "Turquoise";
			array[162] = "Violet";
			array[163] = "Wheat";
			array[164] = "White";
			array[165] = "WhiteSmoke";
			array[166] = "Yellow";
			array[167] = "YellowGreen";
			s_colorNameTable = array;
		}

		public static int KnownColorToArgb(KnownColor color)
		{
			EnsureColorTable();
			return s_colorTable[(int)color];
		}

		public static string KnownColorToName(KnownColor color)
		{
			EnsureColorNameTable();
			return s_colorNameTable[(int)color];
		}

		private static void UpdateSystemColors(int[] colorTable)
		{
			colorTable[1] = -2830136;
			colorTable[2] = -16755485;
			colorTable[3] = -1;
			colorTable[4] = -8355712;
			colorTable[168] = -986896;
			colorTable[169] = -1;
			colorTable[170] = -6250336;
			colorTable[5] = -1250856;
			colorTable[6] = -5461863;
			colorTable[7] = -9343132;
			colorTable[8] = -921630;
			colorTable[9] = -1;
			colorTable[10] = -16777216;
			colorTable[11] = -16757096;
			colorTable[171] = -4599318;
			colorTable[172] = -2628366;
			colorTable[12] = -5461863;
			colorTable[13] = -13538619;
			colorTable[14] = -1;
			colorTable[15] = -16777088;
			colorTable[16] = -2830136;
			colorTable[17] = -8743201;
			colorTable[18] = -2562824;
			colorTable[19] = -31;
			colorTable[20] = -16777216;
			colorTable[21] = -1;
			colorTable[173] = -986896;
			colorTable[174] = -13395457;
			colorTable[22] = -16777216;
			colorTable[23] = -2830136;
			colorTable[24] = -1;
			colorTable[25] = -16777216;
			colorTable[26] = -16777216;
		}
	}
	public class SizeConverter : TypeConverter
	{
		private static readonly string[] s_propertySort = new string[2] { "Width", "Height" };

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			if (sourceType == typeof(string))
			{
				return true;
			}
			return base.CanConvertFrom(context, sourceType);
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			if (destinationType == typeof(InstanceDescriptor))
			{
				return true;
			}
			return base.CanConvertTo(context, destinationType);
		}

		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			if (value is string text)
			{
				string text2 = text.Trim();
				if (text2.Length == 0)
				{
					return null;
				}
				if (culture == null)
				{
					culture = CultureInfo.CurrentCulture;
				}
				char separator = culture.TextInfo.ListSeparator[0];
				string[] array = text2.Split(separator);
				int[] array2 = new int[array.Length];
				TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
				for (int i = 0; i < array2.Length; i++)
				{
					array2[i] = (int)converter.ConvertFromString(context, culture, array[i]);
				}
				if (array2.Length == 2)
				{
					return new Size(array2[0], array2[1]);
				}
				throw new ArgumentException(SR.Format("Text \"{0}\" cannot be parsed. The expected text format is \"{1}\".", text2, "Width,Height"));
			}
			return base.ConvertFrom(context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == null)
			{
				throw new ArgumentNullException("destinationType");
			}
			if (value is Size)
			{
				if (destinationType == typeof(string))
				{
					Size size = (Size)value;
					if (culture == null)
					{
						culture = CultureInfo.CurrentCulture;
					}
					string separator = culture.TextInfo.ListSeparator + " ";
					TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
					string[] array = new string[2];
					int num = 0;
					array[num++] = converter.ConvertToString(context, culture, size.Width);
					array[num++] = converter.ConvertToString(context, culture, size.Height);
					return string.Join(separator, array);
				}
				if (destinationType == typeof(InstanceDescriptor))
				{
					Size size2 = (Size)value;
					ConstructorInfo constructor = typeof(Size).GetConstructor(new Type[2]
					{
						typeof(int),
						typeof(int)
					});
					if (constructor != null)
					{
						return new InstanceDescriptor(constructor, new object[2] { size2.Width, size2.Height });
					}
				}
			}
			return base.ConvertTo(context, culture, value, destinationType);
		}

		public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
		{
			if (propertyValues == null)
			{
				throw new ArgumentNullException("propertyValues");
			}
			object obj = propertyValues["Width"];
			object obj2 = propertyValues["Height"];
			if (obj == null || obj2 == null || !(obj is int) || !(obj2 is int))
			{
				throw new ArgumentException(SR.Format("IDictionary parameter contains at least one entry that is not valid. Ensure all values are consistent with the object's properties."));
			}
			return new Size((int)obj, (int)obj2);
		}

		public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
		{
			return true;
		}

		public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
		{
			return TypeDescriptor.GetProperties(typeof(Size), attributes).Sort(s_propertySort);
		}

		public override bool GetPropertiesSupported(ITypeDescriptorContext context)
		{
			return true;
		}
	}
	public class SizeFConverter : TypeConverter
	{
		private static readonly string[] s_propertySort = new string[2] { "Width", "Height" };

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			if (sourceType == typeof(string))
			{
				return true;
			}
			return base.CanConvertFrom(context, sourceType);
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			if (destinationType == typeof(InstanceDescriptor))
			{
				return true;
			}
			return base.CanConvertTo(context, destinationType);
		}

		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			if (value is string text)
			{
				string text2 = text.Trim();
				if (text2.Length == 0)
				{
					return null;
				}
				if (culture == null)
				{
					culture = CultureInfo.CurrentCulture;
				}
				char separator = culture.TextInfo.ListSeparator[0];
				string[] array = text2.Split(separator);
				float[] array2 = new float[array.Length];
				TypeConverter converter = TypeDescriptor.GetConverter(typeof(float));
				for (int i = 0; i < array2.Length; i++)
				{
					array2[i] = (float)converter.ConvertFromString(context, culture, array[i]);
				}
				if (array2.Length == 2)
				{
					return new SizeF(array2[0], array2[1]);
				}
				throw new ArgumentException(SR.Format("Text \"{0}\" cannot be parsed. The expected text format is \"{1}\".", text2, "Width,Height"));
			}
			return base.ConvertFrom(context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == null)
			{
				throw new ArgumentNullException("destinationType");
			}
			if (destinationType == typeof(string) && value is SizeF sizeF)
			{
				if (culture == null)
				{
					culture = CultureInfo.CurrentCulture;
				}
				string separator = culture.TextInfo.ListSeparator + " ";
				TypeConverter converter = TypeDescriptor.GetConverter(typeof(float));
				string[] array = new string[2];
				int num = 0;
				array[num++] = converter.ConvertToString(context, culture, sizeF.Width);
				array[num++] = converter.ConvertToString(context, culture, sizeF.Height);
				return string.Join(separator, array);
			}
			if (destinationType == typeof(InstanceDescriptor) && value is SizeF sizeF2)
			{
				ConstructorInfo constructor = typeof(SizeF).GetConstructor(new Type[2]
				{
					typeof(float),
					typeof(float)
				});
				if (constructor != null)
				{
					return new InstanceDescriptor(constructor, new object[2] { sizeF2.Width, sizeF2.Height });
				}
			}
			return base.ConvertTo(context, culture, value, destinationType);
		}

		public override object CreateInstance(ITypeDescriptorContext context, IDictionary propertyValues)
		{
			if (propertyValues == null)
			{
				throw new ArgumentNullException("propertyValues");
			}
			object obj = propertyValues["Width"];
			object obj2 = propertyValues["Height"];
			if (obj == null || obj2 == null || !(obj is float) || !(obj2 is float))
			{
				throw new ArgumentException(SR.Format("IDictionary parameter contains at least one entry that is not valid. Ensure all values are consistent with the object's properties."));
			}
			return new SizeF((float)obj, (float)obj2);
		}

		public override bool GetCreateInstanceSupported(ITypeDescriptorContext context)
		{
			return true;
		}

		public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
		{
			return TypeDescriptor.GetProperties(typeof(SizeF), attributes).Sort(s_propertySort);
		}

		public override bool GetPropertiesSupported(ITypeDescriptorContext context)
		{
			return true;
		}
	}
	internal static class AssemblyRef
	{
		public const string SystemDrawingDesign = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

		public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

		public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class BitmapSuffixInSameAssemblyAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	public class BitmapSuffixInSatelliteAssemblyAttribute : Attribute
	{
	}
	public abstract class Brush : MarshalByRefObject, ICloneable, IDisposable
	{
		private IntPtr _nativeBrush;

		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Never)]
		internal IntPtr NativeBrush => _nativeBrush;

		public abstract object Clone();

		protected internal void SetNativeBrush(IntPtr brush)
		{
			SetNativeBrushInternal(brush);
		}

		internal void SetNativeBrushInternal(IntPtr brush)
		{
			_nativeBrush = brush;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (!(_nativeBrush != IntPtr.Zero))
			{
				return;
			}
			try
			{
				GDIPlus.GdipDeleteBrush(new HandleRef(this, _nativeBrush));
			}
			catch (Exception ex) when (!ClientUtils.IsSecurityOrCriticalException(ex))
			{
			}
			finally
			{
				_nativeBrush = IntPtr.Zero;
			}
		}

		~Brush()
		{
			Dispose(disposing: false);
		}
	}
	internal static class ClientUtils
	{
		internal class WeakRefCollection : IList, ICollection, IEnumerable
		{
			internal class WeakRefObject
			{
				private int _hash;

				private WeakReference _weakHolder;

				internal bool IsAlive => _weakHolder.IsAlive;

				internal object Target => _weakHolder.Target;

				internal WeakRefObject(object obj)
				{
					_weakHolder = new WeakReference(obj);
					_hash = obj.GetHashCode();
				}

				public override int GetHashCode()
				{
					return _hash;
				}

				public override bool Equals(object obj)
				{
					WeakRefObject weakRefObject = obj as WeakRefObject;
					if (weakRefObject == this)
					{
						return true;
					}
					if (weakRefObject == null)
					{
						return false;
					}
					if (weakRefObject.Target != Target && (Target == null || !Target.Equals(weakRefObject.Target)))
					{
						return false;
					}
					return true;
				}
			}

			internal ArrayList InnerList { get; }

			public int RefCheckThreshold { get; set; } = int.MaxValue;


			public object this[int index]
			{
				get
				{
					if (InnerList[index] is WeakRefObject weakRefObject && weakRefObject.IsAlive)
					{
						return weakRefObject.Target;
					}
					return null;
				}
				set
				{
					InnerList[index] = CreateWeakRefObject(value);
				}
			}

			public bool IsFixedSize => InnerList.IsFixedSize;

			public int Count => InnerList.Count;

			object ICollection.SyncRoot => InnerList.SyncRoot;

			public bool IsReadOnly => InnerList.IsReadOnly;

			bool ICollection.IsSynchronized => InnerList.IsSynchronized;

			internal WeakRefCollection()
				: this(4)
			{
			}

			internal WeakRefCollection(int size)
			{
				InnerList = new ArrayList(size);
			}

			public void ScavengeReferences()
			{
				int num = 0;
				int count = Count;
				for (int i = 0; i < count; i++)
				{
					if (this[num] == null)
					{
						InnerList.RemoveAt(num);
					}
					else
					{
						num++;
					}
				}
			}

			public override bool Equals(object obj)
			{
				if (!(obj is WeakRefCollection weakRefCollection))
				{
					return true;
				}
				if (weakRefCollection == null || Count != weakRefCollection.Count)
				{
					return false;
				}
				for (int i = 0; i < Count; i++)
				{
					if (InnerList[i] != weakRefCollection.InnerList[i] && (InnerList[i] == null || !InnerList[i].Equals(weakRefCollection.InnerList[i])))
					{
						return false;
					}
				}
				return true;
			}

			public override int GetHashCode()
			{
				return base.GetHashCode();
			}

			private WeakRefObject CreateWeakRefObject(object value)
			{
				if (value == null)
				{
					return null;
				}
				return new WeakRefObject(value);
			}

			private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length)
			{
				if (sourceIndex < destinationIndex)
				{
					sourceIndex += length;
					destinationIndex += length;
					while (length > 0)
					{
						destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex];
						length--;
					}
				}
				else
				{
					while (length > 0)
					{
						destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++];
						length--;
					}
				}
			}

			public void RemoveByHashCode(object value)
			{
				if (value == null)
				{
					return;
				}
				int hashCode = value.GetHashCode();
				for (int i = 0; i < InnerList.Count; i++)
				{
					if (InnerList[i] != null && InnerList[i].GetHashCode() == hashCode)
					{
						RemoveAt(i);
						break;
					}
				}
			}

			public void Clear()
			{
				InnerList.Clear();
			}

			public bool Contains(object value)
			{
				return InnerList.Contains(CreateWeakRefObject(value));
			}

			public void RemoveAt(int index)
			{
				InnerList.RemoveAt(index);
			}

			public void Remove(object value)
			{
				InnerList.Remove(CreateWeakRefObject(value));
			}

			public int IndexOf(object value)
			{
				return InnerList.IndexOf(CreateWeakRefObject(value));
			}

			public void Insert(int index, object value)
			{
				InnerList.Insert(index, CreateWeakRefObject(value));
			}

			public int Add(object value)
			{
				if (Count > RefCheckThreshold)
				{
					ScavengeReferences();
				}
				return InnerList.Add(CreateWeakRefObject(value));
			}

			public void CopyTo(Array array, int index)
			{
				InnerList.CopyTo(array, index);
			}

			public IEnumerator GetEnumerator()
			{
				return InnerList.GetEnumerator();
			}
		}

		public static bool IsCriticalException(Exception ex)
		{
			if (!(ex is NullReferenceException) && !(ex is StackOverflowException) && !(ex is OutOfMemoryException) && !(ex is ThreadAbortException) && !(ex is ExecutionEngineException) && !(ex is IndexOutOfRangeException))
			{
				return ex is AccessViolationException;
			}
			return true;
		}

		public static bool IsSecurityOrCriticalException(Exception ex)
		{
			if (!(ex is SecurityException))
			{
				return IsCriticalException(ex);
			}
			return true;
		}
	}
	public class ColorConverter : TypeConverter
	{
		private class ColorComparer : IComparer
		{
			public int Compare(object left, object right)
			{
				Color color = (Color)left;
				Color color2 = (Color)right;
				return string.Compare(color.Name, color2.Name, ignoreCase: false, CultureInfo.InvariantCulture);
			}
		}

		private static string ColorConstantsLock = "colorConstants";

		private static Hashtable colorConstants;

		private static string SystemColorConstantsLock = "systemColorConstants";

		private static Hashtable systemColorConstants;

		private static string ValuesLock = "values";

		private static StandardValuesCollection values;

		private static Hashtable Colors
		{
			get
			{
				if (colorConstants == null)
				{
					lock (ColorConstantsLock)
					{
						if (colorConstants == null)
						{
							Hashtable hash = new Hashtable(StringComparer.OrdinalIgnoreCase);
							FillConstants(hash, typeof(Color));
							colorConstants = hash;
						}
					}
				}
				return colorConstants;
			}
		}

		private static Hashtable SystemColors
		{
			get
			{
				if (systemColorConstants == null)
				{
					lock (SystemColorConstantsLock)
					{
						if (systemColorConstants == null)
						{
							Hashtable hash = new Hashtable(StringComparer.OrdinalIgnoreCase);
							FillConstants(hash, typeof(SystemColors));
							systemColorConstants = hash;
						}
					}
				}
				return systemColorConstants;
			}
		}

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			if (sourceType == typeof(string))
			{
				return true;
			}
			return base.CanConvertFrom(context, sourceType);
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			if (destinationType == typeof(InstanceDescriptor))
			{
				return true;
			}
			return base.CanConvertTo(context, destinationType);
		}

		internal static object GetNamedColor(string name)
		{
			object obj = null;
			obj = Colors[name];
			if (obj != null)
			{
				return obj;
			}
			return SystemColors[name];
		}

		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			if (value is string text)
			{
				object obj = null;
				string text2 = text.Trim();
				if (text2.Length == 0)
				{
					obj = Color.Empty;
				}
				else
				{
					obj = GetNamedColor(text2);
					if (obj == null)
					{
						if (culture == null)
						{
							culture = CultureInfo.CurrentCulture;
						}
						char c = culture.TextInfo.ListSeparator[0];
						bool flag = true;
						TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
						if (text2.IndexOf(c) == -1)
						{
							if (text2.Length >= 2 && (text2[0] == '\'' || text2[0] == '"') && text2[0] == text2[text2.Length - 1])
							{
								obj = Color.FromName(text2.Substring(1, text2.Length - 2));
								flag = false;
							}
							else if ((text2.Length == 7 && text2[0] == '#') || (text2.Length == 8 && (text2.StartsWith("0x") || text2.StartsWith("0X"))) || (text2.Length == 8 && (text2.StartsWith("&h") || text2.StartsWith("&H"))))
							{
								obj = Color.FromArgb(-16777216 | (int)converter.ConvertFromString(context, culture, text2));
							}
						}
						if (obj == null)
						{
							string[] array = text2.Split(new char[1] { c });
							int[] array2 = new int[array.Length];
							for (int i = 0; i < array2.Length; i++)
							{
								array2[i] = (int)converter.ConvertFromString(context, culture, array[i]);
							}
							switch (array2.Length)
							{
							case 1:
								obj = Color.FromArgb(array2[0]);
								break;
							case 3:
								obj = Color.FromArgb(array2[0], array2[1], array2[2]);
								break;
							case 4:
								obj = Color.FromArgb(array2[0], array2[1], array2[2], array2[3]);
								break;
							}
							flag = true;
						}
						if (obj != null && flag)
						{
							int num = ((Color)obj).ToArgb();
							foreach (Color value2 in Colors.Values)
							{
								if (value2.ToArgb() == num)
								{
									obj = value2;
									break;
								}
							}
						}
					}
					if (obj == null)
					{
						throw new ArgumentException(SR.Format("Color '{0}' is not valid.", text2));
					}
				}
				return obj;
			}
			return base.ConvertFrom(context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == null)
			{
				throw new ArgumentNullException("destinationType");
			}
			if (value is Color)
			{
				if (destinationType == typeof(string))
				{
					Color color = (Color)value;
					if (color == Color.Empty)
					{
						return string.Empty;
					}
					if (color.IsKnownColor)
					{
						return color.Name;
					}
					if (color.IsNamedColor)
					{
						return "'" + color.Name + "'";
					}
					if (culture == null)
					{
						culture = CultureInfo.CurrentCulture;
					}
					string separator = culture.TextInfo.ListSeparator + " ";
					TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
					int num = 0;
					string[] array;
					if (color.A < byte.MaxValue)
					{
						array = new string[4];
						array[num++] = converter.ConvertToString(context, culture, color.A);
					}
					else
					{
						array = new string[3];
					}
					array[num++] = converter.ConvertToString(context, culture, color.R);
					array[num++] = converter.ConvertToString(context, culture, color.G);
					array[num++] = converter.ConvertToString(context, culture, color.B);
					return string.Join(separator, array);
				}
				if (destinationType == typeof(InstanceDescriptor))
				{
					MemberInfo memberInfo = null;
					object[] arguments = null;
					Color color2 = (Color)value;
					if (color2.IsEmpty)
					{
						memberInfo = typeof(Color).GetField("Empty");
					}
					else if (color2.IsSystemColor)
					{
						memberInfo = typeof(SystemColors).GetProperty(color2.Name);
					}
					else if (color2.IsKnownColor)
					{
						memberInfo = typeof(Color).GetProperty(color2.Name);
					}
					else if (color2.A != byte.MaxValue)
					{
						memberInfo = typeof(Color).GetMethod("FromArgb", new Type[4]
						{
							typeof(int),
							typeof(int),
							typeof(int),
							typeof(int)
						});
						arguments = new object[4] { color2.A, color2.R, color2.G, color2.B };
					}
					else if (color2.IsNamedColor)
					{
						memberInfo = typeof(Color).GetMethod("FromName", new Type[1] { typeof(string) });
						arguments = new object[1] { color2.Name };
					}
					else
					{
						memberInfo = typeof(Color).GetMethod("FromArgb", new Type[3]
						{
							typeof(int),
							typeof(int),
							typeof(int)
						});
						arguments = new object[3] { color2.R, color2.G, color2.B };
					}
					if (memberInfo != null)
					{
						return new InstanceDescriptor(memberInfo, arguments);
					}
					return null;
				}
			}
			return base.ConvertTo(context, culture, value, destinationType);
		}

		private static void FillConstants(Hashtable hash, Type enumType)
		{
			MethodAttributes methodAttributes = MethodAttributes.Public | MethodAttributes.Static;
			PropertyInfo[] properties = enumType.GetProperties();
			foreach (PropertyInfo propertyInfo in properties)
			{
				if (propertyInfo.PropertyType == typeof(Color))
				{
					MethodInfo getMethod = propertyInfo.GetGetMethod();
					if (getMethod != null && (getMethod.Attributes & methodAttributes) == methodAttributes)
					{
						object[] index = null;
						hash[propertyInfo.Name] = propertyInfo.GetValue(null, index);
					}
				}
			}
		}

		public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
		{
			if (values == null)
			{
				lock (ValuesLock)
				{
					if (values == null)
					{
						ArrayList arrayList = new ArrayList();
						arrayList.AddRange(Colors.Values);
						arrayList.AddRange(SystemColors.Values);
						int num = arrayList.Count;
						for (int i = 0; i < num - 1; i++)
						{
							for (int j = i + 1; j < num; j++)
							{
								if (arrayList[i].Equals(arrayList[j]))
								{
									arrayList.RemoveAt(j);
									num--;
									j--;
								}
							}
						}
						arrayList.Sort(0, arrayList.Count, new ColorComparer());
						values = new StandardValuesCollection(arrayList.ToArray());
					}
				}
			}
			return values;
		}

		public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
		{
			return true;
		}
	}
	[Flags]
	public enum FontStyle
	{
		Regular = 0,
		Bold = 1,
		Italic = 2,
		Underline = 4,
		Strikeout = 8
	}
	internal class SafeNativeMethods
	{
		internal class Gdip : GDIPlus
		{
			private static readonly TraceSwitch s_gdiPlusInitialization;

			private static IntPtr s_initToken;

			private const string ThreadDataSlotName = "system.drawing.threaddata";

			internal const int Ok = 0;

			internal const int GenericError = 1;

			internal const int InvalidParameter = 2;

			internal const int OutOfMemory = 3;

			internal const int ObjectBusy = 4;

			internal const int InsufficientBuffer = 5;

			internal const int NotImplemented = 6;

			internal const int Win32Error = 7;

			internal const int WrongState = 8;

			internal const int Aborted = 9;

			internal const int FileNotFound = 10;

			internal const int ValueOverflow = 11;

			internal const int AccessDenied = 12;

			internal const int UnknownImageFormat = 13;

			internal const int FontFamilyNotFound = 14;

			internal const int FontStyleNotFound = 15;

			internal const int NotTrueTypeFont = 16;

			internal const int UnsupportedGdiplusVersion = 17;

			internal const int GdiplusNotInitialized = 18;

			internal const int PropertyNotFound = 19;

			internal const int PropertyNotSupported = 20;

			private static bool Initialized => s_initToken != IntPtr.Zero;

			internal static IDictionary ThreadData
			{
				get
				{
					LocalDataStoreSlot namedDataSlot = Thread.GetNamedDataSlot("system.drawing.threaddata");
					IDictionary dictionary = (IDictionary)Thread.GetData(namedDataSlot);
					if (dictionary == null)
					{
						dictionary = new Hashtable();
						Thread.SetData(namedDataSlot, dictionary);
					}
					return dictionary;
				}
			}

			static Gdip()
			{
				s_gdiPlusInitialization = new TraceSwitch("GdiPlusInitialization", "Tracks GDI+ initialization and teardown");
				s_initToken = (IntPtr)1;
				AppDomain currentDomain = AppDomain.CurrentDomain;
				currentDomain.ProcessExit += OnProcessExit;
				if (!currentDomain.IsDefaultAppDomain())
				{
					currentDomain.DomainUnload += OnProcessExit;
				}
			}

			[MethodImpl(MethodImplOptions.NoInlining)]
			private static void ClearThreadData()
			{
				Thread.SetData(Thread.GetNamedDataSlot("system.drawing.threaddata"), null);
			}

			private static void Shutdown()
			{
				if (Initialized)
				{
					ClearThreadData();
					AppDomain currentDomain = AppDomain.CurrentDomain;
					currentDomain.ProcessExit -= OnProcessExit;
					if (!currentDomain.IsDefaultAppDomain())
					{
						currentDomain.DomainUnload -= OnProcessExit;
					}
				}
			}

			[PrePrepareMethod]
			private static void OnProcessExit(object sender, EventArgs e)
			{
				Shutdown();
			}

			internal static void DummyFunction()
			{
			}

			internal static void CheckStatus(int status)
			{
				if (status != 0)
				{
					throw StatusException(status);
				}
			}

			internal static Exception StatusException(int status)
			{
				return status switch
				{
					1 => new ExternalException(SR.Format("A generic error occurred in GDI+."), -2147467259), 
					2 => new ArgumentException(SR.Format("Parameter is not valid.")), 
					3 => new OutOfMemoryException(SR.Format("Out of memory.")), 
					4 => new InvalidOperationException(SR.Format("Object is currently in use elsewhere.")), 
					5 => new OutOfMemoryException(SR.Format("Buffer is too small (internal GDI+ error).")), 
					6 => new NotImplementedException(SR.Format("Not implemented.")), 
					7 => new ExternalException(SR.Format("A generic error occurred in GDI+."), -2147467259), 
					8 => new InvalidOperationException(SR.Format("Bitmap region is already locked.")), 
					9 => new ExternalException(SR.Format("Function was ended."), -2147467260), 
					10 => new FileNotFoundException(SR.Format("File not found.")), 
					11 => new OverflowException(SR.Format("Overflow error.")), 
					12 => new ExternalException(SR.Format("File access is denied."), -2147024891), 
					13 => new ArgumentException(SR.Format("Image format is unknown.")), 
					19 => new ArgumentException(SR.Format("Property cannot be found.")), 
					20 => new ArgumentException(SR.Format("Property is not supported.")), 
					14 => new ArgumentException(SR.Format("Font '{0}' cannot be found.", "?")), 
					15 => new ArgumentException(SR.Format("Font '{0}' does not support style '{1}'.", "?", "?")), 
					16 => new ArgumentException(SR.Format("Only TrueType fonts are supported. This is not a TrueType font.")), 
					17 => new ExternalException(SR.Format("Current version of GDI+ does not support this feature."), -2147467259), 
					18 => new ExternalException(SR.Format("GDI+ is not properly initialized (internal GDI+ error)."), -2147467259), 
					_ => new ExternalException(SR.Format("Unknown GDI+ error occurred."), -2147418113), 
				};
			}

			internal static PointF[] ConvertGPPOINTFArrayF(IntPtr memory, int count)
			{
				if (memory == IntPtr.Zero)
				{
					throw new ArgumentNullException("memory");
				}
				PointF[] array = new PointF[count];
				Type typeFromHandle = typeof(GPPOINTF);
				int num = Marshal.SizeOf(typeFromHandle);
				for (int i = 0; i < count; i++)
				{
					GPPOINTF gPPOINTF = (GPPOINTF)Marshal.PtrToStructure((IntPtr)((long)memory + i * num), typeFromHandle);
					array[i] = new PointF(gPPOINTF.X, gPPOINTF.Y);
				}
				return array;
			}

			internal static Point[] ConvertGPPOINTArray(IntPtr memory, int count)
			{
				if (memory == IntPtr.Zero)
				{
					throw new ArgumentNullException("memory");
				}
				Point[] array = new Point[count];
				Type typeFromHandle = typeof(GPPOINT);
				int num = Marshal.SizeOf(typeFromHandle);
				for (int i = 0; i < count; i++)
				{
					GPPOINT gPPOINT = (GPPOINT)Marshal.PtrToStructure((IntPtr)((long)memory + i * num), typeFromHandle);
					array[i] = new Point(gPPOINT.X, gPPOINT.Y);
				}
				return array;
			}

			internal static IntPtr ConvertPointToMemory(PointF[] points)
			{
				if (points == null)
				{
					throw new ArgumentNullException("points");
				}
				int num = Marshal.SizeOf(typeof(GPPOINTF));
				int num2 = points.Length;
				IntPtr intPtr = Marshal.AllocHGlobal(checked(num2 * num));
				for (int i = 0; i < num2; i++)
				{
					Marshal.StructureToPtr(new GPPOINTF(points[i]), (IntPtr)checked((long)intPtr + i * num), fDeleteOld: false);
				}
				return intPtr;
			}

			internal static IntPtr ConvertPointToMemory(Point[] points)
			{
				if (points == null)
				{
					throw new ArgumentNullException("points");
				}
				int num = Marshal.SizeOf(typeof(GPPOINT));
				int num2 = points.Length;
				IntPtr intPtr = Marshal.AllocHGlobal(checked(num2 * num));
				for (int i = 0; i < num2; i++)
				{
					Marshal.StructureToPtr(new GPPOINT(points[i]), (IntPtr)checked((long)intPtr + i * num), fDeleteOld: false);
				}
				return intPtr;
			}

			internal static IntPtr ConvertRectangleToMemory(RectangleF[] rect)
			{
				if (rect == null)
				{
					throw new ArgumentNullException("rect");
				}
				int num = Marshal.SizeOf(typeof(GPRECTF));
				int num2 = rect.Length;
				IntPtr intPtr = Marshal.AllocHGlobal(checked(num2 * num));
				for (int i = 0; i < num2; i++)
				{
					Marshal.StructureToPtr(new GPRECTF(rect[i]), (IntPtr)checked((long)intPtr + i * num), fDeleteOld: false);
				}
				return intPtr;
			}

			internal static IntPtr ConvertRectangleToMemory(Rectangle[] rect)
			{
				if (rect == null)
				{
					throw new ArgumentNullException("rect");
				}
				int num = Marshal.SizeOf(typeof(GPRECT));
				int num2 = rect.Length;
				IntPtr intPtr = Marshal.AllocHGlobal(checked(num2 * num));
				for (int i = 0; i < num2; i++)
				{
					Marshal.StructureToPtr(new GPRECT(rect[i]), (IntPtr)checked((long)intPtr + i * num), fDeleteOld: false);
				}
				return intPtr;
			}
		}

		[StructLayout(LayoutKind.Sequential)]
		public class ENHMETAHEADER
		{
			public int iType;

			public int nSize = 40;

			public int rclBounds_left;

			public int rclBounds_top;

			public int rclBounds_right;

			public int rclBounds_bottom;

			public int rclFrame_left;

			public int rclFrame_top;

			public int rclFrame_right;

			public int rclFrame_bottom;

			public int dSignature;

			public int nVersion;

			public int nBytes;

			public int nRecords;

			public short nHandles;

			public short sReserved;

			public int nDescription;

			public int offDescription;

			public int nPalEntries;

			public int szlDevice_cx;

			public int szlDevice_cy;

			public int szlMillimeters_cx;

			public int szlMillimeters_cy;

			public int cbPixelFormat;

			public int offPixelFormat;

			public int bOpenGL;
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
		public class DOCINFO
		{
			public int cbSize = 20;

			public string lpszDocName;

			public string lpszOutput;

			public string lpszDatatype;

			public int fwType;
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
		public class PRINTDLG
		{
			public int lStructSize;

			public IntPtr hwndOwner;

			public IntPtr hDevMode;

			public IntPtr hDevNames;

			public IntPtr hDC;

			public int Flags;

			public short nFromPage;

			public short nToPage;

			public short nMinPage;

			public short nMaxPage;

			public short nCopies;

			public IntPtr hInstance;

			public IntPtr lCustData;

			public IntPtr lpfnPrintHook;

			public IntPtr lpfnSetupHook;

			public string lpPrintTemplateName;

			public string lpSetupTemplateName;

			public IntPtr hPrintTemplate;

			public IntPtr hSetupTemplate;
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 1)]
		public class PRINTDLGX86
		{
			public int lStructSize;

			public IntPtr hwndOwner;

			public IntPtr hDevMode;

			public IntPtr hDevNames;

			public IntPtr hDC;

			public int Flags;

			public short nFromPage;

			public short nToPage;

			public short nMinPage;

			public short nMaxPage;

			public short nCopies;

			public IntPtr hInstance;

			public IntPtr lCustData;

			public IntPtr lpfnPrintHook;

			public IntPtr lpfnSetupHook;

			public string lpPrintTemplateName;

			public string lpSetupTemplateName;

			public IntPtr hPrintTemplate;

			public IntPtr hSetupTemplate;
		}

		[StructLayout(LayoutKind.Sequential)]
		public class ICONINFO
		{
			public int fIcon;

			public int xHotspot;

			public int yHotspot;

			public IntPtr hbmMask = IntPtr.Zero;

			public IntPtr hbmColor = IntPtr.Zero;
		}

		[StructLayout(LayoutKind.Sequential)]
		public class BITMAP
		{
			public int bmType;

			public int bmWidth;

			public int bmHeight;

			public int bmWidthBytes;

			public short bmPlanes;

			public short bmBitsPixel;

			public IntPtr bmBits = IntPtr.Zero;
		}

		[StructLayout(LayoutKind.Sequential)]
		public class BITMAPINFOHEADER
		{
			public int biSize = 40;

			public int biWidth;

			public int biHeight;

			public short biPlanes;

			public short biBitCount;

			public int biCompression;

			public int biSizeImage;

			public int biXPelsPerMeter;

			public int biYPelsPerMeter;

			public int biClrUsed;

			public int biClrImportant;
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
		public class LOGFONT
		{
			public int lfHeight;

			public int lfWidth;

			public int lfEscapement;

			public int lfOrientation;

			public int lfWeight;

			public byte lfItalic;

			public byte lfUnderline;

			public byte lfStrikeOut;

			public byte lfCharSet;

			public byte lfOutPrecision;

			public byte lfClipPrecision;

			public byte lfQuality;

			public byte lfPitchAndFamily;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
			public string lfFaceName;

			public override string ToString()
			{
				return "lfHeight=" + lfHeight + ", lfWidth=" + lfWidth + ", lfEscapement=" + lfEscapement + ", lfOrientation=" + lfOrientation + ", lfWeight=" + lfWeight + ", lfItalic=" + lfItalic + ", lfUnderline=" + lfUnderline + ", lfStrikeOut=" + lfStrikeOut + ", lfCharSet=" + lfCharSet + ", lfOutPrecision=" + lfOutPrecision + ", lfClipPrecision=" + lfClipPrecision + ", lfQuality=" + lfQuality + ", lfPitchAndFamily=" + lfPitchAndFamily + ", lfFaceName=" + lfFaceName;
			}
		}

		[StructLayout(LayoutKind.Sequential, Pack = 2)]
		public struct ICONDIR
		{
			public short idReserved;

			public short idType;

			public short idCount;

			public ICONDIRENTRY idEntries;
		}

		public struct ICONDIRENTRY
		{
			public byte bWidth;

			public byte bHeight;

			public byte bColorCount;

			public byte bReserved;

			public short wPlanes;

			public short wBitCount;

			public int dwBytesInRes;

			public int dwImageOffset;
		}

		public class Ole
		{
			public const int PICTYPE_ICON = 3;
		}

		[StructLayout(LayoutKind.Sequential)]
		public class PICTDESC
		{
			internal int cbSizeOfStruct;

			public int picType;

			internal IntPtr union1;

			internal int union2;

			internal int union3;

			public static PICTDESC CreateIconPICTDESC(IntPtr hicon)
			{
				return new PICTDESC
				{
					cbSizeOfStruct = 12,
					picType = 3,
					union1 = hicon
				};
			}
		}

		[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
		public class DEVMODE
		{
			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
			public string dmDeviceName;

			public short dmSpecVersion;

			public short dmDriverVersion;

			public short dmSize;

			public short dmDriverExtra;

			public int dmFields;

			public short dmOrientation;

			public short dmPaperSize;

			public short dmPaperLength;

			public short dmPaperWidth;

			public short dmScale;

			public short dmCopies;

			public short dmDefaultSource;

			public short dmPrintQuality;

			public short dmColor;

			public short dmDuplex;

			public short dmYResolution;

			public short dmTTOption;

			public short dmCollate;

			[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
			public string dmFormName;

			public short dmLogPixels;

			public int dmBitsPerPel;

			public int dmPelsWidth;

			public int dmPelsHeight;

			public int dmDisplayFlags;

			public int dmDisplayFrequency;

			public int dmICMMethod;

			public int dmICMIntent;

			public int dmMediaType;

			public int dmDitherType;

			public int dmICCManufacturer;

			public int dmICCModel;

			public int dmPanningWidth;

			public int dmPanningHeight;

			public override string ToString()
			{
				return "[DEVMODE: dmDeviceName=" + dmDeviceName + ", dmSpecVersion=" + dmSpecVersion + ", dmDriverVersion=" + dmDriverVersion + ", dmSize=" + dmSize + ", dmDriverExtra=" + dmDriverExtra + ", dmFields=" + dmFields + ", dmOrientation=" + dmOrientation + ", dmPaperSize=" + dmPaperSize + ", dmPaperLength=" + dmPaperLength + ", dmPaperWidth=" + dmPaperWidth + ", dmScale=" + dmScale + ", dmCopies=" + dmCopies + ", dmDefaultSource=" + dmDefaultSource + ", dmPrintQuality=" + dmPrintQuality + ", dmColor=" + dmColor + ", dmDuplex=" + dmDuplex + ", dmYResolution=" + dmYResolution + ", dmTTOption=" + dmTTOption + ", dmCollate=" + dmCollate + ", dmFormName=" + dmFormName + ", dmLogPixels=" + dmLogPixels + ", dmBitsPerPel=" + dmBitsPerPel + ", dmPelsWidth=" + dmPelsWidth + ", dmPelsHeight=" + dmPelsHeight + ", dmDisplayFlags=" + dmDisplayFlags + ", dmDisplayFrequency=" + dmDisplayFrequency + ", dmICMMethod=" + dmICMMethod + ", dmICMIntent=" + dmICMIntent + ", dmMediaType=" + dmMediaType + ", dmDitherType=" + dmDitherType + ", dmICCManufacturer=" + dmICCManufacturer + ", dmICCModel=" + dmICCModel + ", dmPanningWidth=" + dmPanningWidth + ", dmPanningHeight=" + dmPanningHeight + "]";
			}
		}

		public sealed class CommonHandles
		{
			public static readonly int GDI;

			public static readonly int HDC;

			public static readonly int Icon;

			public static readonly int Kernel;

			static CommonHandles()
			{
				GDI = System.Internal.HandleCollector.RegisterType("GDI", 50, 500);
				HDC = System.Internal.HandleCollector.RegisterType("HDC", 100, 2);
				Icon = System.Internal.HandleCollector.RegisterType("Icon", 20, 500);
				Kernel = System.Internal.HandleCollector.RegisterType("Kernel", 0, 1000);
			}
		}

		public class StreamConsts
		{
			public const int STREAM_SEEK_SET = 0;

			public const int STREAM_SEEK_CUR = 1;

			public const int STREAM_SEEK_END = 2;
		}

		[ComImport]
		[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
		[Guid("7BF80980-BF32-101A-8BBB-00AA00300CAB")]
		public interface IPicture
		{
			IntPtr GetHandle();

			IntPtr GetHPal();

			[return: MarshalAs(UnmanagedType.I2)]
			short GetPictureType();

			int GetWidth();

			int GetHeight();

			void Render();

			void SetHPal([In] IntPtr phpal);

			IntPtr GetCurDC();

			void SelectPicture([In] IntPtr hdcIn, [Out][MarshalAs(UnmanagedType.LPArray)] int[] phdcOut, [Out][MarshalAs(UnmanagedType.LPArray)] int[] phbmpOut);

			[return: MarshalAs(UnmanagedType.Bool)]
			bool GetKeepOriginalFormat();

			void SetKeepOriginalFormat([In][MarshalAs(UnmanagedType.Bool)] bool pfkeep);

			void PictureChanged();

			[PreserveSig]
			int SaveAsFile([In][MarshalAs(UnmanagedType.Interface)] UnsafeNativeMethods.IStream pstm, [In] int fSaveMemCopy, out int pcbSize);

			int GetAttributes();

			void SetHdc([In] IntPtr hdc);
		}

		public const int ERROR_CANCELLED = 1223;

		public const int E_UNEXPECTED = -2147418113;

		public const int E_NOTIMPL = -2147467263;

		public const int E_ABORT = -2147467260;

		public const int E_FAIL = -2147467259;

		public const int E_ACCESSDENIED = -2147024891;

		public const int GMEM_MOVEABLE = 2;

		public const int GMEM_ZEROINIT = 64;

		public const int DM_IN_BUFFER = 8;

		public const int DM_OUT_BUFFER = 2;

		public const int DT_PLOTTER = 0;

		public const int DT_RASPRINTER = 2;

		public const int TECHNOLOGY = 2;

		public const int DC_PAPERS = 2;

		public const int DC_PAPERSIZE = 3;

		public const int DC_BINS = 6;

		public const int DC_DUPLEX = 7;

		public const int DC_BINNAMES = 12;

		public const int DC_ENUMRESOLUTIONS = 13;

		public const int DC_PAPERNAMES = 16;

		public const int DC_ORIENTATION = 17;

		public const int DC_COPIES = 18;

		public const int PD_ALLPAGES = 0;

		public const int PD_SELECTION = 1;

		public const int PD_PAGENUMS = 2;

		public const int PD_CURRENTPAGE = 4194304;

		public const int PD_RETURNDEFAULT = 1024;

		public const int DI_NORMAL = 3;

		public const int IMAGE_ICON = 1;

		public const int IDI_APPLICATION = 32512;

		public const int IDI_HAND = 32513;

		public const int IDI_QUESTION = 32514;

		public const int IDI_EXCLAMATION = 32515;

		public const int IDI_ASTERISK = 32516;

		public const int IDI_WINLOGO = 32517;

		public const int IDI_WARNING = 32515;

		public const int IDI_ERROR = 32513;

		public const int IDI_INFORMATION = 32516;

		public const int SRCCOPY = 13369376;

		public const int PLANES = 14;

		public const int BITSPIXEL = 12;

		public const int LOGPIXELSX = 88;

		public const int LOGPIXELSY = 90;

		public const int PHYSICALWIDTH = 110;

		public const int PHYSICALHEIGHT = 111;

		public const int PHYSICALOFFSETX = 112;

		public const int PHYSICALOFFSETY = 113;

		public const int VERTRES = 10;

		public const int HORZRES = 8;

		public const int DM_ORIENTATION = 1;

		public const int DM_PAPERSIZE = 2;

		public const int DM_PAPERLENGTH = 4;

		public const int DM_PAPERWIDTH = 8;

		public const int DM_COPIES = 256;

		public const int DM_DEFAULTSOURCE = 512;

		public const int DM_PRINTQUALITY = 1024;

		public const int DM_COLOR = 2048;

		public const int DM_DUPLEX = 4096;

		public const int DM_YRESOLUTION = 8192;

		public const int DM_COLLATE = 32768;

		public const int DMORIENT_PORTRAIT = 1;

		public const int DMORIENT_LANDSCAPE = 2;

		public const int DMPAPER_LETTER = 1;

		public const int DMPAPER_LETTERSMALL = 2;

		public const int DMPAPER_TABLOID = 3;

		public const int DMPAPER_LEDGER = 4;

		public const int DMPAPER_LEGAL = 5;

		public const int DMPAPER_STATEMENT = 6;

		public const int DMPAPER_EXECUTIVE = 7;

		public const int DMPAPER_A3 = 8;

		public const int DMPAPER_A4 = 9;

		public const int DMPAPER_A4SMALL = 10;

		public const int DMPAPER_A5 = 11;

		public const int DMPAPER_B4 = 12;

		public const int DMPAPER_B5 = 13;

		public const int DMPAPER_FOLIO = 14;

		public const int DMPAPER_QUARTO = 15;

		public const int DMPAPER_10X14 = 16;

		public const int DMPAPER_11X17 = 17;

		public const int DMPAPER_NOTE = 18;

		public const int DMPAPER_ENV_9 = 19;

		public const int DMPAPER_ENV_10 = 20;

		public const int DMPAPER_ENV_11 = 21;

		public const int DMPAPER_ENV_12 = 22;

		public const int DMPAPER_ENV_14 = 23;

		public const int DMPAPER_CSHEET = 24;

		public const int DMPAPER_DSHEET = 25;

		public const int DMPAPER_ESHEET = 26;

		public const int DMPAPER_ENV_DL = 27;

		public const int DMPAPER_ENV_C5 = 28;

		public const int DMPAPER_ENV_C3 = 29;

		public const int DMPAPER_ENV_C4 = 30;

		public const int DMPAPER_ENV_C6 = 31;

		public const int DMPAPER_ENV_C65 = 32;

		public const int DMPAPER_ENV_B4 = 33;

		public const int DMPAPER_ENV_B5 = 34;

		public const int DMPAPER_ENV_B6 = 35;

		public const int DMPAPER_ENV_ITALY = 36;

		public const int DMPAPER_ENV_MONARCH = 37;

		public const int DMPAPER_ENV_PERSONAL = 38;

		public const int DMPAPER_FANFOLD_US = 39;

		public const int DMPAPER_FANFOLD_STD_GERMAN = 40;

		public const int DMPAPER_FANFOLD_LGL_GERMAN = 41;

		public const int DMPAPER_ISO_B4 = 42;

		public const int DMPAPER_JAPANESE_POSTCARD = 43;

		public const int DMPAPER_9X11 = 44;

		public const int DMPAPER_10X11 = 45;

		public const int DMPAPER_15X11 = 46;

		public const int DMPAPER_ENV_INVITE = 47;

		public const int DMPAPER_RESERVED_48 = 48;

		public const int DMPAPER_RESERVED_49 = 49;

		public const int DMPAPER_LETTER_EXTRA = 50;

		public const int DMPAPER_LEGAL_EXTRA = 51;

		public const int DMPAPER_TABLOID_EXTRA = 52;

		public const int DMPAPER_A4_EXTRA = 53;

		public const int DMPAPER_LETTER_TRANSVERSE = 54;

		public const int DMPAPER_A4_TRANSVERSE = 55;

		public const int DMPAPER_LETTER_EXTRA_TRANSVERSE = 56;

		public const int DMPAPER_A_PLUS = 57;

		public const int DMPAPER_B_PLUS = 58;

		public const int DMPAPER_LETTER_PLUS = 59;

		public const int DMPAPER_A4_PLUS = 60;

		public const int DMPAPER_A5_TRANSVERSE = 61;

		public const int DMPAPER_B5_TRANSVERSE = 62;

		public const int DMPAPER_A3_EXTRA = 63;

		public const int DMPAPER_A5_EXTRA = 64;

		public const int DMPAPER_B5_EXTRA = 65;

		public const int DMPAPER_A2 = 66;

		public const int DMPAPER_A3_TRANSVERSE = 67;

		public const int DMPAPER_A3_EXTRA_TRANSVERSE = 68;

		public const int DMPAPER_DBL_JAPANESE_POSTCARD = 69;

		public const int DMPAPER_A6 = 70;

		public const int DMPAPER_JENV_KAKU2 = 71;

		public const int DMPAPER_JENV_KAKU3 = 72;

		public const int DMPAPER_JENV_CHOU3 = 73;

		public const int DMPAPER_JENV_CHOU4 = 74;

		public const int DMPAPER_LETTER_ROTATED = 75;

		public const int DMPAPER_A3_ROTATED = 76;

		public const int DMPAPER_A4_ROTATED = 77;

		public const int DMPAPER_A5_ROTATED = 78;

		public const int DMPAPER_B4_JIS_ROTATED = 79;

		public const int DMPAPER_B5_JIS_ROTATED = 80;

		public const int DMPAPER_JAPANESE_POSTCARD_ROTATED = 81;

		public const int DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED = 82;

		public const int DMPAPER_A6_ROTATED = 83;

		public const int DMPAPER_JENV_KAKU2_ROTATED = 84;

		public const int DMPAPER_JENV_KAKU3_ROTATED = 85;

		public const int DMPAPER_JENV_CHOU3_ROTATED = 86;

		public const int DMPAPER_JENV_CHOU4_ROTATED = 87;

		public const int DMPAPER_B6_JIS = 88;

		public const int DMPAPER_B6_JIS_ROTATED = 89;

		public const int DMPAPER_12X11 = 90;

		public const int DMPAPER_JENV_YOU4 = 91;

		public const int DMPAPER_JENV_YOU4_ROTATED = 92;

		public const int DMPAPER_P16K = 93;

		public const int DMPAPER_P32K = 94;

		public const int DMPAPER_P32KBIG = 95;

		public const int DMPAPER_PENV_1 = 96;

		public const int DMPAPER_PENV_2 = 97;

		public const int DMPAPER_PENV_3 = 98;

		public const int DMPAPER_PENV_4 = 99;

		public const int DMPAPER_PENV_5 = 100;

		public const int DMPAPER_PENV_6 = 101;

		public const int DMPAPER_PENV_7 = 102;

		public const int DMPAPER_PENV_8 = 103;

		public const int DMPAPER_PENV_9 = 104;

		public const int DMPAPER_PENV_10 = 105;

		public const int DMPAPER_P16K_ROTATED = 106;

		public const int DMPAPER_P32K_ROTATED = 107;

		public const int DMPAPER_P32KBIG_ROTATED = 108;

		public const int DMPAPER_PENV_1_ROTATED = 109;

		public const int DMPAPER_PENV_2_ROTATED = 110;

		public const int DMPAPER_PENV_3_ROTATED = 111;

		public const int DMPAPER_PENV_4_ROTATED = 112;

		public const int DMPAPER_PENV_5_ROTATED = 113;

		public const int DMPAPER_PENV_6_ROTATED = 114;

		public const int DMPAPER_PENV_7_ROTATED = 115;

		public const int DMPAPER_PENV_8_ROTATED = 116;

		public const int DMPAPER_PENV_9_ROTATED = 117;

		public const int DMPAPER_PENV_10_ROTATED = 118;

		public const int DMPAPER_LAST = 118;

		public const int DMBIN_UPPER = 1;

		public const int DMBIN_LOWER = 2;

		public const int DMBIN_MIDDLE = 3;

		public const int DMBIN_MANUAL = 4;

		public const int DMBIN_ENVELOPE = 5;

		public const int DMBIN_ENVMANUAL = 6;

		public const int DMBIN_AUTO = 7;

		public const int DMBIN_TRACTOR = 8;

		public const int DMBIN_SMALLFMT = 9;

		public const int DMBIN_LARGEFMT = 10;

		public const int DMBIN_LARGECAPACITY = 11;

		public const int DMBIN_CASSETTE = 14;

		public const int DMBIN_FORMSOURCE = 15;

		public const int DMBIN_LAST = 15;

		public const int DMBIN_USER = 256;

		public const int DMRES_DRAFT = -1;

		public const int DMRES_LOW = -2;

		public const int DMRES_MEDIUM = -3;

		public const int DMRES_HIGH = -4;

		public const int DMCOLOR_MONOCHROME = 1;

		public const int DMCOLOR_COLOR = 2;

		public const int DMDUP_SIMPLEX = 1;

		public const int DMDUP_VERTICAL = 2;

		public const int DMDUP_HORIZONTAL = 3;

		public const int DMCOLLATE_FALSE = 0;

		public const int DMCOLLATE_TRUE = 1;

		public const int PRINTER_ENUM_LOCAL = 2;

		public const int PRINTER_ENUM_CONNECTIONS = 4;

		public const int SRCPAINT = 15597702;

		public const int SRCAND = 8913094;

		public const int SRCINVERT = 6684742;

		public const int SRCERASE = 4457256;

		public const int NOTSRCCOPY = 3342344;

		public const int NOTSRCERASE = 1114278;

		public const int MERGECOPY = 12583114;

		public const int MERGEPAINT = 12255782;

		public const int PATCOPY = 15728673;

		public const int PATPAINT = 16452105;

		public const int PATINVERT = 5898313;

		public const int DSTINVERT = 5570569;

		public const int BLACKNESS = 66;

		public const int WHITENESS = 16711778;

		public const int CAPTUREBLT = 1073741824;

		public const int SM_CXICON = 11;

		public const int SM_CYICON = 12;

		public const int DEFAULT_CHARSET = 1;

		public const int NOMIRRORBITMAP = int.MinValue;

		public const int QUERYESCSUPPORT = 8;

		public const int CHECKJPEGFORMAT = 4119;

		public const int CHECKPNGFORMAT = 4120;

		public const int ERROR_ACCESS_DENIED = 5;

		public const int ERROR_INVALID_PARAMETER = 87;

		public const int ERROR_PROC_NOT_FOUND = 127;

		[DllImport("gdi32", CharSet = CharSet.Auto, EntryPoint = "CreateCompatibleBitmap", ExactSpelling = true, SetLastError = true)]
		public static extern IntPtr IntCreateCompatibleBitmap(HandleRef hDC, int width, int height);

		public static IntPtr CreateCompatibleBitmap(HandleRef hDC, int width, int height)
		{
			return System.Internal.HandleCollector.Add(IntCreateCompatibleBitmap(hDC, width, height), CommonHandles.GDI);
		}

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int BitBlt(HandleRef hDC, int x, int y, int nWidth, int nHeight, HandleRef hSrcDC, int xSrc, int ySrc, int dwRop);

		[DllImport("gdi32")]
		public static extern int GetDIBits(HandleRef hdc, HandleRef hbm, int arg1, int arg2, IntPtr arg3, ref NativeMethods.BITMAPINFO_FLAT bmi, int arg5);

		[DllImport("gdi32")]
		public static extern uint GetPaletteEntries(HandleRef hpal, int iStartIndex, int nEntries, byte[] lppe);

		[DllImport("gdi32", CharSet = CharSet.Auto, EntryPoint = "CreateDIBSection", ExactSpelling = true, SetLastError = true)]
		public static extern IntPtr IntCreateDIBSection(HandleRef hdc, ref NativeMethods.BITMAPINFO_FLAT bmi, int iUsage, ref IntPtr ppvBits, IntPtr hSection, int dwOffset);

		public static IntPtr CreateDIBSection(HandleRef hdc, ref NativeMethods.BITMAPINFO_FLAT bmi, int iUsage, ref IntPtr ppvBits, IntPtr hSection, int dwOffset)
		{
			return System.Internal.HandleCollector.Add(IntCreateDIBSection(hdc, ref bmi, iUsage, ref ppvBits, hSection, dwOffset), CommonHandles.GDI);
		}

		[DllImport("kernel32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern IntPtr GlobalFree(HandleRef handle);

		[DllImport("gdi32", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern int StartDoc(HandleRef hDC, DOCINFO lpDocInfo);

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int StartPage(HandleRef hDC);

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int EndPage(HandleRef hDC);

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int AbortDoc(HandleRef hDC);

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int EndDoc(HandleRef hDC);

		[DllImport("comdlg32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern bool PrintDlg([In][Out] PRINTDLG lppd);

		[DllImport("comdlg32.dll", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern bool PrintDlg([In][Out] PRINTDLGX86 lppd);

		[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern int DeviceCapabilities(string pDevice, string pPort, short fwCapabilities, IntPtr pOutput, IntPtr pDevMode);

		[DllImport("winspool.drv", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
		public static extern int DocumentProperties(HandleRef hwnd, HandleRef hPrinter, string pDeviceName, IntPtr pDevModeOutput, HandleRef pDevModeInput, int fMode);

		[DllImport("winspool.drv", BestFitMapping = false, CharSet = CharSet.Auto, SetLastError = true)]
		public static extern int DocumentProperties(HandleRef hwnd, HandleRef hPrinter, string pDeviceName, IntPtr pDevModeOutput, IntPtr pDevModeInput, int fMode);

		[DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern int EnumPrinters(int flags, string name, int level, IntPtr pPrinterEnum, int cbBuf, out int pcbNeeded, out int pcReturned);

		[DllImport("kernel32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern IntPtr GlobalLock(HandleRef handle);

		[DllImport("gdi32", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern IntPtr ResetDC(HandleRef hDC, HandleRef lpDevMode);

		[DllImport("kernel32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern bool GlobalUnlock(HandleRef handle);

		[DllImport("gdi32", CharSet = CharSet.Auto, EntryPoint = "CreateRectRgn", ExactSpelling = true, SetLastError = true)]
		private static extern IntPtr IntCreateRectRgn(int x1, int y1, int x2, int y2);

		public static IntPtr CreateRectRgn(int x1, int y1, int x2, int y2)
		{
			return System.Internal.HandleCollector.Add(IntCreateRectRgn(x1, y1, x2, y2), CommonHandles.GDI);
		}

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int GetClipRgn(HandleRef hDC, HandleRef hRgn);

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int SelectClipRgn(HandleRef hDC, HandleRef hRgn);

		[DllImport("gdi32", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern int AddFontResourceEx(string lpszFilename, int fl, IntPtr pdv);

		public static int AddFontFile(string fileName)
		{
			return AddFontResourceEx(fileName, 16, IntPtr.Zero);
		}

		internal static IntPtr SaveClipRgn(IntPtr hDC)
		{
			IntPtr intPtr = CreateRectRgn(0, 0, 0, 0);
			IntPtr result = IntPtr.Zero;
			try
			{
				if (GetClipRgn(new HandleRef(null, hDC), new HandleRef(null, intPtr)) > 0)
				{
					result = intPtr;
					intPtr = IntPtr.Zero;
				}
			}
			finally
			{
				if (intPtr != IntPtr.Zero)
				{
					DeleteObject(new HandleRef(null, intPtr));
				}
			}
			return result;
		}

		internal static void RestoreClipRgn(IntPtr hDC, IntPtr hRgn)
		{
			try
			{
				SelectClipRgn(new HandleRef(null, hDC), new HandleRef(null, hRgn));
			}
			finally
			{
				if (hRgn != IntPtr.Zero)
				{
					DeleteObject(new HandleRef(null, hRgn));
				}
			}
		}

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int ExtEscape(HandleRef hDC, int nEscape, int cbInput, ref int inData, int cbOutput, out int outData);

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int ExtEscape(HandleRef hDC, int nEscape, int cbInput, byte[] inData, int cbOutput, out int outData);

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern int IntersectClipRect(HandleRef hDC, int x1, int y1, int x2, int y2);

		[DllImport("kernel32", CharSet = CharSet.Auto, EntryPoint = "GlobalAlloc", ExactSpelling = true, SetLastError = true)]
		public static extern IntPtr IntGlobalAlloc(int uFlags, UIntPtr dwBytes);

		public static IntPtr GlobalAlloc(int uFlags, uint dwBytes)
		{
			return IntGlobalAlloc(uFlags, new UIntPtr(dwBytes));
		}

		internal unsafe static void ZeroMemory(byte* ptr, ulong length)
		{
			byte* ptr2 = ptr + length;
			while (ptr != ptr2)
			{
				*(ptr++) = 0;
			}
		}

		[DllImport("gdi32", CharSet = CharSet.Auto, EntryPoint = "DeleteObject", ExactSpelling = true, SetLastError = true)]
		internal static extern int IntDeleteObject(HandleRef hObject);

		public static int DeleteObject(HandleRef hObject)
		{
			System.Internal.HandleCollector.Remove((IntPtr)hObject, CommonHandles.GDI);
			return IntDeleteObject(hObject);
		}

		[DllImport("gdi32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern IntPtr SelectObject(HandleRef hdc, HandleRef obj);

		[DllImport("user32", EntryPoint = "CreateIconFromResourceEx", SetLastError = true)]
		private unsafe static extern IntPtr IntCreateIconFromResourceEx(byte* pbIconBits, int cbIconBits, bool fIcon, int dwVersion, int csDesired, int cyDesired, int flags);

		public unsafe static IntPtr CreateIconFromResourceEx(byte* pbIconBits, int cbIconBits, bool fIcon, int dwVersion, int csDesired, int cyDesired, int flags)
		{
			return System.Internal.HandleCollector.Add(IntCreateIconFromResourceEx(pbIconBits, cbIconBits, fIcon, dwVersion, csDesired, cyDesired, flags), CommonHandles.Icon);
		}

		[DllImport("shell32.dll", BestFitMapping = false, CharSet = CharSet.Auto, EntryPoint = "ExtractAssociatedIcon")]
		public static extern IntPtr IntExtractAssociatedIcon(HandleRef hInst, StringBuilder iconPath, ref int index);

		public static IntPtr ExtractAssociatedIcon(HandleRef hInst, StringBuilder iconPath, ref int index)
		{
			return System.Internal.HandleCollector.Add(IntExtractAssociatedIcon(hInst, iconPath, ref index), CommonHandles.Icon);
		}

		[DllImport("user32", CharSet = CharSet.Auto, EntryPoint = "LoadIcon", SetLastError = true)]
		private static extern IntPtr IntLoadIcon(HandleRef hInst, IntPtr iconId);

		public static IntPtr LoadIcon(HandleRef hInst, int iconId)
		{
			return IntLoadIcon(hInst, new IntPtr(iconId));
		}

		[DllImport("user32", CharSet = CharSet.Auto, EntryPoint = "DestroyIcon", ExactSpelling = true, SetLastError = true)]
		private static extern bool IntDestroyIcon(HandleRef hIcon);

		public static bool DestroyIcon(HandleRef hIcon)
		{
			System.Internal.HandleCollector.Remove((IntPtr)hIcon, CommonHandles.Icon);
			return IntDestroyIcon(hIcon);
		}

		[DllImport("user32", CharSet = CharSet.Auto, EntryPoint = "CopyImage", ExactSpelling = true, SetLastError = true)]
		private static extern IntPtr IntCopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags);

		public static IntPtr CopyImage(HandleRef hImage, int uType, int cxDesired, int cyDesired, int fuFlags)
		{
			return System.Internal.HandleCollector.Add(type: (uType != 1) ? CommonHandles.GDI : CommonHandles.Icon, handle: IntCopyImage(hImage, uType, cxDesired, cyDesired, fuFlags));
		}

		[DllImport("gdi32", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern int GetObject(HandleRef hObject, int nSize, [In][Out] BITMAP bm);

		[DllImport("gdi32", CharSet = CharSet.Auto, SetLastError = true)]
		public static extern int GetObject(HandleRef hObject, int nSize, [In][Out] LOGFONT lf);

		public static int GetObject(HandleRef hObject, LOGFONT lp)
		{
			return GetObject(hObject, Marshal.SizeOf(typeof(LOGFONT)), lp);
		}

		[DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern bool GetIconInfo(HandleRef hIcon, [In][Out] ICONINFO info);

		[DllImport("user32", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
		public static extern bool DrawIconEx(HandleRef hDC, int x, int y, HandleRef hIcon, int width, int height, int iStepIfAniCursor, HandleRef hBrushFlickerFree, int diFlags);

		[DllImport("oleaut32.dll", PreserveSig = false)]
		public static extern IPicture OleCreatePictureIndirect(PICTDESC pictdesc, [In] ref Guid refiid, bool fOwn);
	}
	public interface IDeviceContext : IDisposable
	{
		IntPtr GetHdc();

		void ReleaseHdc();
	}
	internal class NativeMethods
	{
		internal struct BITMAPINFO_FLAT
		{
			public int bmiHeader_biSize;

			public int bmiHeader_biWidth;

			public int bmiHeader_biHeight;

			public short bmiHeader_biPlanes;

			public short bmiHeader_biBitCount;

			public int bmiHeader_biCompression;

			public int bmiHeader_biSizeImage;

			public int bmiHeader_biXPelsPerMeter;

			public int bmiHeader_biYPelsPerMeter;

			public int bmiHeader_biClrUsed;

			public int bmiHeader_biClrImportant;

			[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1024)]
			public byte[] bmiColors;
		}

		[StructLayout(LayoutKind.Sequential)]
		internal class BITMAPINFOHEADER
		{
			public int biSize = 40;

			public int biWidth;

			public int biHeight;

			public short biPlanes;

			public short biBitCount;

			public int biCompression;

			public int biSizeImage;

			public int biXPelsPerMeter;

			public int biYPelsPerMeter;

			public int biClrUsed;

			public int biClrImportant;
		}

		internal struct PALETTEENTRY
		{
			public byte peRed;

			public byte peGreen;

			public byte peBlue;

			public byte peFlags;
		}

		internal struct RGBQUAD
		{
			public byte rgbBlue;

			public byte rgbGreen;

			public byte rgbRed;

			public byte rgbReserved;
		}

		[StructLayout(LayoutKind.Sequential)]
		internal class NONCLIENTMETRICS
		{
			public int cbSize = Marshal.SizeOf(typeof(NONCLIENTMETRICS));

			public int iBorderWidth;

			public int iScrollWidth;

			public int iScrollHeight;

			public int iCaptionWidth;

			public int iCaptionHeight;

			[MarshalAs(UnmanagedType.Struct)]
			public SafeNativeMethods.LOGFONT lfCaptionFont;

			public int iSmCaptionWidth;

			public int iSmCaptionHeight;

			[MarshalAs(UnmanagedType.Struct)]
			public SafeNativeMethods.LOGFONT lfSmCaptionFont;

			public int iMenuWidth;

			public int iMenuHeight;

			[MarshalAs(UnmanagedType.Struct)]
			public SafeNativeMethods.LOGFONT lfMenuFont;

			[MarshalAs(UnmanagedType.Struct)]
			public SafeNativeMethods.LOGFONT lfStatusFont;

			[MarshalAs(UnmanagedType.Struct)]
			public SafeNativeMethods.LOGFONT lfMessageFont;
		}

		internal static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);

		public const int MAX_PATH = 260;

		internal const int SM_REMOTESESSION = 4096;

		internal const int OBJ_DC = 3;

		internal const int OBJ_METADC = 4;

		internal const int OBJ_MEMDC = 10;

		internal const int OBJ_ENHMETADC = 12;

		internal const int DIB_RGB_COLORS = 0;

		internal const int BI_BITFIELDS = 3;

		internal const int BI_RGB = 0;

		internal const int BITMAPINFO_MAX_COLORSIZE = 256;

		internal const int SPI_GETICONTITLELOGFONT = 31;

		internal const int SPI_GETNONCLIENTMETRICS = 41;

		internal const int DEFAULT_GUI_FONT = 17;
	}
	public class PointConverter : TypeConverter
	{
		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			if (sourceType == typeof(string))
			{
				return true;
			}
			return base.CanConvertFrom(context, sourceType);
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			if (destinationType == typeof(InstanceDescriptor))
			{
				return true;
			}
			return base.CanConvertTo(context, destinationType);
		}

		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			if (value is string text)
			{
				string text2 = text.Trim();
				if (text2.Length == 0)
				{
					return null;
				}
				if (culture == null)
				{
					culture = CultureInfo.CurrentCulture;
				}
				char c = culture.TextInfo.ListSeparator[0];
				string[] array = text2.Split(new char[1] { c });
				int[] array2 = new int[array.Length];
				TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
				for (int i = 0; i < array2.Length; i++)
				{
					array2[i] = (int)converter.ConvertFromString(context, culture, array[i]);
				}
				if (array2.Length == 2)
				{
					return new Point(array2[0], array2[1]);
				}
				throw new ArgumentException(SR.Format("Text \"{0}\" cannot be parsed. The expected text format is \"{1}\".", text2, "x, y"));
			}
			return base.ConvertFrom(context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (destinationType == null)
			{
				throw new ArgumentNullException("destinationType");
			}
			if (value is Point)
			{
				if (destinationType == typeof(string))
				{
					Point point = (Point)value;
					if (culture == null)
					{
						culture = CultureInfo.CurrentCulture;
					}
					string separator = culture.TextInfo.ListSeparator + " ";
					TypeConverter converter = TypeDescriptor.GetConverter(typeof(int));
					string[] array = new string[2];
					int num = 0;
					array[num++] = converter.ConvertToString(context, culture, point.X);
					array[num++] = converter.ConvertToString(context, culture, point.Y);
					return string.Join(separator, array);
				}
				if (destinationType == typeof(InstanceDescriptor))
				{
					Point point2 = (Point)value;
					ConstructorInfo constructor = typeof(Point).GetConstructor(new Type[2]
					{
						typeof(int),
						typeof(int)
					});
					if (constructor != null)
					{
						return new InstanceDescriptor(constructor, new object[2] { point2.X, point2.Y });
					}
				}
			}
			return base.ConvertTo(context, culture, value, destinationType);
		}

		public

BepInEx/core/System.EnterpriseServices.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Diagnostics;
using System.EnterpriseServices;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Transactions;
using Unity;

[assembly: ComVisible(true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.EnterpriseServices.dll")]
[assembly: AssemblyDescription("System.EnterpriseServices.dll")]
[assembly: AssemblyDefaultAlias("System.EnterpriseServices.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: ApplicationID("1e246775-2281-484f-8ad4-044c15b86eb7")]
[assembly: ApplicationName(".NET Utilities")]
[assembly: Guid("4fb2d46f-efc8-4643-bcd0-6e5bfa6a174c")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: AssemblyVersion("4.0.0.0")]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
namespace System
{
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoTODOAttribute : Attribute
	{
		private string comment;

		public string Comment => comment;

		public MonoTODOAttribute()
		{
		}

		public MonoTODOAttribute(string comment)
		{
			this.comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoDocumentationNoteAttribute : MonoTODOAttribute
	{
		public MonoDocumentationNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoExtensionAttribute : MonoTODOAttribute
	{
		public MonoExtensionAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoInternalNoteAttribute : MonoTODOAttribute
	{
		public MonoInternalNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoLimitationAttribute : MonoTODOAttribute
	{
		public MonoLimitationAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoNotSupportedAttribute : MonoTODOAttribute
	{
		public MonoNotSupportedAttribute(string comment)
			: base(comment)
		{
		}
	}
}
namespace System.EnterpriseServices
{
	[Serializable]
	public enum AccessChecksLevelOption
	{
		Application,
		ApplicationComponent
	}
	[Serializable]
	public enum ActivationOption
	{
		Library,
		Server
	}
	[ComVisible(false)]
	public sealed class Activity
	{
		[MonoTODO]
		public Activity(ServiceConfig cfg)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void AsynchronousCall(IServiceCall serviceCall)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void BindToCurrentThread()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void SynchronousCall(IServiceCall serviceCall)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void UnbindFromThread()
		{
			throw new NotImplementedException();
		}
	}
	[ComVisible(false)]
	[AttributeUsage(AttributeTargets.Assembly)]
	public sealed class ApplicationAccessControlAttribute : Attribute, IConfigurationAttribute
	{
		private AccessChecksLevelOption accessChecksLevel;

		private AuthenticationOption authentication;

		private ImpersonationLevelOption impersonation;

		private bool val;

		public AccessChecksLevelOption AccessChecksLevel
		{
			get
			{
				return accessChecksLevel;
			}
			set
			{
				accessChecksLevel = value;
			}
		}

		public AuthenticationOption Authentication
		{
			get
			{
				return authentication;
			}
			set
			{
				authentication = value;
			}
		}

		public ImpersonationLevelOption ImpersonationLevel
		{
			get
			{
				return impersonation;
			}
			set
			{
				impersonation = value;
			}
		}

		public bool Value
		{
			get
			{
				return val;
			}
			set
			{
				val = value;
			}
		}

		public ApplicationAccessControlAttribute()
		{
			val = false;
		}

		public ApplicationAccessControlAttribute(bool val)
		{
			this.val = val;
		}

		bool IConfigurationAttribute.AfterSaveChanges(Hashtable info)
		{
			return false;
		}

		[MonoTODO]
		bool IConfigurationAttribute.Apply(Hashtable cache)
		{
			throw new NotImplementedException();
		}

		bool IConfigurationAttribute.IsValidTarget(string s)
		{
			return s == "Application";
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	[ComVisible(false)]
	public sealed class ApplicationActivationAttribute : Attribute, IConfigurationAttribute
	{
		private ActivationOption opt;

		private string soapMailbox;

		private string soapVRoot;

		public string SoapMailbox
		{
			get
			{
				return soapMailbox;
			}
			set
			{
				soapMailbox = value;
			}
		}

		public string SoapVRoot
		{
			get
			{
				return soapVRoot;
			}
			set
			{
				soapVRoot = value;
			}
		}

		public ActivationOption Value => opt;

		public ApplicationActivationAttribute(ActivationOption opt)
		{
			this.opt = opt;
		}

		[MonoTODO]
		bool IConfigurationAttribute.AfterSaveChanges(Hashtable info)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		bool IConfigurationAttribute.Apply(Hashtable cache)
		{
			throw new NotImplementedException();
		}

		bool IConfigurationAttribute.IsValidTarget(string s)
		{
			return s == "Application";
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	[ComVisible(false)]
	public sealed class ApplicationIDAttribute : Attribute, IConfigurationAttribute
	{
		private Guid guid;

		public Guid Value => guid;

		public ApplicationIDAttribute(string guid)
		{
			this.guid = new Guid(guid);
		}

		bool IConfigurationAttribute.AfterSaveChanges(Hashtable info)
		{
			return false;
		}

		bool IConfigurationAttribute.Apply(Hashtable cache)
		{
			return false;
		}

		bool IConfigurationAttribute.IsValidTarget(string s)
		{
			return s == "Application";
		}
	}
	[AttributeUsage(AttributeTargets.Assembly)]
	[ComVisible(false)]
	public sealed class ApplicationNameAttribute : Attribute, IConfigurationAttribute
	{
		private string name;

		public string Value => name;

		public ApplicationNameAttribute(string name)
		{
			this.name = name;
		}

		bool IConfigurationAttribute.AfterSaveChanges(Hashtable info)
		{
			return false;
		}

		[MonoTODO]
		bool IConfigurationAttribute.Apply(Hashtable cache)
		{
			throw new NotImplementedException();
		}

		bool IConfigurationAttribute.IsValidTarget(string s)
		{
			return s == "Application";
		}
	}
	[ComVisible(false)]
	[AttributeUsage(AttributeTargets.Assembly)]
	public sealed class ApplicationQueuingAttribute : Attribute
	{
		private bool enabled;

		private int maxListenerThreads;

		private bool queueListenerEnabled;

		public bool Enabled
		{
			get
			{
				return enabled;
			}
			set
			{
				enabled = value;
			}
		}

		public int MaxListenerThreads
		{
			get
			{
				return maxListenerThreads;
			}
			set
			{
				maxListenerThreads = value;
			}
		}

		public bool QueueListenerEnabled
		{
			get
			{
				return queueListenerEnabled;
			}
			set
			{
				queueListenerEnabled = value;
			}
		}

		public ApplicationQueuingAttribute()
		{
			enabled = true;
			queueListenerEnabled = false;
			maxListenerThreads = 0;
		}
	}
	[Serializable]
	public enum AuthenticationOption
	{
		Call = 3,
		Connect = 2,
		Default = 0,
		Integrity = 5,
		None = 1,
		Packet = 4,
		Privacy = 6
	}
	[AttributeUsage(AttributeTargets.Method)]
	[ComVisible(false)]
	public sealed class AutoCompleteAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public AutoCompleteAttribute()
		{
			val = true;
		}

		public AutoCompleteAttribute(bool val)
		{
			this.val = val;
		}
	}
	[ComVisible(false)]
	public struct BOID
	{
		[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
		public byte[] rgb;
	}
	public sealed class BYOT
	{
		private BYOT()
		{
		}

		[MonoTODO]
		public static object CreateWithTipTransaction(string url, Type t)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static object CreateWithTransaction(object transaction, Type t)
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	[ComVisible(false)]
	public enum BindingOption
	{
		NoBinding,
		BindingToPoolThread
	}
	[ComVisible(false)]
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class COMTIIntrinsicsAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public COMTIIntrinsicsAttribute()
		{
			val = false;
		}

		public COMTIIntrinsicsAttribute(bool val)
		{
			this.val = val;
		}
	}
	[ComVisible(false)]
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class ComponentAccessControlAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public ComponentAccessControlAttribute()
		{
			val = false;
		}

		public ComponentAccessControlAttribute(bool val)
		{
			this.val = val;
		}
	}
	[ComVisible(false)]
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class ConstructionEnabledAttribute : Attribute
	{
		private string def;

		private bool enabled;

		public string Default
		{
			get
			{
				return def;
			}
			set
			{
				def = value;
			}
		}

		public bool Enabled
		{
			get
			{
				return enabled;
			}
			set
			{
				enabled = value;
			}
		}

		public ConstructionEnabledAttribute()
		{
			def = string.Empty;
			enabled = true;
		}

		public ConstructionEnabledAttribute(bool val)
		{
			def = string.Empty;
			enabled = val;
		}
	}
	public sealed class ContextUtil
	{
		private static bool deactivateOnReturn;

		private static TransactionVote myTransactionVote;

		public static Guid ActivityId
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static Guid ApplicationId
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static Guid ApplicationInstanceId
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static Guid ContextId
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static bool DeactivateOnReturn
		{
			get
			{
				return deactivateOnReturn;
			}
			set
			{
				deactivateOnReturn = value;
			}
		}

		public static bool IsInTransaction
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static bool IsSecurityEnabled
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public static TransactionVote MyTransactionVote
		{
			get
			{
				return myTransactionVote;
			}
			set
			{
				myTransactionVote = value;
			}
		}

		public static Guid PartitionId
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static object Transaction
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static Transaction SystemTransaction
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static Guid TransactionId
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		internal ContextUtil()
		{
		}

		[MonoTODO]
		public static void DisableCommit()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static void EnableCommit()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static object GetNamedProperty(string name)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static bool IsCallerInRole(string role)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static bool IsDefaultContext()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static void SetAbort()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static void SetComplete()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static void SetNamedProperty(string name, object value)
		{
			throw new NotImplementedException();
		}
	}
	[ComVisible(false)]
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Interface)]
	public sealed class DescriptionAttribute : Attribute
	{
		public DescriptionAttribute(string desc)
		{
		}
	}
	[ComVisible(false)]
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class EventClassAttribute : Attribute
	{
		private bool allowInProcSubscribers;

		private bool fireInParallel;

		private string publisherFilter;

		public bool AllowInprocSubscribers
		{
			get
			{
				return allowInProcSubscribers;
			}
			set
			{
				allowInProcSubscribers = value;
			}
		}

		public bool FireInParallel
		{
			get
			{
				return fireInParallel;
			}
			set
			{
				fireInParallel = value;
			}
		}

		public string PublisherFilter
		{
			get
			{
				return publisherFilter;
			}
			set
			{
				publisherFilter = value;
			}
		}

		public EventClassAttribute()
		{
			allowInProcSubscribers = true;
			fireInParallel = false;
			publisherFilter = null;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class EventTrackingEnabledAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public EventTrackingEnabledAttribute()
		{
			val = true;
		}

		public EventTrackingEnabledAttribute(bool val)
		{
			this.val = val;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class ExceptionClassAttribute : Attribute
	{
		private string name;

		public string Value => name;

		public ExceptionClassAttribute(string name)
		{
			this.name = name;
		}
	}
	[ComImport]
	[Guid("FE6777FB-A674-4177-8F32-6D707E113484")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IAsyncErrorNotify
	{
		void OnError(int hresult);
	}
	internal interface IConfigurationAttribute
	{
		bool AfterSaveChanges(Hashtable info);

		bool Apply(Hashtable info);

		bool IsValidTarget(string s);
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class IISIntrinsicsAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public IISIntrinsicsAttribute()
		{
			val = true;
		}

		public IISIntrinsicsAttribute(bool val)
		{
			this.val = val;
		}
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("51372AFD-CAE7-11CF-BE81-00AA00A2FA25")]
	public interface IPlaybackControl
	{
		void FinalClientRetry();

		void FinalServerRetry();
	}
	[ComImport]
	[Guid("72380d55-8d2b-43a3-8513-2b6ef31434e9")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IProcessInitControl
	{
		void ResetInitializerTimeout(int dwSecondsRemaining);
	}
	[ComImport]
	[Guid("1113f52d-dc7f-4943-aed6-88d04027e32a")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IProcessInitializer
	{
		void Shutdown();

		void Startup([In][MarshalAs(UnmanagedType.IUnknown)] object punkProcessControl);
	}
	[Guid("55e3ea25-55cb-4650-8887-18e8d30bb4bc")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IRegistrationHelper
	{
		void InstallAssembly([In][MarshalAs(UnmanagedType.BStr)] string assembly, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string application, [In][Out][MarshalAs(UnmanagedType.BStr)] ref string tlb, [In] InstallationFlags installFlags);

		void UninstallAssembly([In][MarshalAs(UnmanagedType.BStr)] string assembly, [In][MarshalAs(UnmanagedType.BStr)] string application);
	}
	[Guid("6619a740-8154-43be-a186-0319578e02db")]
	public interface IRemoteDispatch
	{
		[AutoComplete]
		string RemoteDispatchAutoDone(string s);

		[AutoComplete(false)]
		string RemoteDispatchNotAutoDone(string s);
	}
	internal interface ISecurityCallContext
	{
		int Count { get; }

		void GetEnumerator(ref IEnumerator enumerator);

		object GetItem(string user);

		bool IsCallerInRole(string role);

		bool IsSecurityEnabled();

		bool IsUserInRole(ref object user, string role);
	}
	internal interface ISecurityCallersColl
	{
		int Count { get; }

		void GetEnumerator(out IEnumerator enumerator);

		ISecurityIdentityColl GetItem(int idx);
	}
	internal interface ISecurityIdentityColl
	{
		int Count { get; }

		void GetEnumerator(out IEnumerator enumerator);

		SecurityIdentity GetItem(int idx);
	}
	[ComImport]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("BD3E2E12-42DD-40f4-A09A-95A50C58304B")]
	public interface IServiceCall
	{
		void OnCall();
	}
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	[Guid("8165B19E-8D3A-4d0b-80C8-97DE310DB583")]
	public interface IServicedComponentInfo
	{
		void GetComponentInfo(ref int infoMask, out string[] infoArray);
	}
	internal interface ISharedProperty
	{
		object Value { get; set; }
	}
	internal interface ISharedPropertyGroup
	{
		ISharedProperty CreateProperty(string name, out bool fExists);

		ISharedProperty CreatePropertyByPosition(int position, out bool fExists);

		ISharedProperty Property(string name);

		ISharedProperty PropertyByPosition(int position);
	}
	[ComImport]
	[Guid("0FB15084-AF41-11CE-BD2B-204C4F4F5020")]
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface ITransaction
	{
		void Abort(ref BOID pboidReason, int fRetaining, int fAsync);

		void Commit(int fRetaining, int grfTC, int grfRM);

		void GetTransactionInfo(out XACTTRANSINFO pinfo);
	}
	[Serializable]
	public enum ImpersonationLevelOption
	{
		Anonymous = 1,
		Default = 0,
		Delegate = 4,
		Identify = 2,
		Impersonate = 3
	}
	[Serializable]
	[ComVisible(false)]
	public enum InheritanceOption
	{
		Inherit,
		Ignore
	}
	[Serializable]
	[Flags]
	public enum InstallationFlags
	{
		Configure = 0x400,
		ConfigureComponentsOnly = 0x10,
		CreateTargetApplication = 2,
		Default = 0,
		ExpectExistingTypeLib = 1,
		FindOrCreateTargetApplication = 4,
		Install = 0x200,
		ReconfigureExistingApplication = 8,
		Register = 0x100,
		ReportWarningsToConsole = 0x20
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true)]
	[ComVisible(false)]
	public sealed class InterfaceQueuingAttribute : Attribute
	{
		private bool enabled;

		private string interfaceName;

		public bool Enabled
		{
			get
			{
				return enabled;
			}
			set
			{
				enabled = value;
			}
		}

		public string Interface
		{
			get
			{
				return interfaceName;
			}
			set
			{
				interfaceName = value;
			}
		}

		public InterfaceQueuingAttribute()
			: this(enabled: true)
		{
		}

		public InterfaceQueuingAttribute(bool enabled)
		{
			this.enabled = enabled;
			interfaceName = null;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class JustInTimeActivationAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public JustInTimeActivationAttribute()
			: this(val: true)
		{
		}

		public JustInTimeActivationAttribute(bool val)
		{
			this.val = val;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class LoadBalancingSupportedAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public LoadBalancingSupportedAttribute()
			: this(val: true)
		{
		}

		public LoadBalancingSupportedAttribute(bool val)
		{
			this.val = val;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class MustRunInClientContextAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public MustRunInClientContextAttribute()
			: this(val: true)
		{
		}

		public MustRunInClientContextAttribute(bool val)
		{
			this.val = val;
		}
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class ObjectPoolingAttribute : Attribute, IConfigurationAttribute
	{
		private int creationTimeout;

		private bool enabled;

		private int minPoolSize;

		private int maxPoolSize;

		public int CreationTimeout
		{
			get
			{
				return creationTimeout;
			}
			set
			{
				creationTimeout = value;
			}
		}

		public bool Enabled
		{
			get
			{
				return enabled;
			}
			set
			{
				enabled = value;
			}
		}

		public int MaxPoolSize
		{
			get
			{
				return maxPoolSize;
			}
			set
			{
				maxPoolSize = value;
			}
		}

		public int MinPoolSize
		{
			get
			{
				return minPoolSize;
			}
			set
			{
				minPoolSize = value;
			}
		}

		public ObjectPoolingAttribute()
			: this(enable: true)
		{
		}

		public ObjectPoolingAttribute(bool enable)
		{
			enabled = enable;
		}

		public ObjectPoolingAttribute(int minPoolSize, int maxPoolSize)
			: this(enable: true, minPoolSize, maxPoolSize)
		{
		}

		public ObjectPoolingAttribute(bool enable, int minPoolSize, int maxPoolSize)
		{
			enabled = enable;
			this.minPoolSize = minPoolSize;
			this.maxPoolSize = maxPoolSize;
		}

		[MonoTODO]
		public bool AfterSaveChanges(Hashtable info)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public bool Apply(Hashtable info)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public bool IsValidTarget(string s)
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	[ComVisible(false)]
	public enum PartitionOption
	{
		Ignore,
		Inherit,
		New
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class PrivateComponentAttribute : Attribute
	{
	}
	[Serializable]
	[ComVisible(false)]
	public enum PropertyLockMode
	{
		Method = 1,
		SetGet = 0
	}
	[Serializable]
	[ComVisible(false)]
	public enum PropertyReleaseMode
	{
		Process = 1,
		Standard = 0
	}
	[Serializable]
	[Guid("36dcda30-dc3b-4d93-be42-90b2d74c64e7")]
	public class RegistrationConfig
	{
		[MonoTODO]
		public string Application
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string ApplicationRootDirectory
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string AssemblyFile
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public InstallationFlags InstallationFlags
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string Partition
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string TypeLibrary
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public RegistrationConfig()
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	public sealed class RegistrationErrorInfo
	{
		private int errorCode;

		private string errorString;

		private string majorRef;

		private string minorRef;

		private string name;

		public int ErrorCode => errorCode;

		public string ErrorString => errorString;

		public string MajorRef => majorRef;

		public string MinorRef => minorRef;

		public string Name => name;

		[MonoTODO]
		internal RegistrationErrorInfo(string name, string majorRef, string minorRef, int errorCode)
		{
			this.name = name;
			this.majorRef = majorRef;
			this.minorRef = minorRef;
			this.errorCode = errorCode;
		}

		internal RegistrationErrorInfo()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	[Serializable]
	public sealed class RegistrationException : SystemException
	{
		private RegistrationErrorInfo[] errorInfo;

		public RegistrationErrorInfo[] ErrorInfo => errorInfo;

		[MonoTODO]
		public RegistrationException(string msg)
			: base(msg)
		{
		}

		public RegistrationException()
			: this("Registration error")
		{
		}

		public RegistrationException(string msg, Exception inner)
			: base(msg, inner)
		{
		}

		[MonoTODO]
		public override void GetObjectData(SerializationInfo info, StreamingContext ctx)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("89a86e7b-c229-4008-9baa-2f5c8411d7e0")]
	public sealed class RegistrationHelper : MarshalByRefObject, IRegistrationHelper
	{
		public void InstallAssembly(string assembly, ref string application, ref string tlb, InstallationFlags installFlags)
		{
			application = string.Empty;
			tlb = string.Empty;
			InstallAssembly(assembly, ref application, null, ref tlb, installFlags);
		}

		[MonoTODO]
		public void InstallAssembly(string assembly, ref string application, string partition, ref string tlb, InstallationFlags installFlags)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void InstallAssemblyFromConfig([MarshalAs(UnmanagedType.IUnknown)] ref RegistrationConfig regConfig)
		{
			throw new NotImplementedException();
		}

		public void UninstallAssembly(string assembly, string application)
		{
			UninstallAssembly(assembly, application, null);
		}

		[MonoTODO]
		public void UninstallAssembly(string assembly, string application, string partition)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void UninstallAssemblyFromConfig([MarshalAs(UnmanagedType.IUnknown)] ref RegistrationConfig regConfig)
		{
			throw new NotImplementedException();
		}
	}
	[Transaction(TransactionOption.RequiresNew)]
	[Guid("C89AC250-E18A-4FC7-ABD5-B8897B6A78A5")]
	public sealed class RegistrationHelperTx : ServicedComponent
	{
		[MonoTODO]
		public RegistrationHelperTx()
		{
		}

		[MonoTODO]
		protected internal override void Activate()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		protected internal override void Deactivate()
		{
			throw new NotImplementedException();
		}

		public void InstallAssembly(string assembly, ref string application, ref string tlb, InstallationFlags installFlags, object sync)
		{
			InstallAssembly(assembly, ref application, null, ref tlb, installFlags, sync);
		}

		[MonoTODO]
		public void InstallAssembly(string assembly, ref string application, string partition, ref string tlb, InstallationFlags installFlags, object sync)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void InstallAssemblyFromConfig([MarshalAs(UnmanagedType.IUnknown)] ref RegistrationConfig regConfig, object sync)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public bool IsInTransaction()
		{
			throw new NotImplementedException();
		}

		public void UninstallAssembly(string assembly, string application, object sync)
		{
			UninstallAssembly(assembly, application, null, sync);
		}

		[MonoTODO]
		public void UninstallAssembly(string assembly, string application, string partition, object sync)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void UninstallAssemblyFromConfig([MarshalAs(UnmanagedType.IUnknown)] ref RegistrationConfig regConfig, object sync)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class ResourcePool
	{
		public delegate void TransactionEndDelegate(object resource);

		[MonoTODO]
		public ResourcePool(TransactionEndDelegate cb)
		{
		}

		[MonoTODO]
		public object GetResource()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public bool PutResource(object resource)
		{
			throw new NotImplementedException();
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
	[ComVisible(false)]
	public sealed class SecureMethodAttribute : Attribute
	{
	}
	public sealed class SecurityCallContext
	{
		public SecurityCallers Callers
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public static SecurityCallContext CurrentCall
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public SecurityIdentity DirectCaller
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public bool IsSecurityEnabled
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public int MinAuthenticationLevel
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public int NumCallers
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public SecurityIdentity OriginalCaller
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		internal SecurityCallContext()
		{
		}

		internal SecurityCallContext(ISecurityCallContext context)
		{
		}

		[MonoTODO]
		public bool IsCallerInRole(string role)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public bool IsUserInRole(string user, string role)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class SecurityCallers : IEnumerable
	{
		public int Count
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public SecurityIdentity this[int idx]
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		internal SecurityCallers()
		{
		}

		internal SecurityCallers(ISecurityCallersColl collection)
		{
		}

		[MonoTODO]
		public IEnumerator GetEnumerator()
		{
			throw new NotImplementedException();
		}
	}
	public sealed class SecurityIdentity
	{
		public string AccountName
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public AuthenticationOption AuthenticationLevel
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public int AuthenticationService
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public ImpersonationLevelOption ImpersonationLevel
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		internal SecurityIdentity()
		{
		}

		[MonoTODO]
		internal SecurityIdentity(ISecurityIdentityColl collection)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Interface, AllowMultiple = true)]
	[ComVisible(false)]
	public sealed class SecurityRoleAttribute : Attribute
	{
		private string description;

		private bool everyone;

		private string role;

		public string Description
		{
			get
			{
				return description;
			}
			set
			{
				description = value;
			}
		}

		public string Role
		{
			get
			{
				return role;
			}
			set
			{
				role = value;
			}
		}

		public bool SetEveryoneAccess
		{
			get
			{
				return everyone;
			}
			set
			{
				everyone = value;
			}
		}

		public SecurityRoleAttribute(string role)
			: this(role, everyone: false)
		{
		}

		public SecurityRoleAttribute(string role, bool everyone)
		{
			description = string.Empty;
			this.everyone = everyone;
			this.role = role;
		}
	}
	[MonoTODO]
	[ComVisible(false)]
	public sealed class ServiceConfig
	{
		[MonoTODO]
		public BindingOption Binding
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public Transaction BringYourOwnSystemTransaction
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public ITransaction BringYourOwnTransaction
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public bool COMTIIntrinsicsEnabled
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public bool IISIntrinsicsEnabled
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public InheritanceOption Inheritance
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public TransactionIsolationLevel IsolationLevel
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public Guid PartitionId
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public PartitionOption PartitionOption
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string SxsDirectory
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string SxsName
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public SxsOption SxsOption
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public SynchronizationOption Synchronization
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public ThreadPoolOption ThreadPool
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string TipUrl
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string TrackingAppName
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string TrackingComponentName
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public bool TrackingEnabled
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public TransactionOption Transaction
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string TransactionDescription
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public int TransactionTimeout
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public ServiceConfig()
		{
			throw new NotImplementedException();
		}
	}
	[ComVisible(false)]
	public sealed class ServiceDomain
	{
		private ServiceDomain()
		{
		}

		[MonoTODO]
		public static void Enter(ServiceConfig cfg)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static TransactionStatus Leave()
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	public abstract class ServicedComponent : ContextBoundObject, IDisposable, IRemoteDispatch, IServicedComponentInfo
	{
		public ServicedComponent()
		{
		}

		[MonoTODO]
		protected internal virtual void Activate()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		protected internal virtual bool CanBePooled()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		protected internal virtual void Construct(string s)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		protected internal virtual void Deactivate()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void Dispose()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		protected virtual void Dispose(bool disposing)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static void DisposeObject(ServicedComponent sc)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		string IRemoteDispatch.RemoteDispatchAutoDone(string s)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		string IRemoteDispatch.RemoteDispatchNotAutoDone(string s)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		void IServicedComponentInfo.GetComponentInfo(ref int infoMask, out string[] infoArray)
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	[ComVisible(false)]
	public sealed class ServicedComponentException : SystemException
	{
		public ServicedComponentException()
		{
		}

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

		public ServicedComponentException(string message, Exception innerException)
			: base(message, innerException)
		{
		}
	}
	[ComVisible(false)]
	public sealed class SharedProperty
	{
		private ISharedProperty property;

		public object Value
		{
			get
			{
				return property.Value;
			}
			set
			{
				property.Value = value;
			}
		}

		internal SharedProperty(ISharedProperty property)
		{
			this.property = property;
		}

		internal SharedProperty()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	[ComVisible(false)]
	public sealed class SharedPropertyGroup
	{
		private ISharedPropertyGroup propertyGroup;

		internal SharedPropertyGroup(ISharedPropertyGroup propertyGroup)
		{
			this.propertyGroup = propertyGroup;
		}

		public SharedProperty CreateProperty(string name, out bool fExists)
		{
			return new SharedProperty(propertyGroup.CreateProperty(name, out fExists));
		}

		public SharedProperty CreatePropertyByPosition(int position, out bool fExists)
		{
			return new SharedProperty(propertyGroup.CreatePropertyByPosition(position, out fExists));
		}

		public SharedProperty Property(string name)
		{
			return new SharedProperty(propertyGroup.Property(name));
		}

		public SharedProperty PropertyByPosition(int position)
		{
			return new SharedProperty(propertyGroup.PropertyByPosition(position));
		}

		internal SharedPropertyGroup()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	[ComVisible(false)]
	public sealed class SharedPropertyGroupManager : IEnumerable
	{
		[MonoTODO]
		public SharedPropertyGroup CreatePropertyGroup(string name, ref PropertyLockMode dwIsoMode, ref PropertyReleaseMode dwRelMode, out bool fExist)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public IEnumerator GetEnumerator()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public SharedPropertyGroup Group(string name)
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	[ComVisible(false)]
	public enum SxsOption
	{
		Ignore,
		Inherit,
		New
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class SynchronizationAttribute : Attribute
	{
		private SynchronizationOption val;

		public SynchronizationOption Value => val;

		public SynchronizationAttribute()
			: this(SynchronizationOption.Required)
		{
		}

		public SynchronizationAttribute(SynchronizationOption val)
		{
			this.val = val;
		}
	}
	[Serializable]
	public enum SynchronizationOption
	{
		Disabled = 0,
		NotSupported = 1,
		Required = 3,
		RequiresNew = 4,
		Supported = 2
	}
	[Serializable]
	[ComVisible(false)]
	public enum ThreadPoolOption
	{
		None,
		Inherit,
		STA,
		MTA
	}
	[AttributeUsage(AttributeTargets.Class)]
	[ComVisible(false)]
	public sealed class TransactionAttribute : Attribute
	{
		private TransactionIsolationLevel isolation;

		private int timeout;

		private TransactionOption val;

		public TransactionIsolationLevel Isolation
		{
			get
			{
				return isolation;
			}
			set
			{
				isolation = value;
			}
		}

		public int Timeout
		{
			get
			{
				return timeout;
			}
			set
			{
				timeout = value;
			}
		}

		public TransactionOption Value => val;

		public TransactionAttribute()
			: this(TransactionOption.Required)
		{
		}

		public TransactionAttribute(TransactionOption val)
		{
			isolation = TransactionIsolationLevel.Serializable;
			timeout = -1;
			this.val = val;
		}
	}
	[Serializable]
	public enum TransactionIsolationLevel
	{
		Any = 0,
		ReadCommitted = 2,
		ReadUncommitted = 1,
		RepeatableRead = 3,
		Serializable = 4
	}
	[Serializable]
	public enum TransactionOption
	{
		Disabled,
		NotSupported,
		Supported,
		Required,
		RequiresNew
	}
	[Serializable]
	[ComVisible(false)]
	public enum TransactionStatus
	{
		Commited,
		LocallyOk,
		NoTransaction,
		Aborting,
		Aborted
	}
	[Serializable]
	[ComVisible(false)]
	public enum TransactionVote
	{
		Abort = 1,
		Commit = 0
	}
	[ComVisible(false)]
	public struct XACTTRANSINFO
	{
		public int grfRMSupported;

		public int grfRMSupportedRetaining;

		public int grfTCSupported;

		public int grfTCSupportedRetaining;

		public int isoFlags;

		public int isoLevel;

		public BOID uow;
	}
}
namespace System.EnterpriseServices.Internal
{
	[Guid("ef24f689-14f8-4d92-b4af-d7b1f0e70fd4")]
	public class AppDomainHelper
	{
		[MonoTODO]
		public AppDomainHelper()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		~AppDomainHelper()
		{
			throw new NotImplementedException();
		}
	}
	[Guid("458aa3b5-265a-4b75-bc05-9bea4630cf18")]
	public class AssemblyLocator : MarshalByRefObject
	{
		[MonoTODO]
		public AssemblyLocator()
		{
			throw new NotImplementedException();
		}
	}
	public class ClientRemotingConfig
	{
		[MonoTODO]
		public ClientRemotingConfig()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static bool Write(string DestinationDirectory, string VRoot, string BaseUrl, string AssemblyName, string TypeName, string ProgId, string Mode, string Transport)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("ecabafd1-7f19-11d2-978e-0000f8757e2a")]
	public class ClrObjectFactory : IClrObjectFactory
	{
		[MonoTODO]
		public ClrObjectFactory()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public object CreateFromAssembly(string AssemblyName, string TypeName, string Mode)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public object CreateFromMailbox(string Mailbox, string Mode)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public object CreateFromVroot(string VrootUrl, string Mode)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public object CreateFromWsdl(string WsdlUrl, string Mode)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("3b0398c9-7812-4007-85cb-18c771f2206f")]
	public class ComManagedImportUtil : IComManagedImportUtil
	{
		[MonoTODO]
		public ComManagedImportUtil()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void GetComponentInfo(string assemblyPath, out string numComponents, out string componentInfo)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void InstallAssembly(string asmpath, string parname, string appname)
		{
			throw new NotImplementedException();
		}
	}
	public class ComSoapPublishError
	{
		[MonoTODO]
		public ComSoapPublishError()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static void Report(string s)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("d8013ff1-730b-45e2-ba24-874b7242c425")]
	public class GenerateMetadata : IComSoapMetadata
	{
		[MonoTODO]
		public GenerateMetadata()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public string Generate(string strSrcTypeLib, string outPath)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public string GenerateMetaData(string strSrcTypeLib, string outPath, byte[] PublicKey, StrongNameKeyPair KeyPair)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public string GenerateSigned(string strSrcTypeLib, string outPath, bool InstallGac, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static int SearchPath(string path, string fileName, string extension, int numBufferChars, string buffer, int[] filePart)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("ecabafd2-7f19-11d2-978e-0000f8757e2a")]
	public interface IClrObjectFactory
	{
		[DispId(1)]
		[return: MarshalAs(UnmanagedType.IDispatch)]
		object CreateFromAssembly(string assembly, string type, string mode);

		[DispId(4)]
		[return: MarshalAs(UnmanagedType.IDispatch)]
		object CreateFromMailbox(string Mailbox, string Mode);

		[DispId(2)]
		[return: MarshalAs(UnmanagedType.IDispatch)]
		object CreateFromVroot(string VrootUrl, string Mode);

		[DispId(3)]
		[return: MarshalAs(UnmanagedType.IDispatch)]
		object CreateFromWsdl(string WsdlUrl, string Mode);
	}
	[Guid("c3f8f66b-91be-4c99-a94f-ce3b0a951039")]
	public interface IComManagedImportUtil
	{
		[DispId(4)]
		void GetComponentInfo([MarshalAs(UnmanagedType.BStr)] string assemblyPath, [MarshalAs(UnmanagedType.BStr)] out string numComponents, [MarshalAs(UnmanagedType.BStr)] out string componentInfo);

		[DispId(5)]
		void InstallAssembly([MarshalAs(UnmanagedType.BStr)] string filename, [MarshalAs(UnmanagedType.BStr)] string parname, [MarshalAs(UnmanagedType.BStr)] string appname);
	}
	[Guid("d8013ef0-730b-45e2-ba24-874b7242c425")]
	public interface IComSoapIISVRoot
	{
		[DispId(1)]
		void Create([MarshalAs(UnmanagedType.BStr)] string RootWeb, [MarshalAs(UnmanagedType.BStr)] string PhysicalDirectory, [MarshalAs(UnmanagedType.BStr)] string VirtualDirectory, [MarshalAs(UnmanagedType.BStr)] out string Error);

		[DispId(2)]
		void Delete([MarshalAs(UnmanagedType.BStr)] string RootWeb, [MarshalAs(UnmanagedType.BStr)] string PhysicalDirectory, [MarshalAs(UnmanagedType.BStr)] string VirtualDirectory, [MarshalAs(UnmanagedType.BStr)] out string Error);
	}
	[Guid("d8013ff0-730b-45e2-ba24-874b7242c425")]
	public interface IComSoapMetadata
	{
		[DispId(1)]
		[return: MarshalAs(UnmanagedType.BStr)]
		string Generate([MarshalAs(UnmanagedType.BStr)] string SrcTypeLibFileName, [MarshalAs(UnmanagedType.BStr)] string OutPath);

		[DispId(2)]
		[return: MarshalAs(UnmanagedType.BStr)]
		string GenerateSigned([MarshalAs(UnmanagedType.BStr)] string SrcTypeLibFileName, [MarshalAs(UnmanagedType.BStr)] string OutPath, [MarshalAs(UnmanagedType.Bool)] bool InstallGac, [MarshalAs(UnmanagedType.BStr)] out string Error);
	}
	[Guid("d8013eee-730b-45e2-ba24-874b7242c425")]
	public interface IComSoapPublisher
	{
		[DispId(6)]
		void CreateMailBox([MarshalAs(UnmanagedType.BStr)] string RootMailServer, [MarshalAs(UnmanagedType.BStr)] string MailBox, [MarshalAs(UnmanagedType.BStr)] out string SmtpName, [MarshalAs(UnmanagedType.BStr)] out string Domain, [MarshalAs(UnmanagedType.BStr)] out string PhysicalPath, [MarshalAs(UnmanagedType.BStr)] out string Error);

		[DispId(4)]
		void CreateVirtualRoot([MarshalAs(UnmanagedType.BStr)] string Operation, [MarshalAs(UnmanagedType.BStr)] string FullUrl, [MarshalAs(UnmanagedType.BStr)] out string BaseUrl, [MarshalAs(UnmanagedType.BStr)] out string VirtualRoot, [MarshalAs(UnmanagedType.BStr)] out string PhysicalPath, [MarshalAs(UnmanagedType.BStr)] out string Error);

		[DispId(7)]
		void DeleteMailBox([MarshalAs(UnmanagedType.BStr)] string RootMailServer, [MarshalAs(UnmanagedType.BStr)] string MailBox, [MarshalAs(UnmanagedType.BStr)] out string Error);

		[DispId(5)]
		void DeleteVirtualRoot([MarshalAs(UnmanagedType.BStr)] string RootWebServer, [MarshalAs(UnmanagedType.BStr)] string FullUrl, [MarshalAs(UnmanagedType.BStr)] out string Error);

		[DispId(13)]
		void GacInstall([MarshalAs(UnmanagedType.BStr)] string AssemblyPath);

		[DispId(14)]
		void GacRemove([MarshalAs(UnmanagedType.BStr)] string AssemblyPath);

		[DispId(15)]
		void GetAssemblyNameForCache([MarshalAs(UnmanagedType.BStr)] string TypeLibPath, [MarshalAs(UnmanagedType.BStr)] out string CachePath);

		[DispId(10)]
		[return: MarshalAs(UnmanagedType.BStr)]
		string GetTypeNameFromProgId([MarshalAs(UnmanagedType.BStr)] string AssemblyPath, [MarshalAs(UnmanagedType.BStr)] string ProgId);

		[DispId(9)]
		void ProcessClientTlb([MarshalAs(UnmanagedType.BStr)] string ProgId, [MarshalAs(UnmanagedType.BStr)] string SrcTlbPath, [MarshalAs(UnmanagedType.BStr)] string PhysicalPath, [MarshalAs(UnmanagedType.BStr)] string VRoot, [MarshalAs(UnmanagedType.BStr)] string BaseUrl, [MarshalAs(UnmanagedType.BStr)] string Mode, [MarshalAs(UnmanagedType.BStr)] string Transport, [MarshalAs(UnmanagedType.BStr)] out string AssemblyName, [MarshalAs(UnmanagedType.BStr)] out string TypeName, [MarshalAs(UnmanagedType.BStr)] out string Error);

		[DispId(8)]
		void ProcessServerTlb([MarshalAs(UnmanagedType.BStr)] string ProgId, [MarshalAs(UnmanagedType.BStr)] string SrcTlbPath, [MarshalAs(UnmanagedType.BStr)] string PhysicalPath, [MarshalAs(UnmanagedType.BStr)] string Operation, [MarshalAs(UnmanagedType.BStr)] out string AssemblyName, [MarshalAs(UnmanagedType.BStr)] out string TypeName, [MarshalAs(UnmanagedType.BStr)] out string Error);

		[DispId(11)]
		void RegisterAssembly([MarshalAs(UnmanagedType.BStr)] string AssemblyPath);

		[DispId(12)]
		void UnRegisterAssembly([MarshalAs(UnmanagedType.BStr)] string AssemblyPath);
	}
	[Guid("d8013ef1-730b-45e2-ba24-874b7242c425")]
	public class IISVirtualRoot : IComSoapIISVRoot
	{
		[MonoTODO]
		public IISVirtualRoot()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void Create(string RootWeb, string inPhysicalDirectory, string VirtualDirectory, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void Delete(string RootWeb, string PhysicalDirectory, string VirtualDirectory, out string Error)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("6261e4b5-572a-4142-a2f9-1fe1a0c97097")]
	public interface IServerWebConfig
	{
		[DispId(1)]
		void AddElement([MarshalAs(UnmanagedType.BStr)] string FilePath, [MarshalAs(UnmanagedType.BStr)] string AssemblyName, [MarshalAs(UnmanagedType.BStr)] string TypeName, [MarshalAs(UnmanagedType.BStr)] string ProgId, [MarshalAs(UnmanagedType.BStr)] string Mode, [MarshalAs(UnmanagedType.BStr)] out string Error);

		[DispId(2)]
		void Create([MarshalAs(UnmanagedType.BStr)] string FilePath, [MarshalAs(UnmanagedType.BStr)] string FileRootName, [MarshalAs(UnmanagedType.BStr)] out string Error);
	}
	[Guid("E7F0F021-9201-47e4-94DA-1D1416DEC27A")]
	public interface ISoapClientImport
	{
		[DispId(1)]
		void ProcessClientTlbEx([MarshalAs(UnmanagedType.BStr)] string progId, [MarshalAs(UnmanagedType.BStr)] string virtualRoot, [MarshalAs(UnmanagedType.BStr)] string baseUrl, [MarshalAs(UnmanagedType.BStr)] string authentication, [MarshalAs(UnmanagedType.BStr)] string assemblyName, [MarshalAs(UnmanagedType.BStr)] string typeName);
	}
	[Guid("1E7BA9F7-21DB-4482-929E-21BDE2DFE51C")]
	public interface ISoapServerTlb
	{
		[DispId(1)]
		void AddServerTlb([MarshalAs(UnmanagedType.BStr)] string progId, [MarshalAs(UnmanagedType.BStr)] string classId, [MarshalAs(UnmanagedType.BStr)] string interfaceId, [MarshalAs(UnmanagedType.BStr)] string srcTlbPath, [MarshalAs(UnmanagedType.BStr)] string rootWebServer, [MarshalAs(UnmanagedType.BStr)] string baseUrl, [MarshalAs(UnmanagedType.BStr)] string virtualRoot, [MarshalAs(UnmanagedType.BStr)] string clientActivated, [MarshalAs(UnmanagedType.BStr)] string wellKnown, [MarshalAs(UnmanagedType.BStr)] string discoFile, [MarshalAs(UnmanagedType.BStr)] string operation, [MarshalAs(UnmanagedType.BStr)] out string assemblyName, [MarshalAs(UnmanagedType.BStr)] out string typeName);

		[DispId(2)]
		void DeleteServerTlb([MarshalAs(UnmanagedType.BStr)] string progId, [MarshalAs(UnmanagedType.BStr)] string classId, [MarshalAs(UnmanagedType.BStr)] string interfaceId, [MarshalAs(UnmanagedType.BStr)] string srcTlbPath, [MarshalAs(UnmanagedType.BStr)] string rootWebServer, [MarshalAs(UnmanagedType.BStr)] string baseUrl, [MarshalAs(UnmanagedType.BStr)] string virtualRoot, [MarshalAs(UnmanagedType.BStr)] string operation, [MarshalAs(UnmanagedType.BStr)] string assemblyName, [MarshalAs(UnmanagedType.BStr)] string typeName);
	}
	[Guid("A31B6577-71D2-4344-AEDF-ADC1B0DC5347")]
	public interface ISoapServerVRoot
	{
		[DispId(1)]
		void CreateVirtualRootEx([MarshalAs(UnmanagedType.BStr)] string rootWebServer, [MarshalAs(UnmanagedType.BStr)] string inBaseUrl, [MarshalAs(UnmanagedType.BStr)] string inVirtualRoot, [MarshalAs(UnmanagedType.BStr)] string homePage, [MarshalAs(UnmanagedType.BStr)] string discoFile, [MarshalAs(UnmanagedType.BStr)] string secureSockets, [MarshalAs(UnmanagedType.BStr)] string authentication, [MarshalAs(UnmanagedType.BStr)] string operation, [MarshalAs(UnmanagedType.BStr)] out string baseUrl, [MarshalAs(UnmanagedType.BStr)] out string virtualRoot, [MarshalAs(UnmanagedType.BStr)] out string physicalPath);

		[DispId(2)]
		void DeleteVirtualRootEx([MarshalAs(UnmanagedType.BStr)] string rootWebServer, [MarshalAs(UnmanagedType.BStr)] string baseUrl, [MarshalAs(UnmanagedType.BStr)] string virtualRoot);

		[DispId(3)]
		void GetVirtualRootStatus([MarshalAs(UnmanagedType.BStr)] string rootWebServer, [MarshalAs(UnmanagedType.BStr)] string inBaseUrl, [MarshalAs(UnmanagedType.BStr)] string inVirtualRoot, [MarshalAs(UnmanagedType.BStr)] out string exists, [MarshalAs(UnmanagedType.BStr)] out string secureSockets, [MarshalAs(UnmanagedType.BStr)] out string windowsAuth, [MarshalAs(UnmanagedType.BStr)] out string anonymous, [MarshalAs(UnmanagedType.BStr)] out string homePage, [MarshalAs(UnmanagedType.BStr)] out string discoFile, [MarshalAs(UnmanagedType.BStr)] out string physicalPath, [MarshalAs(UnmanagedType.BStr)] out string baseUrl, [MarshalAs(UnmanagedType.BStr)] out string virtualRoot);
	}
	[Guid("5AC4CB7E-F89F-429b-926B-C7F940936BF4")]
	public interface ISoapUtility
	{
		[DispId(2)]
		void GetServerBinPath([MarshalAs(UnmanagedType.BStr)] string rootWebServer, [MarshalAs(UnmanagedType.BStr)] string inBaseUrl, [MarshalAs(UnmanagedType.BStr)] string inVirtualRoot, [MarshalAs(UnmanagedType.BStr)] out string binPath);

		[DispId(1)]
		void GetServerPhysicalPath([MarshalAs(UnmanagedType.BStr)] string rootWebServer, [MarshalAs(UnmanagedType.BStr)] string inBaseUrl, [MarshalAs(UnmanagedType.BStr)] string inVirtualRoot, [MarshalAs(UnmanagedType.BStr)] out string physicalPath);

		[DispId(3)]
		void Present();
	}
	[Guid("d8013eef-730b-45e2-ba24-874b7242c425")]
	public class Publish : IComSoapPublisher
	{
		[MonoTODO]
		public Publish()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void CreateMailBox(string RootMailServer, string MailBox, out string SmtpName, out string Domain, out string PhysicalPath, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void CreateVirtualRoot(string Operation, string FullUrl, out string BaseUrl, out string VirtualRoot, out string PhysicalPath, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void DeleteMailBox(string RootMailServer, string MailBox, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void DeleteVirtualRoot(string RootWebServer, string FullUrl, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void GacInstall(string AssemblyPath)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void GacRemove(string AssemblyPath)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void GetAssemblyNameForCache(string TypeLibPath, out string CachePath)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static string GetClientPhysicalPath(bool CreateDir)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public string GetTypeNameFromProgId(string AssemblyPath, string ProgId)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static void ParseUrl(string FullUrl, out string BaseUrl, out string VirtualRoot)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void ProcessClientTlb(string ProgId, string SrcTlbPath, string PhysicalPath, string VRoot, string BaseUrl, string Mode, string Transport, out string AssemblyName, out string TypeName, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void ProcessServerTlb(string ProgId, string SrcTlbPath, string PhysicalPath, string Operation, out string strAssemblyName, out string TypeName, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void RegisterAssembly(string AssemblyPath)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void UnRegisterAssembly(string AssemblyPath)
		{
			throw new NotImplementedException();
		}
	}
	public class ServerWebConfig : IServerWebConfig
	{
		[MonoTODO]
		public ServerWebConfig()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void AddElement(string FilePath, string AssemblyName, string TypeName, string ProgId, string WkoMode, out string Error)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void Create(string FilePath, string FilePrefix, out string Error)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("346D5B9F-45E1-45c0-AADF-1B7D221E9063")]
	public sealed class SoapClientImport : ISoapClientImport
	{
		[MonoTODO]
		public SoapClientImport()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void ProcessClientTlbEx(string progId, string virtualRoot, string baseUrl, string authentication, string assemblyName, string typeName)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("F6B6768F-F99E-4152-8ED2-0412F78517FB")]
	public sealed class SoapServerTlb : ISoapServerTlb
	{
		[MonoTODO]
		public SoapServerTlb()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void AddServerTlb(string progId, string classId, string interfaceId, string srcTlbPath, string rootWebServer, string inBaseUrl, string inVirtualRoot, string clientActivated, string wellKnown, string discoFile, string operation, out string strAssemblyName, out string typeName)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void DeleteServerTlb(string progId, string classId, string interfaceId, string srcTlbPath, string rootWebServer, string baseUrl, string virtualRoot, string operation, string assemblyName, string typeName)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("CAA817CC-0C04-4d22-A05C-2B7E162F4E8F")]
	public sealed class SoapServerVRoot : ISoapServerVRoot
	{
		[MonoTODO]
		public SoapServerVRoot()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void CreateVirtualRootEx(string rootWebServer, string inBaseUrl, string inVirtualRoot, string homePage, string discoFile, string secureSockets, string authentication, string operation, out string baseUrl, out string virtualRoot, out string physicalPath)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void DeleteVirtualRootEx(string rootWebServer, string inBaseUrl, string inVirtualRoot)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void GetVirtualRootStatus(string RootWebServer, string inBaseUrl, string inVirtualRoot, out string Exists, out string SSL, out string WindowsAuth, out string Anonymous, out string HomePage, out string DiscoFile, out string PhysicalPath, out string BaseUrl, out string VirtualRoot)
		{
			throw new NotImplementedException();
		}
	}
	[Guid("5F9A955F-AA55-4127-A32B-33496AA8A44E")]
	public sealed class SoapUtility : ISoapUtility
	{
		[MonoTODO]
		public SoapUtility()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void GetServerBinPath(string rootWebServer, string inBaseUrl, string inVirtualRoot, out string binPath)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void GetServerPhysicalPath(string rootWebServer, string inBaseUrl, string inVirtualRoot, out string physicalPath)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void Present()
		{
			throw new NotImplementedException();
		}
	}
}
namespace System.EnterpriseServices.CompensatingResourceManager
{
	[AttributeUsage(AttributeTargets.Assembly)]
	[ComVisible(false)]
	[ProgId("System.EnterpriseServices.Crm.ApplicationCrmEnabledAttribute")]
	public sealed class ApplicationCrmEnabledAttribute : Attribute
	{
		private bool val;

		public bool Value => val;

		public ApplicationCrmEnabledAttribute()
		{
			val = true;
		}

		public ApplicationCrmEnabledAttribute(bool val)
		{
			this.val = val;
		}
	}
	public sealed class Clerk
	{
		public int LogRecordCount
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		public string TransactionUOW
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public Clerk(string compensator, string description, CompensatorOptions flags)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public Clerk(Type compensator, string description, CompensatorOptions flags)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		~Clerk()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void ForceLog()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void ForceTransactionToAbort()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void ForgetLogRecord()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void WriteLogRecord(object record)
		{
			throw new NotImplementedException();
		}
	}
	public sealed class ClerkInfo
	{
		[MonoTODO]
		public string ActivityId
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public Clerk Clerk
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string Compensator
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string Description
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string InstanceId
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public string TransactionUOW
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		~ClerkInfo()
		{
			throw new NotImplementedException();
		}

		internal ClerkInfo()
		{
		}
	}
	public sealed class ClerkMonitor : IEnumerable
	{
		[MonoTODO]
		public int Count
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public ClerkInfo this[string index]
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public ClerkInfo this[int index]
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		~ClerkMonitor()
		{
		}

		[MonoTODO]
		public ClerkMonitor()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public IEnumerator GetEnumerator()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public void Populate()
		{
			throw new NotImplementedException();
		}
	}
	public class Compensator : ServicedComponent
	{
		public Clerk Clerk
		{
			[MonoTODO]
			get
			{
				throw new NotImplementedException();
			}
		}

		[MonoTODO]
		public Compensator()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual bool AbortRecord(LogRecord rec)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual void BeginAbort(bool fRecovery)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual void BeginCommit(bool fRecovery)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual void BeginPrepare()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual bool CommitRecord(LogRecord rec)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual void EndAbort()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual void EndCommit()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual bool EndPrepare()
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public virtual bool PrepareRecord(LogRecord rec)
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	[Flags]
	public enum CompensatorOptions
	{
		PreparePhase = 1,
		CommitPhase = 2,
		AbortPhase = 4,
		AllPhases = 7,
		FailIfInDoubtsRemain = 0x10
	}
	public sealed class LogRecord
	{
		private LogRecordFlags flags;

		private object record;

		private int sequence;

		public LogRecordFlags Flags => flags;

		public object Record => record;

		public int Sequence => sequence;

		[MonoTODO]
		internal LogRecord()
		{
		}

		[MonoTODO]
		internal LogRecord(_LogRecord logRecord)
		{
			flags = (LogRecordFlags)logRecord.dwCrmFlags;
			sequence = logRecord.dwSequenceNumber;
			record = logRecord.blobUserData;
		}
	}
	internal struct _LogRecord
	{
		public int dwCrmFlags;

		public int dwSequenceNumber;

		public object blobUserData;
	}
	[Serializable]
	[Flags]
	public enum LogRecordFlags
	{
		ForgetTarget = 1,
		WrittenDuringPrepare = 2,
		WrittenDuringCommit = 4,
		WrittenDuringAbort = 8,
		WrittenDurringRecovery = 0x10,
		WrittenDuringReplay = 0x20,
		ReplayInProgress = 0x40
	}
	[Serializable]
	public enum TransactionState
	{
		Active,
		Committed,
		Aborted,
		Indoubt
	}
}
namespace Unity
{
	internal sealed class ThrowStub : ObjectDisposedException
	{
		public static void ThrowNotSupportedException()
		{
			throw new PlatformNotSupportedException();
		}
	}
}

BepInEx/core/System.IO.Compression.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO.Compression;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
using Unity;

[assembly: CLSCompliant(true)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.IO.Compression.dll")]
[assembly: AssemblyDefaultAlias("System.IO.Compression.dll")]
[assembly: AssemblyDescription("System.IO.Compression.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: AssemblyDelaySign(true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: TypeForwardedTo(typeof(CompressionLevel))]
[assembly: TypeForwardedTo(typeof(CompressionMode))]
[assembly: TypeForwardedTo(typeof(DeflateStream))]
[assembly: TypeForwardedTo(typeof(GZipStream))]
[module: UnverifiableCode]
internal static class Interop
{
	internal static class Brotli
	{
		[DllImport("__Internal")]
		internal static extern SafeBrotliDecoderHandle BrotliDecoderCreateInstance(IntPtr allocFunc, IntPtr freeFunc, IntPtr opaque);

		[DllImport("__Internal")]
		internal unsafe static extern int BrotliDecoderDecompressStream(SafeBrotliDecoderHandle state, ref IntPtr availableIn, byte** nextIn, ref IntPtr availableOut, byte** nextOut, out IntPtr totalOut);

		[DllImport("__Internal")]
		internal unsafe static extern bool BrotliDecoderDecompress(IntPtr availableInput, byte* inBytes, ref IntPtr availableOutput, byte* outBytes);

		[DllImport("__Internal")]
		internal static extern void BrotliDecoderDestroyInstance(IntPtr state);

		[DllImport("__Internal")]
		internal static extern bool BrotliDecoderIsFinished(SafeBrotliDecoderHandle state);

		[DllImport("__Internal")]
		internal static extern SafeBrotliEncoderHandle BrotliEncoderCreateInstance(IntPtr allocFunc, IntPtr freeFunc, IntPtr opaque);

		[DllImport("__Internal")]
		internal static extern bool BrotliEncoderSetParameter(SafeBrotliEncoderHandle state, BrotliEncoderParameter parameter, uint value);

		[DllImport("__Internal")]
		internal unsafe static extern bool BrotliEncoderCompressStream(SafeBrotliEncoderHandle state, BrotliEncoderOperation op, ref IntPtr availableIn, byte** nextIn, ref IntPtr availableOut, byte** nextOut, out IntPtr totalOut);

		[DllImport("__Internal")]
		internal static extern bool BrotliEncoderHasMoreOutput(SafeBrotliEncoderHandle state);

		[DllImport("__Internal")]
		internal static extern void BrotliEncoderDestroyInstance(IntPtr state);

		[DllImport("__Internal")]
		internal unsafe static extern bool BrotliEncoderCompress(int quality, int window, int v, IntPtr availableInput, byte* inBytes, ref IntPtr availableOutput, byte* outBytes);
	}

	internal static class Libraries
	{
		internal const string CompressionNative = "__Internal";
	}
}
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class SR
{
	public const string ArgumentOutOfRange_Enum = "Enum value was out of legal range.";

	public const string ArgumentOutOfRange_NeedPosNum = "Positive number required.";

	public const string CannotReadFromDeflateStream = "Reading from the compression stream is not supported.";

	public const string CannotWriteToDeflateStream = "Writing to the compression stream is not supported.";

	public const string GenericInvalidData = "Found invalid data while decoding.";

	public const string InvalidArgumentOffsetCount = "Offset plus count is larger than the length of target array.";

	public const string InvalidBeginCall = "Only one asynchronous reader or writer is allowed time at one time.";

	public const string InvalidBlockLength = "Block length does not match with its complement.";

	public const string InvalidHuffmanData = "Failed to construct a huffman tree using the length array. The stream might be corrupted.";

	public const string NotSupported = "This operation is not supported.";

	public const string NotSupported_UnreadableStream = "Stream does not support reading.";

	public const string NotSupported_UnwritableStream = "Stream does not support writing.";

	public const string ObjectDisposed_StreamClosed = "Can not access a closed Stream.";

	public const string UnknownBlockType = "Unknown block type. Stream might be corrupted.";

	public const string UnknownState = "Decoder is in some unknown state. This might be caused by corrupted data.";

	public const string ZLibErrorDLLLoadError = "The underlying compression routine could not be loaded correctly.";

	public const string ZLibErrorInconsistentStream = "The stream state of the underlying compression routine is inconsistent.";

	public const string ZLibErrorIncorrectInitParameters = "The underlying compression routine received incorrect initialization parameters.";

	public const string ZLibErrorNotEnoughMemory = "The underlying compression routine could not reserve sufficient memory.";

	public const string ZLibErrorVersionMismatch = "The version of the underlying compression routine does not match expected version.";

	public const string ZLibErrorUnexpected = "The underlying compression routine returned an unexpected error code.";

	public const string ArgumentNeedNonNegative = "The argument must be non-negative.";

	public const string CannotBeEmpty = "String cannot be empty.";

	public const string CDCorrupt = "Central Directory corrupt.";

	public const string CentralDirectoryInvalid = "Central Directory is invalid.";

	public const string CreateInReadMode = "Cannot create entries on an archive opened in read mode.";

	public const string CreateModeCapabilities = "Cannot use create mode on a non-writable stream.";

	public const string CreateModeCreateEntryWhileOpen = "Entries cannot be created while previously created entries are still open.";

	public const string CreateModeWriteOnceAndOneEntryAtATime = "Entries in create mode may only be written to once, and only one entry may be held open at a time.";

	public const string DateTimeOutOfRange = "The DateTimeOffset specified cannot be converted into a Zip file timestamp.";

	public const string DeletedEntry = "Cannot modify deleted entry.";

	public const string DeleteOnlyInUpdate = "Delete can only be used when the archive is in Update mode.";

	public const string DeleteOpenEntry = "Cannot delete an entry currently open for writing.";

	public const string EntriesInCreateMode = "Cannot access entries in Create mode.";

	public const string EntryNameEncodingNotSupported = "The specified entry name encoding is not supported.";

	public const string EntryNamesTooLong = "Entry names cannot require more than 2^16 bits.";

	public const string EntryTooLarge = "Entries larger than 4GB are not supported in Update mode.";

	public const string EOCDNotFound = "End of Central Directory record could not be found.";

	public const string FieldTooBigCompressedSize = "Compressed Size cannot be held in an Int64.";

	public const string FieldTooBigLocalHeaderOffset = "Local Header Offset cannot be held in an Int64.";

	public const string FieldTooBigNumEntries = "Number of Entries cannot be held in an Int64.";

	public const string FieldTooBigOffsetToCD = "Offset to Central Directory cannot be held in an Int64.";

	public const string FieldTooBigOffsetToZip64EOCD = "Offset to Zip64 End Of Central Directory record cannot be held in an Int64.";

	public const string FieldTooBigStartDiskNumber = "Start Disk Number cannot be held in an Int64.";

	public const string FieldTooBigUncompressedSize = "Uncompressed Size cannot be held in an Int64.";

	public const string FrozenAfterWrite = "Cannot modify entry in Create mode after entry has been opened for writing.";

	public const string HiddenStreamName = "A stream from ZipArchiveEntry has been disposed.";

	public const string LengthAfterWrite = "Length properties are unavailable once an entry has been opened for writing.";

	public const string LocalFileHeaderCorrupt = "A local file header is corrupt.";

	public const string NumEntriesWrong = "Number of entries expected in End Of Central Directory does not correspond to number of entries in Central Directory.";

	public const string OffsetLengthInvalid = "The offset and length parameters are not valid for the array that was given.";

	public const string ReadingNotSupported = "This stream from ZipArchiveEntry does not support reading.";

	public const string ReadModeCapabilities = "Cannot use read mode on a non-readable stream.";

	public const string ReadOnlyArchive = "Cannot modify read-only archive.";

	public const string SeekingNotSupported = "This stream from ZipArchiveEntry does not support seeking.";

	public const string SetLengthRequiresSeekingAndWriting = "SetLength requires a stream that supports seeking and writing.";

	public const string SplitSpanned = "Split or spanned archives are not supported.";

	public const string UnexpectedEndOfStream = "Zip file corrupt: unexpected end of stream reached.";

	public const string UnsupportedCompression = "The archive entry was compressed using an unsupported compression method.";

	public const string UnsupportedCompressionMethod = "The archive entry was compressed using {0} and is not supported.";

	public const string UpdateModeCapabilities = "Update mode requires a stream with read, write, and seek capabilities.";

	public const string UpdateModeOneStream = "Entries cannot be opened multiple times in Update mode.";

	public const string WritingNotSupported = "This stream from ZipArchiveEntry does not support writing.";

	public const string Zip64EOCDNotWhereExpected = "Zip 64 End of Central Directory Record not where indicated.";

	public const string Argument_InvalidPathChars = "Illegal characters in path '{0}'.";

	public const string Stream_FalseCanRead = "Stream does not support reading.";

	public const string Stream_FalseCanWrite = "Stream does not support writing.";

	public const string BrotliEncoder_Create = "Failed to create BrotliEncoder instance";

	public const string BrotliEncoder_Disposed = "Can not access a closed Encoder.";

	public const string BrotliEncoder_Quality = "Provided BrotliEncoder Quality of {0} is not between the minimum value of {1} and the maximum value of {2}";

	public const string BrotliEncoder_Window = "Provided BrotliEncoder Window of {0} is not between the minimum value of {1} and the maximum value of {2}";

	public const string BrotliEncoder_InvalidSetParameter = "The BrotliEncoder {0} can not be changed at current encoder state.";

	public const string BrotliDecoder_Create = "Failed to create BrotliDecoder instance";

	public const string BrotliDecoder_Error = "Decoder threw unexpected error: {0}";

	public const string BrotliDecoder_Disposed = "Can not access a closed Decoder.";

	public const string BrotliStream_Compress_UnsupportedOperation = "Can not perform Read operations on a BrotliStream constructed with CompressionMode.Compress.";

	public const string BrotliStream_Compress_InvalidData = "Encoder ran into invalid data.";

	public const string BrotliStream_Decompress_UnsupportedOperation = "Can not perform Write operations on a BrotliStream constructed with CompressionMode.Decompress.";

	public const string BrotliStream_Decompress_InvalidData = "Decoder ran into invalid data.";

	public const string BrotliStream_Decompress_InvalidStream = "BrotliStream.BaseStream returned more bytes than requested in Read.";

	internal static string GetString(string name, params object[] args)
	{
		return GetString(CultureInfo.InvariantCulture, name, args);
	}

	internal static string GetString(CultureInfo culture, string name, params object[] args)
	{
		return string.Format(culture, name, args);
	}

	internal static string GetString(string name)
	{
		return name;
	}

	internal static string GetString(CultureInfo culture, string name)
	{
		return name;
	}

	internal static string Format(string resourceFormat, params object[] args)
	{
		if (args != null)
		{
			return string.Format(CultureInfo.InvariantCulture, resourceFormat, args);
		}
		return resourceFormat;
	}

	internal static string Format(string resourceFormat, object p1)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1);
	}

	internal static string Format(string resourceFormat, object p1, object p2)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2);
	}

	internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2)
	{
		return string.Format(ci, resourceFormat, p1, p2);
	}

	internal static string Format(string resourceFormat, object p1, object p2, object p3)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3);
	}

	internal static string GetResourceString(string str)
	{
		return str;
	}
}
namespace System.Runtime.CompilerServices
{
	internal class FriendAccessAllowedAttribute : Attribute
	{
	}
}
namespace System.IO.Compression
{
	public sealed class BrotliStream : Stream
	{
		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <FinishReadAsyncMemory>d__41 : IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncValueTaskMethodBuilder<int> <>t__builder;

			public BrotliStream <>4__this;

			public CancellationToken cancellationToken;

			public Memory<byte> buffer;

			private int <totalWritten>5__2;

			private ConfiguredValueTaskAwaiter<int> <>u__1;

			private void MoveNext()
			{
				//IL_013c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0141: Unknown result type (might be due to invalid IL or missing references)
				//IL_0149: 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_002c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0223: Unknown result type (might be due to invalid IL or missing references)
				//IL_0032: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Invalid comparison between Unknown and I4
				//IL_019d: Unknown result type (might be due to invalid IL or missing references)
				//IL_01a2: 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_01b6: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
				//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
				//IL_01be: Invalid comparison between Unknown and I4
				//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
				//IL_00f9: Unknown result type (might be due to invalid IL or missing references)
				//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
				//IL_0103: Unknown result type (might be due to invalid IL or missing references)
				//IL_0107: Unknown result type (might be due to invalid IL or missing references)
				//IL_010c: 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_0123: 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_0061: Unknown result type (might be due to invalid IL or missing references)
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_020b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0210: Unknown result type (might be due to invalid IL or missing references)
				int num = <>1__state;
				BrotliStream brotliStream = <>4__this;
				int result;
				try
				{
					if (num != 0)
					{
						brotliStream.AsyncOperationStarting();
					}
					try
					{
						OperationStatus val;
						if (num != 0)
						{
							<totalWritten>5__2 = 0;
							_ = Memory<byte>.Empty;
							val = (OperationStatus)1;
							goto IL_0215;
						}
						ConfiguredValueTaskAwaiter<int> awaiter = <>u__1;
						<>u__1 = default(ConfiguredValueTaskAwaiter<int>);
						num = (<>1__state = -1);
						goto IL_0158;
						IL_0215:
						int num2;
						if (buffer.Length > 0 && (int)val != 0)
						{
							if ((int)val == 2)
							{
								if (brotliStream._bufferCount > 0 && brotliStream._bufferOffset != 0)
								{
									MemoryExtensions.AsSpan<byte>(brotliStream._buffer, brotliStream._bufferOffset, brotliStream._bufferCount).CopyTo(Span<byte>.op_Implicit(brotliStream._buffer));
								}
								brotliStream._bufferOffset = 0;
								num2 = 0;
								goto IL_00ab;
							}
							goto IL_017a;
						}
						goto IL_0229;
						IL_00ab:
						bool flag = brotliStream._bufferCount < brotliStream._buffer.Length;
						if (flag)
						{
							awaiter = brotliStream._stream.ReadAsync(new Memory<byte>(brotliStream._buffer, brotliStream._bufferCount, brotliStream._buffer.Length - brotliStream._bufferCount), default(CancellationToken)).ConfigureAwait(false).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter;
								<>t__builder.AwaitUnsafeOnCompleted<ConfiguredValueTaskAwaiter<int>, <FinishReadAsyncMemory>d__41>(ref awaiter, ref this);
								return;
							}
							goto IL_0158;
						}
						goto IL_0167;
						IL_0158:
						flag = (num2 = awaiter.GetResult()) > 0;
						goto IL_0167;
						IL_0167:
						if (flag)
						{
							brotliStream._bufferCount += num2;
							if (brotliStream._bufferCount > brotliStream._buffer.Length)
							{
								throw new InvalidDataException("BrotliStream.BaseStream returned more bytes than requested in Read.");
							}
							goto IL_00ab;
						}
						if (brotliStream._bufferCount > 0)
						{
							goto IL_017a;
						}
						goto IL_0229;
						IL_0229:
						result = <totalWritten>5__2;
						goto end_IL_0018;
						IL_017a:
						cancellationToken.ThrowIfCancellationRequested();
						val = brotliStream._decoder.Decompress(Span<byte>.op_Implicit(MemoryExtensions.AsSpan<byte>(brotliStream._buffer, brotliStream._bufferOffset, brotliStream._bufferCount)), buffer.Span, out var bytesConsumed, out var bytesWritten);
						if ((int)val == 3)
						{
							throw new InvalidOperationException("Decoder ran into invalid data.");
						}
						if (bytesConsumed > 0)
						{
							brotliStream._bufferOffset += bytesConsumed;
							brotliStream._bufferCount -= bytesConsumed;
						}
						if (bytesWritten > 0)
						{
							<totalWritten>5__2 += bytesWritten;
							buffer = buffer.Slice(bytesWritten);
						}
						goto IL_0215;
						end_IL_0018:;
					}
					finally
					{
						if (num < 0)
						{
							brotliStream.AsyncOperationCompleting();
						}
					}
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<>t__builder.SetResult(result);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		private const int DefaultInternalBufferSize = 65520;

		private Stream _stream;

		private readonly byte[] _buffer;

		private readonly bool _leaveOpen;

		private readonly CompressionMode _mode;

		private int _activeAsyncOperation;

		private BrotliDecoder _decoder;

		private int _bufferOffset;

		private int _bufferCount;

		private BrotliEncoder _encoder;

		public Stream BaseStream => _stream;

		public override bool CanRead
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				if ((int)_mode == 0 && _stream != null)
				{
					return _stream.CanRead;
				}
				return false;
			}
		}

		public override bool CanWrite
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0007: Invalid comparison between Unknown and I4
				if ((int)_mode == 1 && _stream != null)
				{
					return _stream.CanWrite;
				}
				return false;
			}
		}

		public override bool CanSeek => false;

		public override long Length
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public override long Position
		{
			get
			{
				throw new NotSupportedException();
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		private bool AsyncOperationIsActive => _activeAsyncOperation != 0;

		public BrotliStream(Stream stream, CompressionMode mode)
			: this(stream, mode, leaveOpen: false)
		{
		}//IL_0002: Unknown result type (might be due to invalid IL or missing references)


		public BrotliStream(Stream stream, CompressionMode mode, bool leaveOpen)
		{
			//IL_0014: 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_0019: Invalid comparison between Unknown and I4
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			if ((int)mode != 0)
			{
				if ((int)mode != 1)
				{
					throw new ArgumentException("Enum value was out of legal range.", "mode");
				}
				if (!stream.CanWrite)
				{
					throw new ArgumentException("Stream does not support writing.", "stream");
				}
			}
			else if (!stream.CanRead)
			{
				throw new ArgumentException("Stream does not support reading.", "stream");
			}
			_mode = mode;
			_stream = stream;
			_leaveOpen = leaveOpen;
			_buffer = new byte[65520];
		}

		private void EnsureNotDisposed()
		{
			if (_stream == null)
			{
				throw new ObjectDisposedException("stream", "Can not access a closed Stream.");
			}
		}

		protected override void Dispose(bool disposing)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Invalid comparison between Unknown and I4
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (disposing && _stream != null)
				{
					if ((int)_mode == 1)
					{
						WriteCore(ReadOnlySpan<byte>.Empty, isFinalBlock: true);
					}
					if (!_leaveOpen)
					{
						_stream.Dispose();
					}
				}
			}
			finally
			{
				_stream = null;
				_encoder.Dispose();
				_decoder.Dispose();
				base.Dispose(disposing);
			}
		}

		private static void ValidateParameters(byte[] array, int offset, int count)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", "Positive number required.");
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count", "Positive number required.");
			}
			if (array.Length - offset < count)
			{
				throw new ArgumentException("Offset plus count is larger than the length of target array.");
			}
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		private void EnsureNoActiveAsyncOperation()
		{
			if (AsyncOperationIsActive)
			{
				ThrowInvalidBeginCall();
			}
		}

		private void AsyncOperationStarting()
		{
			if (Interlocked.CompareExchange(ref _activeAsyncOperation, 1, 0) != 0)
			{
				ThrowInvalidBeginCall();
			}
		}

		private void AsyncOperationCompleting()
		{
			Interlocked.CompareExchange(ref _activeAsyncOperation, 0, 1);
		}

		private static void ThrowInvalidBeginCall()
		{
			throw new InvalidOperationException("Only one asynchronous reader or writer is allowed time at one time.");
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			ValidateParameters(buffer, offset, count);
			return ((Stream)this).Read(new Span<byte>(buffer, offset, count));
		}

		public int Read(Span<byte> buffer)
		{
			//IL_0001: 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_0158: 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_0024: Invalid comparison between Unknown and I4
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Unknown result type (might be due to invalid IL or missing references)
			//IL_010d: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Invalid comparison between Unknown and I4
			//IL_004c: 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)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0147: Unknown result type (might be due to invalid IL or missing references)
			//IL_014c: Unknown result type (might be due to invalid IL or missing references)
			if ((int)_mode != 0)
			{
				throw new InvalidOperationException("Can not perform Read operations on a BrotliStream constructed with CompressionMode.Compress.");
			}
			EnsureNotDisposed();
			int num = 0;
			OperationStatus val = (OperationStatus)1;
			while (buffer.Length > 0 && (int)val != 0)
			{
				if ((int)val == 2)
				{
					if (_bufferCount > 0 && _bufferOffset != 0)
					{
						MemoryExtensions.AsSpan<byte>(_buffer, _bufferOffset, _bufferCount).CopyTo(Span<byte>.op_Implicit(_buffer));
					}
					_bufferOffset = 0;
					int num2 = 0;
					while (_bufferCount < _buffer.Length && (num2 = _stream.Read(_buffer, _bufferCount, _buffer.Length - _bufferCount)) > 0)
					{
						_bufferCount += num2;
						if (_bufferCount > _buffer.Length)
						{
							throw new InvalidDataException("BrotliStream.BaseStream returned more bytes than requested in Read.");
						}
					}
					if (_bufferCount <= 0)
					{
						break;
					}
				}
				val = _decoder.Decompress(Span<byte>.op_Implicit(MemoryExtensions.AsSpan<byte>(_buffer, _bufferOffset, _bufferCount)), buffer, out var bytesConsumed, out var bytesWritten);
				if ((int)val == 3)
				{
					throw new InvalidOperationException("Decoder ran into invalid data.");
				}
				if (bytesConsumed > 0)
				{
					_bufferOffset += bytesConsumed;
					_bufferCount -= bytesConsumed;
				}
				if (bytesWritten > 0)
				{
					num += bytesWritten;
					buffer = buffer.Slice(bytesWritten);
				}
			}
			return num;
		}

		public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
		{
			return System.Threading.Tasks.TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
		}

		public override int EndRead(IAsyncResult asyncResult)
		{
			return System.Threading.Tasks.TaskToApm.End<int>(asyncResult);
		}

		public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			//IL_000c: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			ValidateParameters(buffer, offset, count);
			return ((Stream)this).ReadAsync(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
		}

		public ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			//IL_0001: 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_0037: 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)
			if ((int)_mode != 0)
			{
				throw new InvalidOperationException("Can not perform Read operations on a BrotliStream constructed with CompressionMode.Compress.");
			}
			EnsureNoActiveAsyncOperation();
			EnsureNotDisposed();
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
			}
			return FinishReadAsyncMemory(buffer, cancellationToken);
		}

		[AsyncStateMachine(typeof(<FinishReadAsyncMemory>d__41))]
		private ValueTask<int> FinishReadAsyncMemory(Memory<byte> buffer, CancellationToken cancellationToken)
		{
			//IL_000a: 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_001f: 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)
			<FinishReadAsyncMemory>d__41 <FinishReadAsyncMemory>d__ = default(<FinishReadAsyncMemory>d__41);
			<FinishReadAsyncMemory>d__.<>4__this = this;
			<FinishReadAsyncMemory>d__.buffer = buffer;
			<FinishReadAsyncMemory>d__.cancellationToken = cancellationToken;
			<FinishReadAsyncMemory>d__.<>t__builder = AsyncValueTaskMethodBuilder<int>.Create();
			<FinishReadAsyncMemory>d__.<>1__state = -1;
			<FinishReadAsyncMemory>d__.<>t__builder.Start<<FinishReadAsyncMemory>d__41>(ref <FinishReadAsyncMemory>d__);
			return <FinishReadAsyncMemory>d__.<>t__builder.Task;
		}

		public BrotliStream(Stream stream, CompressionLevel compressionLevel)
			: this(stream, compressionLevel, leaveOpen: false)
		{
		}//IL_0002: Unknown result type (might be due to invalid IL or missing references)


		public BrotliStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen)
			: this(stream, (CompressionMode)1, leaveOpen)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			_encoder.SetQuality(BrotliUtils.GetQualityFromCompressionLevel(compressionLevel));
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			ValidateParameters(buffer, offset, count);
			WriteCore(new ReadOnlySpan<byte>(buffer, offset, count));
		}

		public void Write(ReadOnlySpan<byte> buffer)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			WriteCore(buffer);
		}

		internal void WriteCore(ReadOnlySpan<byte> buffer, bool isFinalBlock = false)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Invalid comparison between Unknown and I4
			//IL_0035: 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_003c: 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_0044: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0075: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			if ((int)_mode != 1)
			{
				throw new InvalidOperationException("Can not perform Write operations on a BrotliStream constructed with CompressionMode.Decompress.");
			}
			EnsureNotDisposed();
			OperationStatus val = (OperationStatus)1;
			Span<byte> destination = default(Span<byte>);
			destination..ctor(_buffer);
			while ((int)val == 1)
			{
				int bytesConsumed = 0;
				int bytesWritten = 0;
				val = _encoder.Compress(buffer, destination, out bytesConsumed, out bytesWritten, isFinalBlock);
				if ((int)val == 3)
				{
					throw new InvalidOperationException("Encoder ran into invalid data.");
				}
				if (bytesWritten > 0)
				{
					_stream.Write(Span<byte>.op_Implicit(destination.Slice(0, bytesWritten)));
				}
				if (bytesConsumed > 0)
				{
					buffer = buffer.Slice(bytesConsumed);
				}
			}
		}

		public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
		{
			return System.Threading.Tasks.TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
		}

		public override void EndWrite(IAsyncResult asyncResult)
		{
			System.Threading.Tasks.TaskToApm.End(asyncResult);
		}

		public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			//IL_000c: 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_0018: Unknown result type (might be due to invalid IL or missing references)
			ValidateParameters(buffer, offset, count);
			ValueTask val = ((Stream)this).WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken);
			return ((ValueTask)(ref val)).AsTask();
		}

		public ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			//IL_002a: 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 ((int)_mode != 1)
			{
				throw new InvalidOperationException("Can not perform Write operations on a BrotliStream constructed with CompressionMode.Decompress.");
			}
			EnsureNoActiveAsyncOperation();
			EnsureNotDisposed();
			return new ValueTask(cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : WriteAsyncMemoryCore(buffer, cancellationToken));
		}

		private async Task WriteAsyncMemoryCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken)
		{
			//IL_000a: 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)
			AsyncOperationStarting();
			try
			{
				OperationStatus lastResult = (OperationStatus)1;
				Memory<byte> destination = default(Memory<byte>);
				while ((int)lastResult == 1)
				{
					destination..ctor(_buffer);
					int bytesConsumed = 0;
					int bytesWritten = 0;
					lastResult = _encoder.Compress(buffer, destination, out bytesConsumed, out bytesWritten, isFinalBlock: false);
					if ((int)lastResult == 3)
					{
						throw new InvalidOperationException("Encoder ran into invalid data.");
					}
					if (bytesConsumed > 0)
					{
						buffer = buffer.Slice(bytesConsumed);
					}
					if (bytesWritten > 0)
					{
						ValueTask val = _stream.WriteAsync(new ReadOnlyMemory<byte>(_buffer, 0, bytesWritten), cancellationToken);
						await ((ValueTask)(ref val)).ConfigureAwait(false);
					}
				}
			}
			finally
			{
				AsyncOperationCompleting();
			}
		}

		public override void Flush()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Invalid comparison between Unknown and I4
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Invalid comparison between Unknown and I4
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: 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)
			//IL_0053: Invalid comparison between Unknown and I4
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Unknown result type (might be due to invalid IL or missing references)
			EnsureNotDisposed();
			if ((int)_mode != 1 || _encoder._state == null || _encoder._state.IsClosed)
			{
				return;
			}
			OperationStatus val = (OperationStatus)1;
			Span<byte> destination = default(Span<byte>);
			destination..ctor(_buffer);
			while ((int)val == 1)
			{
				int bytesWritten = 0;
				val = _encoder.Flush(destination, out bytesWritten);
				if ((int)val == 3)
				{
					throw new InvalidDataException("Encoder ran into invalid data.");
				}
				if (bytesWritten > 0)
				{
					_stream.Write(Span<byte>.op_Implicit(destination.Slice(0, bytesWritten)));
				}
			}
		}

		public override Task FlushAsync(CancellationToken cancellationToken)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Invalid comparison between Unknown and I4
			EnsureNoActiveAsyncOperation();
			EnsureNotDisposed();
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			if ((int)_mode == 1)
			{
				return FlushAsyncCore(cancellationToken);
			}
			return Task.CompletedTask;
		}

		private async Task FlushAsyncCore(CancellationToken cancellationToken)
		{
			AsyncOperationStarting();
			try
			{
				if (_encoder._state == null || _encoder._state.IsClosed)
				{
					return;
				}
				OperationStatus lastResult = (OperationStatus)1;
				Memory<byte> destination = default(Memory<byte>);
				while ((int)lastResult == 1)
				{
					destination..ctor(_buffer);
					int bytesWritten = 0;
					lastResult = _encoder.Flush(destination, out bytesWritten);
					if ((int)lastResult == 3)
					{
						throw new InvalidDataException("Encoder ran into invalid data.");
					}
					if (bytesWritten > 0)
					{
						ValueTask val = _stream.WriteAsync(Memory<byte>.op_Implicit(destination.Slice(0, bytesWritten)), cancellationToken);
						await ((ValueTask)(ref val)).ConfigureAwait(false);
					}
				}
			}
			finally
			{
				AsyncOperationCompleting();
			}
		}
	}
	internal static class BrotliUtils
	{
		public const int WindowBits_Min = 10;

		public const int WindowBits_Default = 22;

		public const int WindowBits_Max = 24;

		public const int Quality_Min = 0;

		public const int Quality_Default = 11;

		public const int Quality_Max = 11;

		public const int MaxInputSize = 2147483132;

		internal static int GetQualityFromCompressionLevel(CompressionLevel level)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected I4, but got Unknown
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected I4, but got Unknown
			return (int)level switch
			{
				0 => 11, 
				2 => 0, 
				1 => 1, 
				_ => (int)level, 
			};
		}
	}
	public struct BrotliDecoder : IDisposable
	{
		private SafeBrotliDecoderHandle _state;

		private bool _disposed;

		internal void InitializeDecoder()
		{
			_state = global::Interop.Brotli.BrotliDecoderCreateInstance(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
			if (_state.IsInvalid)
			{
				throw new IOException("Failed to create BrotliDecoder instance");
			}
		}

		internal void EnsureInitialized()
		{
			EnsureNotDisposed();
			if (_state == null)
			{
				InitializeDecoder();
			}
		}

		public void Dispose()
		{
			_disposed = true;
			_state?.Dispose();
		}

		private void EnsureNotDisposed()
		{
			if (_disposed)
			{
				throw new ObjectDisposedException("BrotliDecoder", "Can not access a closed Decoder.");
			}
		}

		public unsafe OperationStatus Decompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesConsumed, out int bytesWritten)
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			EnsureInitialized();
			bytesConsumed = 0;
			bytesWritten = 0;
			if (!global::Interop.Brotli.BrotliDecoderIsFinished(_state))
			{
				IntPtr availableOut = (IntPtr)destination.Length;
				IntPtr availableIn = (IntPtr)source.Length;
				while ((int)availableOut > 0)
				{
					fixed (byte* ptr = &MemoryMarshal.GetReference<byte>(source))
					{
						fixed (byte* ptr3 = &MemoryMarshal.GetReference<byte>(destination))
						{
							byte* ptr2 = ptr;
							byte* ptr4 = ptr3;
							IntPtr totalOut;
							int num = global::Interop.Brotli.BrotliDecoderDecompressStream(_state, ref availableIn, &ptr2, ref availableOut, &ptr4, out totalOut);
							if (num == 0)
							{
								return (OperationStatus)3;
							}
							bytesConsumed += source.Length - (int)availableIn;
							bytesWritten += destination.Length - (int)availableOut;
							switch (num)
							{
							case 1:
								return (OperationStatus)0;
							case 3:
								return (OperationStatus)1;
							}
							source = source.Slice(source.Length - (int)availableIn);
							destination = destination.Slice(destination.Length - (int)availableOut);
							if (num == 2 && source.Length == 0)
							{
								return (OperationStatus)2;
							}
						}
					}
				}
				return (OperationStatus)1;
			}
			return (OperationStatus)0;
		}

		public unsafe static bool TryDecompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			fixed (byte* inBytes = &MemoryMarshal.GetReference<byte>(source))
			{
				fixed (byte* outBytes = &MemoryMarshal.GetReference<byte>(destination))
				{
					IntPtr availableOutput = (IntPtr)destination.Length;
					bool result = global::Interop.Brotli.BrotliDecoderDecompress((IntPtr)source.Length, inBytes, ref availableOutput, outBytes);
					bytesWritten = (int)availableOutput;
					return result;
				}
			}
		}
	}
	public struct BrotliEncoder : IDisposable
	{
		internal SafeBrotliEncoderHandle _state;

		private bool _disposed;

		public BrotliEncoder(int quality, int window)
		{
			_disposed = false;
			_state = global::Interop.Brotli.BrotliEncoderCreateInstance(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
			if (_state.IsInvalid)
			{
				throw new IOException("Failed to create BrotliEncoder instance");
			}
			SetQuality(quality);
			SetWindow(window);
		}

		internal void InitializeEncoder()
		{
			EnsureNotDisposed();
			_state = global::Interop.Brotli.BrotliEncoderCreateInstance(IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
			if (_state.IsInvalid)
			{
				throw new IOException("Failed to create BrotliEncoder instance");
			}
		}

		internal void EnsureInitialized()
		{
			EnsureNotDisposed();
			if (_state == null)
			{
				InitializeEncoder();
			}
		}

		public void Dispose()
		{
			_disposed = true;
			_state?.Dispose();
		}

		private void EnsureNotDisposed()
		{
			if (_disposed)
			{
				throw new ObjectDisposedException("BrotliEncoder", "Can not access a closed Encoder.");
			}
		}

		internal void SetQuality(int quality)
		{
			EnsureNotDisposed();
			if (_state == null || _state.IsInvalid || _state.IsClosed)
			{
				InitializeEncoder();
			}
			if (quality < 0 || quality > 11)
			{
				throw new ArgumentOutOfRangeException("quality", SR.Format("Provided BrotliEncoder Quality of {0} is not between the minimum value of {1} and the maximum value of {2}", quality, 0, 11));
			}
			if (!global::Interop.Brotli.BrotliEncoderSetParameter(_state, BrotliEncoderParameter.Quality, (uint)quality))
			{
				throw new InvalidOperationException(SR.Format("The BrotliEncoder {0} can not be changed at current encoder state.", "Quality"));
			}
		}

		internal void SetWindow(int window)
		{
			EnsureNotDisposed();
			if (_state == null || _state.IsInvalid || _state.IsClosed)
			{
				InitializeEncoder();
			}
			if (window < 10 || window > 24)
			{
				throw new ArgumentOutOfRangeException("window", SR.Format("Provided BrotliEncoder Window of {0} is not between the minimum value of {1} and the maximum value of {2}", window, 10, 24));
			}
			if (!global::Interop.Brotli.BrotliEncoderSetParameter(_state, BrotliEncoderParameter.LGWin, (uint)window))
			{
				throw new InvalidOperationException(SR.Format("The BrotliEncoder {0} can not be changed at current encoder state.", "Window"));
			}
		}

		public static int GetMaxCompressedLength(int length)
		{
			if (length < 0 || length > 2147483132)
			{
				throw new ArgumentOutOfRangeException("length");
			}
			if (length == 0)
			{
				return 1;
			}
			int num = length >> 24;
			int num2 = (((length & 0xFFFFFF) > 1048576) ? 4 : 3);
			int num3 = 2 + 4 * num + num2 + 1;
			return length + num3;
		}

		internal OperationStatus Flush(Memory<byte> destination, out int bytesWritten)
		{
			//IL_0003: 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)
			return Flush(destination.Span, out bytesWritten);
		}

		public OperationStatus Flush(Span<byte> destination, out int bytesWritten)
		{
			//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_000b: Unknown result type (might be due to invalid IL or missing references)
			int bytesConsumed;
			return Compress(ReadOnlySpan<byte>.Empty, destination, out bytesConsumed, out bytesWritten, BrotliEncoderOperation.Flush);
		}

		internal OperationStatus Compress(ReadOnlyMemory<byte> source, Memory<byte> destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			return Compress(source.Span, destination.Span, out bytesConsumed, out bytesWritten, isFinalBlock);
		}

		public OperationStatus Compress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesConsumed, out int bytesWritten, bool isFinalBlock)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			return Compress(source, destination, out bytesConsumed, out bytesWritten, isFinalBlock ? BrotliEncoderOperation.Finish : BrotliEncoderOperation.Process);
		}

		internal unsafe OperationStatus Compress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesConsumed, out int bytesWritten, BrotliEncoderOperation operation)
		{
			//IL_002c: 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_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			EnsureInitialized();
			bytesWritten = 0;
			bytesConsumed = 0;
			IntPtr availableOut = (IntPtr)destination.Length;
			IntPtr availableIn = (IntPtr)source.Length;
			while ((int)availableOut > 0)
			{
				fixed (byte* ptr = &MemoryMarshal.GetReference<byte>(source))
				{
					fixed (byte* ptr3 = &MemoryMarshal.GetReference<byte>(destination))
					{
						byte* ptr2 = ptr;
						byte* ptr4 = ptr3;
						if (!global::Interop.Brotli.BrotliEncoderCompressStream(_state, operation, ref availableIn, &ptr2, ref availableOut, &ptr4, out var _))
						{
							return (OperationStatus)3;
						}
						bytesConsumed += source.Length - (int)availableIn;
						bytesWritten += destination.Length - (int)availableOut;
						if ((int)availableOut == destination.Length && !global::Interop.Brotli.BrotliEncoderHasMoreOutput(_state) && (int)availableIn == 0)
						{
							return (OperationStatus)0;
						}
						source = source.Slice(source.Length - (int)availableIn);
						destination = destination.Slice(destination.Length - (int)availableOut);
					}
				}
			}
			return (OperationStatus)1;
		}

		public static bool TryCompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			return TryCompress(source, destination, out bytesWritten, 11, 22);
		}

		public unsafe static bool TryCompress(ReadOnlySpan<byte> source, Span<byte> destination, out int bytesWritten, int quality, int window)
		{
			//IL_0067: 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 (quality < 0 || quality > 11)
			{
				throw new ArgumentOutOfRangeException("quality", SR.Format("Provided BrotliEncoder Quality of {0} is not between the minimum value of {1} and the maximum value of {2}", quality, 0, 11));
			}
			if (window < 10 || window > 24)
			{
				throw new ArgumentOutOfRangeException("window", SR.Format("Provided BrotliEncoder Window of {0} is not between the minimum value of {1} and the maximum value of {2}", window, 10, 24));
			}
			fixed (byte* inBytes = &MemoryMarshal.GetReference<byte>(source))
			{
				fixed (byte* outBytes = &MemoryMarshal.GetReference<byte>(destination))
				{
					IntPtr availableOutput = (IntPtr)destination.Length;
					bool result = global::Interop.Brotli.BrotliEncoderCompress(quality, window, 0, (IntPtr)source.Length, inBytes, ref availableOutput, outBytes);
					bytesWritten = (int)availableOutput;
					return result;
				}
			}
		}
	}
	internal enum BrotliEncoderOperation
	{
		Process,
		Flush,
		Finish,
		EmitMetadata
	}
	internal enum BrotliEncoderParameter
	{
		Mode,
		Quality,
		LGWin,
		LGBlock,
		LCModeling,
		SizeHint
	}
	internal enum BlockType
	{
		Uncompressed,
		Static,
		Dynamic
	}
	internal sealed class CopyEncoder
	{
		private const int PaddingSize = 5;

		private const int MaxUncompressedBlockSize = 65536;

		public void GetBlock(DeflateInput input, OutputBuffer output, bool isFinal)
		{
			int num = 0;
			if (input != null)
			{
				num = Math.Min(input.Count, output.FreeBytes - 5 - output.BitsInBuffer);
				if (num > 65531)
				{
					num = 65531;
				}
			}
			if (isFinal)
			{
				output.WriteBits(3, 1u);
			}
			else
			{
				output.WriteBits(3, 0u);
			}
			output.FlushBits();
			WriteLenNLen((ushort)num, output);
			if (input != null && num > 0)
			{
				output.WriteBytes(input.Buffer, input.StartIndex, num);
				input.ConsumeBytes(num);
			}
		}

		private void WriteLenNLen(ushort len, OutputBuffer output)
		{
			output.WriteUInt16(len);
			ushort value = (ushort)(~len);
			output.WriteUInt16(value);
		}
	}
	internal sealed class DeflateInput
	{
		internal readonly struct InputState
		{
			internal readonly int _count;

			internal readonly int _startIndex;

			internal InputState(int count, int startIndex)
			{
				_count = count;
				_startIndex = startIndex;
			}
		}

		internal byte[] Buffer { get; set; }

		internal int Count { get; set; }

		internal int StartIndex { get; set; }

		internal void ConsumeBytes(int n)
		{
			StartIndex += n;
			Count -= n;
		}

		internal InputState DumpState()
		{
			return new InputState(Count, StartIndex);
		}

		internal void RestoreState(InputState state)
		{
			Count = state._count;
			StartIndex = state._startIndex;
		}
	}
	internal sealed class DeflateManagedStream : Stream
	{
		internal const int DefaultBufferSize = 8192;

		private Stream _stream;

		private CompressionMode _mode;

		private bool _leaveOpen;

		private System.IO.Compression.InflaterManaged _inflater;

		private DeflaterManaged _deflater;

		private byte[] _buffer;

		private int _asyncOperations;

		private IFileFormatWriter _formatWriter;

		private bool _wroteHeader;

		private bool _wroteBytes;

		public override bool CanRead
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				if (_stream == null)
				{
					return false;
				}
				if ((int)_mode == 0)
				{
					return _stream.CanRead;
				}
				return false;
			}
		}

		public override bool CanWrite
		{
			get
			{
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Invalid comparison between Unknown and I4
				if (_stream == null)
				{
					return false;
				}
				if ((int)_mode == 1)
				{
					return _stream.CanWrite;
				}
				return false;
			}
		}

		public override bool CanSeek => false;

		public override long Length
		{
			get
			{
				throw new NotSupportedException("This operation is not supported.");
			}
		}

		public override long Position
		{
			get
			{
				throw new NotSupportedException("This operation is not supported.");
			}
			set
			{
				throw new NotSupportedException("This operation is not supported.");
			}
		}

		internal DeflateManagedStream(Stream stream, ZipArchiveEntry.CompressionMethodValues method)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			if (!stream.CanRead)
			{
				throw new ArgumentException("Stream does not support reading.", "stream");
			}
			InitializeInflater(stream, leaveOpen: false, null, method);
		}

		internal void InitializeInflater(Stream stream, bool leaveOpen, IFileFormatReader reader = null, ZipArchiveEntry.CompressionMethodValues method = ZipArchiveEntry.CompressionMethodValues.Deflate)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			if (!stream.CanRead)
			{
				throw new ArgumentException("Stream does not support reading.", "stream");
			}
			_inflater = new System.IO.Compression.InflaterManaged(reader, method == ZipArchiveEntry.CompressionMethodValues.Deflate64);
			_stream = stream;
			_mode = (CompressionMode)0;
			_leaveOpen = leaveOpen;
			_buffer = new byte[8192];
		}

		internal void SetFileFormatWriter(IFileFormatWriter writer)
		{
			if (writer != null)
			{
				_formatWriter = writer;
			}
		}

		public override void Flush()
		{
			EnsureNotDisposed();
		}

		public override Task FlushAsync(CancellationToken cancellationToken)
		{
			EnsureNotDisposed();
			if (!cancellationToken.IsCancellationRequested)
			{
				return Task.CompletedTask;
			}
			return Task.FromCanceled(cancellationToken);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException("This operation is not supported.");
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException("This operation is not supported.");
		}

		public override int Read(byte[] array, int offset, int count)
		{
			EnsureDecompressionMode();
			ValidateParameters(array, offset, count);
			EnsureNotDisposed();
			int num = offset;
			int num2 = count;
			while (true)
			{
				int num3 = _inflater.Inflate(array, num, num2);
				num += num3;
				num2 -= num3;
				if (num2 == 0 || _inflater.Finished())
				{
					break;
				}
				int num4 = _stream.Read(_buffer, 0, _buffer.Length);
				if (num4 <= 0)
				{
					break;
				}
				if (num4 > _buffer.Length)
				{
					throw new InvalidDataException("Found invalid data while decoding.");
				}
				_inflater.SetInput(_buffer, 0, num4);
			}
			return count - num2;
		}

		private void ValidateParameters(byte[] array, int offset, int count)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset");
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count");
			}
			if (array.Length - offset < count)
			{
				throw new ArgumentException("Offset plus count is larger than the length of target array.");
			}
		}

		private void EnsureNotDisposed()
		{
			if (_stream == null)
			{
				ThrowStreamClosedException();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void ThrowStreamClosedException()
		{
			throw new ObjectDisposedException(null, "Can not access a closed Stream.");
		}

		private void EnsureDecompressionMode()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			if ((int)_mode != 0)
			{
				ThrowCannotReadFromDeflateManagedStreamException();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void ThrowCannotReadFromDeflateManagedStreamException()
		{
			throw new InvalidOperationException("Reading from the compression stream is not supported.");
		}

		private void EnsureCompressionMode()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Invalid comparison between Unknown and I4
			if ((int)_mode != 1)
			{
				ThrowCannotWriteToDeflateManagedStreamException();
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void ThrowCannotWriteToDeflateManagedStreamException()
		{
			throw new InvalidOperationException("Writing to the compression stream is not supported.");
		}

		public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
		{
			return System.Threading.Tasks.TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
		}

		public override int EndRead(IAsyncResult asyncResult)
		{
			return System.Threading.Tasks.TaskToApm.End<int>(asyncResult);
		}

		public override Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
		{
			EnsureDecompressionMode();
			if (_asyncOperations != 0)
			{
				throw new InvalidOperationException("Only one asynchronous reader or writer is allowed time at one time.");
			}
			ValidateParameters(array, offset, count);
			EnsureNotDisposed();
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled<int>(cancellationToken);
			}
			Interlocked.Increment(ref _asyncOperations);
			Task<int> task = null;
			try
			{
				int num = _inflater.Inflate(array, offset, count);
				if (num != 0)
				{
					return Task.FromResult(num);
				}
				if (_inflater.Finished())
				{
					return Task.FromResult(0);
				}
				task = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
				if (task == null)
				{
					throw new InvalidOperationException("Stream does not support reading.");
				}
				return ReadAsyncCore(task, array, offset, count, cancellationToken);
			}
			finally
			{
				if (task == null)
				{
					Interlocked.Decrement(ref _asyncOperations);
				}
			}
		}

		private async Task<int> ReadAsyncCore(Task<int> readTask, byte[] array, int offset, int count, CancellationToken cancellationToken)
		{
			try
			{
				int num;
				while (true)
				{
					num = await readTask.ConfigureAwait(continueOnCapturedContext: false);
					EnsureNotDisposed();
					if (num <= 0)
					{
						return 0;
					}
					if (num > _buffer.Length)
					{
						throw new InvalidDataException("Found invalid data while decoding.");
					}
					cancellationToken.ThrowIfCancellationRequested();
					_inflater.SetInput(_buffer, 0, num);
					num = _inflater.Inflate(array, offset, count);
					if (num != 0 || _inflater.Finished())
					{
						break;
					}
					readTask = _stream.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
					if (readTask == null)
					{
						throw new InvalidOperationException("Stream does not support reading.");
					}
				}
				return num;
			}
			finally
			{
				Interlocked.Decrement(ref _asyncOperations);
			}
		}

		public override void Write(byte[] array, int offset, int count)
		{
			EnsureCompressionMode();
			ValidateParameters(array, offset, count);
			EnsureNotDisposed();
			DoMaintenance(array, offset, count);
			WriteDeflaterOutput();
			_deflater.SetInput(array, offset, count);
			WriteDeflaterOutput();
		}

		private void WriteDeflaterOutput()
		{
			while (!_deflater.NeedsInput())
			{
				int deflateOutput = _deflater.GetDeflateOutput(_buffer);
				if (deflateOutput > 0)
				{
					_stream.Write(_buffer, 0, deflateOutput);
				}
			}
		}

		private void DoMaintenance(byte[] array, int offset, int count)
		{
			if (count <= 0)
			{
				return;
			}
			_wroteBytes = true;
			if (_formatWriter != null)
			{
				if (!_wroteHeader)
				{
					byte[] header = _formatWriter.GetHeader();
					_stream.Write(header, 0, header.Length);
					_wroteHeader = true;
				}
				_formatWriter.UpdateWithBytesRead(array, offset, count);
			}
		}

		private void PurgeBuffers(bool disposing)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Invalid comparison between Unknown and I4
			if (!disposing || _stream == null)
			{
				return;
			}
			Flush();
			if ((int)_mode != 1)
			{
				return;
			}
			if (_wroteBytes)
			{
				WriteDeflaterOutput();
				bool flag;
				do
				{
					flag = _deflater.Finish(_buffer, out var bytesRead);
					if (bytesRead > 0)
					{
						_stream.Write(_buffer, 0, bytesRead);
					}
				}
				while (!flag);
			}
			else
			{
				int bytesRead2;
				while (!_deflater.Finish(_buffer, out bytesRead2))
				{
				}
			}
			if (_formatWriter != null && _wroteHeader)
			{
				byte[] footer = _formatWriter.GetFooter();
				_stream.Write(footer, 0, footer.Length);
			}
		}

		protected override void Dispose(bool disposing)
		{
			try
			{
				PurgeBuffers(disposing);
			}
			finally
			{
				try
				{
					if (disposing && !_leaveOpen && _stream != null)
					{
						_stream.Dispose();
					}
				}
				finally
				{
					_stream = null;
					try
					{
						_deflater?.Dispose();
						_inflater?.Dispose();
					}
					finally
					{
						_deflater = null;
						_inflater = null;
						base.Dispose(disposing);
					}
				}
			}
		}

		public override Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken)
		{
			EnsureCompressionMode();
			if (_asyncOperations != 0)
			{
				throw new InvalidOperationException("Only one asynchronous reader or writer is allowed time at one time.");
			}
			ValidateParameters(array, offset, count);
			EnsureNotDisposed();
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled<int>(cancellationToken);
			}
			return WriteAsyncCore(array, offset, count, cancellationToken);
		}

		private async Task WriteAsyncCore(byte[] array, int offset, int count, CancellationToken cancellationToken)
		{
			Interlocked.Increment(ref _asyncOperations);
			try
			{
				await base.WriteAsync(array, offset, count, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			finally
			{
				Interlocked.Decrement(ref _asyncOperations);
			}
		}

		public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
		{
			return System.Threading.Tasks.TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState);
		}

		public override void EndWrite(IAsyncResult asyncResult)
		{
			System.Threading.Tasks.TaskToApm.End(asyncResult);
		}
	}
	internal sealed class DeflaterManaged : IDisposable
	{
		private enum DeflaterState
		{
			NotStarted,
			SlowDownForIncompressible1,
			SlowDownForIncompressible2,
			StartingSmallData,
			CompressThenCheck,
			CheckingForIncompressible,
			HandlingSmallData
		}

		private const int MinBlockSize = 256;

		private const int MaxHeaderFooterGoo = 120;

		private const int CleanCopySize = 8072;

		private const double BadCompressionThreshold = 1.0;

		private readonly FastEncoder _deflateEncoder;

		private readonly CopyEncoder _copyEncoder;

		private readonly DeflateInput _input;

		private readonly OutputBuffer _output;

		private DeflaterState _processingState;

		private DeflateInput _inputFromHistory;

		internal DeflaterManaged()
		{
			_deflateEncoder = new FastEncoder();
			_copyEncoder = new CopyEncoder();
			_input = new DeflateInput();
			_output = new OutputBuffer();
			_processingState = DeflaterState.NotStarted;
		}

		internal bool NeedsInput()
		{
			if (_input.Count == 0)
			{
				return _deflateEncoder.BytesInHistory == 0;
			}
			return false;
		}

		internal void SetInput(byte[] inputBuffer, int startIndex, int count)
		{
			_input.Buffer = inputBuffer;
			_input.Count = count;
			_input.StartIndex = startIndex;
			if (count > 0 && count < 256)
			{
				switch (_processingState)
				{
				case DeflaterState.NotStarted:
				case DeflaterState.CheckingForIncompressible:
					_processingState = DeflaterState.StartingSmallData;
					break;
				case DeflaterState.CompressThenCheck:
					_processingState = DeflaterState.HandlingSmallData;
					break;
				}
			}
		}

		internal int GetDeflateOutput(byte[] outputBuffer)
		{
			_output.UpdateBuffer(outputBuffer);
			switch (_processingState)
			{
			case DeflaterState.NotStarted:
			{
				DeflateInput.InputState state3 = _input.DumpState();
				OutputBuffer.BufferState state4 = _output.DumpState();
				_deflateEncoder.GetBlockHeader(_output);
				_deflateEncoder.GetCompressedData(_input, _output);
				if (!UseCompressed(_deflateEncoder.LastCompressionRatio))
				{
					_input.RestoreState(state3);
					_output.RestoreState(state4);
					_copyEncoder.GetBlock(_input, _output, isFinal: false);
					FlushInputWindows();
					_processingState = DeflaterState.CheckingForIncompressible;
				}
				else
				{
					_processingState = DeflaterState.CompressThenCheck;
				}
				break;
			}
			case DeflaterState.CompressThenCheck:
				_deflateEncoder.GetCompressedData(_input, _output);
				if (!UseCompressed(_deflateEncoder.LastCompressionRatio))
				{
					_processingState = DeflaterState.SlowDownForIncompressible1;
					_inputFromHistory = _deflateEncoder.UnprocessedInput;
				}
				break;
			case DeflaterState.SlowDownForIncompressible1:
				_deflateEncoder.GetBlockFooter(_output);
				_processingState = DeflaterState.SlowDownForIncompressible2;
				goto case DeflaterState.SlowDownForIncompressible2;
			case DeflaterState.SlowDownForIncompressible2:
				if (_inputFromHistory.Count > 0)
				{
					_copyEncoder.GetBlock(_inputFromHistory, _output, isFinal: false);
				}
				if (_inputFromHistory.Count == 0)
				{
					_deflateEncoder.FlushInput();
					_processingState = DeflaterState.CheckingForIncompressible;
				}
				break;
			case DeflaterState.CheckingForIncompressible:
			{
				DeflateInput.InputState state = _input.DumpState();
				OutputBuffer.BufferState state2 = _output.DumpState();
				_deflateEncoder.GetBlock(_input, _output, 8072);
				if (!UseCompressed(_deflateEncoder.LastCompressionRatio))
				{
					_input.RestoreState(state);
					_output.RestoreState(state2);
					_copyEncoder.GetBlock(_input, _output, isFinal: false);
					FlushInputWindows();
				}
				break;
			}
			case DeflaterState.StartingSmallData:
				_deflateEncoder.GetBlockHeader(_output);
				_processingState = DeflaterState.HandlingSmallData;
				goto case DeflaterState.HandlingSmallData;
			case DeflaterState.HandlingSmallData:
				_deflateEncoder.GetCompressedData(_input, _output);
				break;
			}
			return _output.BytesWritten;
		}

		internal bool Finish(byte[] outputBuffer, out int bytesRead)
		{
			if (_processingState == DeflaterState.NotStarted)
			{
				bytesRead = 0;
				return true;
			}
			_output.UpdateBuffer(outputBuffer);
			if (_processingState == DeflaterState.CompressThenCheck || _processingState == DeflaterState.HandlingSmallData || _processingState == DeflaterState.SlowDownForIncompressible1)
			{
				_deflateEncoder.GetBlockFooter(_output);
			}
			WriteFinal();
			bytesRead = _output.BytesWritten;
			return true;
		}

		private bool UseCompressed(double ratio)
		{
			return ratio <= 1.0;
		}

		private void FlushInputWindows()
		{
			_deflateEncoder.FlushInput();
		}

		private void WriteFinal()
		{
			_copyEncoder.GetBlock(null, _output, isFinal: true);
		}

		public void Dispose()
		{
		}
	}
	internal sealed class FastEncoder
	{
		private readonly FastEncoderWindow _inputWindow;

		private readonly Match _currentMatch;

		private double _lastCompressionRatio;

		internal int BytesInHistory => _inputWindow.BytesAvailable;

		internal DeflateInput UnprocessedInput => _inputWindow.UnprocessedInput;

		internal double LastCompressionRatio => _lastCompressionRatio;

		public FastEncoder()
		{
			_inputWindow = new FastEncoderWindow();
			_currentMatch = new Match();
		}

		internal void FlushInput()
		{
			_inputWindow.FlushWindow();
		}

		internal void GetBlock(DeflateInput input, OutputBuffer output, int maxBytesToCopy)
		{
			WriteDeflatePreamble(output);
			GetCompressedOutput(input, output, maxBytesToCopy);
			WriteEndOfBlock(output);
		}

		internal void GetCompressedData(DeflateInput input, OutputBuffer output)
		{
			GetCompressedOutput(input, output, -1);
		}

		internal void GetBlockHeader(OutputBuffer output)
		{
			WriteDeflatePreamble(output);
		}

		internal void GetBlockFooter(OutputBuffer output)
		{
			WriteEndOfBlock(output);
		}

		private void GetCompressedOutput(DeflateInput input, OutputBuffer output, int maxBytesToCopy)
		{
			int bytesWritten = output.BytesWritten;
			int num = 0;
			int num2 = BytesInHistory + input.Count;
			do
			{
				int num3 = ((input.Count < _inputWindow.FreeWindowSpace) ? input.Count : _inputWindow.FreeWindowSpace);
				if (maxBytesToCopy >= 1)
				{
					num3 = Math.Min(num3, maxBytesToCopy - num);
				}
				if (num3 > 0)
				{
					_inputWindow.CopyBytes(input.Buffer, input.StartIndex, num3);
					input.ConsumeBytes(num3);
					num += num3;
				}
				GetCompressedOutput(output);
			}
			while (SafeToWriteTo(output) && InputAvailable(input) && (maxBytesToCopy < 1 || num < maxBytesToCopy));
			int num4 = output.BytesWritten - bytesWritten;
			int num5 = BytesInHistory + input.Count;
			int num6 = num2 - num5;
			if (num4 != 0)
			{
				_lastCompressionRatio = (double)num4 / (double)num6;
			}
		}

		private void GetCompressedOutput(OutputBuffer output)
		{
			while (_inputWindow.BytesAvailable > 0 && SafeToWriteTo(output))
			{
				_inputWindow.GetNextSymbolOrMatch(_currentMatch);
				if (_currentMatch.State == MatchState.HasSymbol)
				{
					WriteChar(_currentMatch.Symbol, output);
					continue;
				}
				if (_currentMatch.State == MatchState.HasMatch)
				{
					WriteMatch(_currentMatch.Length, _currentMatch.Position, output);
					continue;
				}
				WriteChar(_currentMatch.Symbol, output);
				WriteMatch(_currentMatch.Length, _currentMatch.Position, output);
			}
		}

		private bool InputAvailable(DeflateInput input)
		{
			if (input.Count <= 0)
			{
				return BytesInHistory > 0;
			}
			return true;
		}

		private bool SafeToWriteTo(OutputBuffer output)
		{
			return output.FreeBytes > 16;
		}

		private void WriteEndOfBlock(OutputBuffer output)
		{
			uint num = FastEncoderStatics.FastEncoderLiteralCodeInfo[256];
			int n = (int)(num & 0x1F);
			output.WriteBits(n, num >> 5);
		}

		internal static void WriteMatch(int matchLen, int matchPos, OutputBuffer output)
		{
			uint num = FastEncoderStatics.FastEncoderLiteralCodeInfo[254 + matchLen];
			int num2 = (int)(num & 0x1F);
			if (num2 <= 16)
			{
				output.WriteBits(num2, num >> 5);
			}
			else
			{
				output.WriteBits(16, (num >> 5) & 0xFFFFu);
				output.WriteBits(num2 - 16, num >> 21);
			}
			num = FastEncoderStatics.FastEncoderDistanceCodeInfo[FastEncoderStatics.GetSlot(matchPos)];
			output.WriteBits((int)(num & 0xF), num >> 8);
			int num3 = (int)((num >> 4) & 0xF);
			if (num3 != 0)
			{
				output.WriteBits(num3, (uint)matchPos & FastEncoderStatics.BitMask[num3]);
			}
		}

		internal static void WriteChar(byte b, OutputBuffer output)
		{
			uint num = FastEncoderStatics.FastEncoderLiteralCodeInfo[b];
			output.WriteBits((int)(num & 0x1F), num >> 5);
		}

		internal static void WriteDeflatePreamble(OutputBuffer output)
		{
			output.WriteBytes(FastEncoderStatics.FastEncoderTreeStructureData, 0, FastEncoderStatics.FastEncoderTreeStructureData.Length);
			output.WriteBits(9, 34u);
		}
	}
	internal static class FastEncoderStatics
	{
		internal static readonly byte[] FastEncoderTreeStructureData = new byte[98]
		{
			236, 189, 7, 96, 28, 73, 150, 37, 38, 47,
			109, 202, 123, 127, 74, 245, 74, 215, 224, 116,
			161, 8, 128, 96, 19, 36, 216, 144, 64, 16,
			236, 193, 136, 205, 230, 146, 236, 29, 105, 71,
			35, 41, 171, 42, 129, 202, 101, 86, 101, 93,
			102, 22, 64, 204, 237, 157, 188, 247, 222, 123,
			239, 189, 247, 222, 123, 239, 189, 247, 186, 59,
			157, 78, 39, 247, 223, 255, 63, 92, 102, 100,
			1, 108, 246, 206, 74, 218, 201, 158, 33, 128,
			170, 200, 31, 63, 126, 124, 31, 63
		};

		internal static readonly byte[] BFinalFastEncoderTreeStructureData = new byte[98]
		{
			237, 189, 7, 96, 28, 73, 150, 37, 38, 47,
			109, 202, 123, 127, 74, 245, 74, 215, 224, 116,
			161, 8, 128, 96, 19, 36, 216, 144, 64, 16,
			236, 193, 136, 205, 230, 146, 236, 29, 105, 71,
			35, 41, 171, 42, 129, 202, 101, 86, 101, 93,
			102, 22, 64, 204, 237, 157, 188, 247, 222, 123,
			239, 189, 247, 222, 123, 239, 189, 247, 186, 59,
			157, 78, 39, 247, 223, 255, 63, 92, 102, 100,
			1, 108, 246, 206, 74, 218, 201, 158, 33, 128,
			170, 200, 31, 63, 126, 124, 31, 63
		};

		internal static readonly uint[] FastEncoderLiteralCodeInfo = new uint[513]
		{
			55278u, 317422u, 186350u, 448494u, 120814u, 382958u, 251886u, 514030u, 14318u, 51180u,
			294u, 276462u, 145390u, 407534u, 79854u, 341998u, 210926u, 473070u, 47086u, 309230u,
			178158u, 440302u, 112622u, 374766u, 243694u, 505838u, 30702u, 292846u, 161774u, 423918u,
			6125u, 96238u, 1318u, 358382u, 9194u, 116716u, 227310u, 489454u, 137197u, 25578u,
			2920u, 3817u, 23531u, 5098u, 1127u, 7016u, 3175u, 12009u, 1896u, 5992u,
			3944u, 7913u, 8040u, 16105u, 21482u, 489u, 232u, 8681u, 4585u, 4328u,
			12777u, 13290u, 2280u, 63470u, 325614u, 6376u, 2537u, 1256u, 10729u, 5352u,
			6633u, 29674u, 56299u, 3304u, 15339u, 194542u, 14825u, 3050u, 1513u, 19434u,
			9705u, 10220u, 5609u, 13801u, 3561u, 11242u, 75756u, 48107u, 456686u, 129006u,
			42988u, 31723u, 391150u, 64491u, 260078u, 522222u, 4078u, 806u, 615u, 2663u,
			1639u, 1830u, 7400u, 744u, 3687u, 166u, 108524u, 11753u, 1190u, 359u,
			2407u, 678u, 1383u, 71661u, 1702u, 422u, 1446u, 3431u, 4840u, 2792u,
			7657u, 6888u, 2027u, 202733u, 26604u, 38893u, 169965u, 266222u, 135150u, 397294u,
			69614u, 331758u, 200686u, 462830u, 36846u, 298990u, 167918u, 430062u, 102382u, 364526u,
			233454u, 495598u, 20462u, 282606u, 151534u, 413678u, 85998u, 348142u, 217070u, 479214u,
			53230u, 315374u, 184302u, 446446u, 118766u, 380910u, 249838u, 511982u, 12270u, 274414u,
			143342u, 405486u, 77806u, 339950u, 208878u, 471022u, 45038u, 307182u, 176110u, 438254u,
			110574u, 372718u, 241646u, 503790u, 28654u, 290798u, 159726u, 421870u, 94190u, 356334u,
			225262u, 487406u, 61422u, 323566u, 192494u, 454638u, 126958u, 389102u, 258030u, 520174u,
			8174u, 270318u, 139246u, 401390u, 73710u, 335854u, 204782u, 466926u, 40942u, 303086u,
			172014u, 434158u, 106478u, 368622u, 237550u, 499694u, 24558u, 286702u, 155630u, 417774u,
			90094u, 352238u, 221166u, 483310u, 57326u, 319470u, 188398u, 450542u, 122862u, 385006u,
			253934u, 516078u, 16366u, 278510u, 147438u, 409582u, 81902u, 344046u, 212974u, 475118u,
			49134u, 311278u, 180206u, 442350u, 114670u, 376814u, 245742u, 507886u, 32750u, 294894u,
			163822u, 425966u, 98286u, 104429u, 235501u, 22509u, 360430u, 153581u, 229358u, 88045u,
			491502u, 219117u, 65518u, 327662u, 196590u, 458734u, 131054u, 132u, 3u, 388u,
			68u, 324u, 197u, 709u, 453u, 966u, 1990u, 38u, 1062u, 935u,
			2983u, 1959u, 4007u, 551u, 1575u, 2599u, 3623u, 104u, 2152u, 4200u,
			6248u, 873u, 4969u, 9065u, 13161u, 1770u, 9962u, 18154u, 26346u, 5867u,
			14059u, 22251u, 30443u, 38635u, 46827u, 55019u, 63211u, 15852u, 32236u, 48620u,
			65004u, 81388u, 97772u, 114156u, 130540u, 27629u, 60397u, 93165u, 125933u, 158701u,
			191469u, 224237u, 257005u, 1004u, 17388u, 33772u, 50156u, 66540u, 82924u, 99308u,
			115692u, 7150u, 39918u, 72686u, 105454u, 138222u, 170990u, 203758u, 236526u, 269294u,
			302062u, 334830u, 367598u, 400366u, 433134u, 465902u, 498670u, 92144u, 223216u, 354288u,
			485360u, 616432u, 747504u, 878576u, 1009648u, 1140720u, 1271792u, 1402864u, 1533936u, 1665008u,
			1796080u, 1927152u, 2058224u, 34799u, 100335u, 165871u, 231407u, 296943u, 362479u, 428015u,
			493551u, 559087u, 624623u, 690159u, 755695u, 821231u, 886767u, 952303u, 1017839u, 59376u,
			190448u, 321520u, 452592u, 583664u, 714736u, 845808u, 976880u, 1107952u, 1239024u, 1370096u,
			1501168u, 1632240u, 1763312u, 1894384u, 2025456u, 393203u, 917491u, 1441779u, 1966067u, 2490355u,
			3014643u, 3538931u, 4063219u, 4587507u, 5111795u, 5636083u, 6160371u, 6684659u, 7208947u, 7733235u,
			8257523u, 8781811u, 9306099u, 9830387u, 10354675u, 10878963u, 11403251u, 11927539u, 12451827u, 12976115u,
			13500403u, 14024691u, 14548979u, 15073267u, 15597555u, 16121843u, 16646131u, 262131u, 786419u, 1310707u,
			1834995u, 2359283u, 2883571u, 3407859u, 3932147u, 4456435u, 4980723u, 5505011u, 6029299u, 6553587u,
			7077875u, 7602163u, 8126451u, 8650739u, 9175027u, 9699315u, 10223603u, 10747891u, 11272179u, 11796467u,
			12320755u, 12845043u, 13369331u, 13893619u, 14417907u, 14942195u, 15466483u, 15990771u, 16515059u, 524275u,
			1048563u, 1572851u, 2097139u, 2621427u, 3145715u, 3670003u, 4194291u, 4718579u, 5242867u, 5767155u,
			6291443u, 6815731u, 7340019u, 7864307u, 8388595u, 8912883u, 9437171u, 9961459u, 10485747u, 11010035u,
			11534323u, 12058611u, 12582899u, 13107187u, 13631475u, 14155763u, 14680051u, 15204339u, 15728627u, 16252915u,
			16777203u, 124913u, 255985u, 387057u, 518129u, 649201u, 780273u, 911345u, 1042417u, 1173489u,
			1304561u, 1435633u, 1566705u, 1697777u, 1828849u, 1959921u, 2090993u, 2222065u, 2353137u, 2484209u,
			2615281u, 2746353u, 2877425u, 3008497u, 3139569u, 3270641u, 3401713u, 3532785u, 3663857u, 3794929u,
			3926001u, 4057073u, 18411u
		};

		internal static readonly uint[] FastEncoderDistanceCodeInfo = new uint[32]
		{
			3846u, 130826u, 261899u, 524043u, 65305u, 16152u, 48936u, 32552u, 7991u, 24375u,
			3397u, 12102u, 84u, 7509u, 2148u, 869u, 1140u, 4981u, 3204u, 644u,
			2708u, 1684u, 3748u, 420u, 2484u, 2997u, 1476u, 7109u, 2005u, 6101u,
			0u, 256u
		};

		internal static readonly uint[] BitMask = new uint[16]
		{
			0u, 1u, 3u, 7u, 15u, 31u, 63u, 127u, 255u, 511u,
			1023u, 2047u, 4095u, 8191u, 16383u, 32767u
		};

		internal static readonly byte[] ExtraLengthBits = new byte[29]
		{
			0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
			1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
			4, 4, 4, 4, 5, 5, 5, 5, 0
		};

		internal static readonly byte[] ExtraDistanceBits = new byte[32]
		{
			0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
			4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
			9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
			0, 0
		};

		internal const int NumChars = 256;

		internal const int NumLengthBaseCodes = 29;

		internal const int NumDistBaseCodes = 30;

		internal const uint FastEncoderPostTreeBitBuf = 34u;

		internal const int FastEncoderPostTreeBitCount = 9;

		internal const uint NoCompressionHeader = 0u;

		internal const int NoCompressionHeaderBitCount = 3;

		internal const uint BFinalNoCompressionHeader = 1u;

		internal const int BFinalNoCompressionHeaderBitCount = 3;

		internal const int MaxCodeLen = 16;

		private static readonly byte[] s_distLookup = CreateDistanceLookup();

		private static byte[] CreateDistanceLookup()
		{
			byte[] array = new byte[512];
			int num = 0;
			int i;
			for (i = 0; i < 16; i++)
			{
				for (int j = 0; j < 1 << (int)ExtraDistanceBits[i]; j++)
				{
					array[num++] = (byte)i;
				}
			}
			num >>= 7;
			for (; i < 30; i++)
			{
				for (int k = 0; k < 1 << ExtraDistanceBits[i] - 7; k++)
				{
					array[256 + num++] = (byte)i;
				}
			}
			return array;
		}

		internal static int GetSlot(int pos)
		{
			return s_distLookup[(pos < 256) ? pos : (256 + (pos >> 7))];
		}

		public static uint BitReverse(uint code, int length)
		{
			uint num = 0u;
			do
			{
				num |= code & 1u;
				num <<= 1;
				code >>= 1;
			}
			while (--length > 0);
			return num >> 1;
		}
	}
	internal sealed class FastEncoderWindow
	{
		private byte[] _window;

		private int _bufPos;

		private int _bufEnd;

		private const int FastEncoderHashShift = 4;

		private const int FastEncoderHashtableSize = 2048;

		private const int FastEncoderHashMask = 2047;

		private const int FastEncoderWindowSize = 8192;

		private const int FastEncoderWindowMask = 8191;

		private const int FastEncoderMatch3DistThreshold = 16384;

		internal const int MaxMatch = 258;

		internal const int MinMatch = 3;

		private const int SearchDepth = 32;

		private const int GoodLength = 4;

		private const int NiceLength = 32;

		private const int LazyMatchThreshold = 6;

		private ushort[] _prev;

		private ushort[] _lookup;

		public int BytesAvailable => _bufEnd - _bufPos;

		public DeflateInput UnprocessedInput => new DeflateInput
		{
			Buffer = _window,
			StartIndex = _bufPos,
			Count = _bufEnd - _bufPos
		};

		public int FreeWindowSpace => 16384 - _bufEnd;

		public FastEncoderWindow()
		{
			ResetWindow();
		}

		public void FlushWindow()
		{
			ResetWindow();
		}

		private void ResetWindow()
		{
			_window = new byte[16646];
			_prev = new ushort[8450];
			_lookup = new ushort[2048];
			_bufPos = 8192;
			_bufEnd = _bufPos;
		}

		public void CopyBytes(byte[] inputBuffer, int startIndex, int count)
		{
			Array.Copy(inputBuffer, startIndex, _window, _bufEnd, count);
			_bufEnd += count;
		}

		public void MoveWindows()
		{
			Array.Copy(_window, _bufPos - 8192, _window, 0, 8192);
			for (int i = 0; i < 2048; i++)
			{
				int num = _lookup[i] - 8192;
				if (num <= 0)
				{
					_lookup[i] = 0;
				}
				else
				{
					_lookup[i] = (ushort)num;
				}
			}
			for (int i = 0; i < 8192; i++)
			{
				long num2 = (long)_prev[i] - 8192L;
				if (num2 <= 0)
				{
					_prev[i] = 0;
				}
				else
				{
					_prev[i] = (ushort)num2;
				}
			}
			_bufPos = 8192;
			_bufEnd = _bufPos;
		}

		private uint HashValue(uint hash, byte b)
		{
			return (hash << 4) ^ b;
		}

		private uint InsertString(ref uint hash)
		{
			hash = HashValue(hash, _window[_bufPos + 2]);
			uint num = _lookup[hash & 0x7FF];
			_lookup[hash & 0x7FF] = (ushort)_bufPos;
			_prev[_bufPos & 0x1FFF] = (ushort)num;
			return num;
		}

		private void InsertStrings(ref uint hash, int matchLen)
		{
			if (_bufEnd - _bufPos <= matchLen)
			{
				_bufPos += matchLen - 1;
				return;
			}
			while (--matchLen > 0)
			{
				InsertString(ref hash);
				_bufPos++;
			}
		}

		internal bool GetNextSymbolOrMatch(Match match)
		{
			uint hash = HashValue(0u, _window[_bufPos]);
			hash = HashValue(hash, _window[_bufPos + 1]);
			int matchPos = 0;
			int num;
			if (_bufEnd - _bufPos <= 3)
			{
				num = 0;
			}
			else
			{
				int num2 = (int)InsertString(ref hash);
				if (num2 != 0)
				{
					num = FindMatch(num2, out matchPos, 32, 32);
					if (_bufPos + num > _bufEnd)
					{
						num = _bufEnd - _bufPos;
					}
				}
				else
				{
					num = 0;
				}
			}
			if (num < 3)
			{
				match.State = MatchState.HasSymbol;
				match.Symbol = _window[_bufPos];
				_bufPos++;
			}
			else
			{
				_bufPos++;
				if (num <= 6)
				{
					int matchPos2 = 0;
					int num3 = (int)InsertString(ref hash);
					int num4;
					if (num3 != 0)
					{
						num4 = FindMatch(num3, out matchPos2, (num < 4) ? 32 : 8, 32);
						if (_bufPos + num4 > _bufEnd)
						{
							num4 = _bufEnd - _bufPos;
						}
					}
					else
					{
						num4 = 0;
					}
					if (num4 > num)
					{
						match.State = MatchState.HasSymbolAndMatch;
						match.Symbol = _window[_bufPos - 1];
						match.Position = matchPos2;
						match.Length = num4;
						_bufPos++;
						num = num4;
						InsertStrings(ref hash, num);
					}
					else
					{
						match.State = MatchState.HasMatch;
						match.Position = matchPos;
						match.Length = num;
						num--;
						_bufPos++;
						InsertStrings(ref hash, num);
					}
				}
				else
				{
					match.State = MatchState.HasMatch;
					match.Position = matchPos;
					match.Length = num;
					InsertStrings(ref hash, num);
				}
			}
			if (_bufPos == 16384)
			{
				MoveWindows();
			}
			return true;
		}

		private int FindMatch(int search, out int matchPos, int searchDepth, int niceLength)
		{
			int num = 0;
			int num2 = 0;
			int num3 = _bufPos - 8192;
			byte b = _window[_bufPos];
			while (search > num3)
			{
				if (_window[search + num] == b)
				{
					int i;
					for (i = 0; i < 258 && _window[_bufPos + i] == _window[search + i]; i++)
					{
					}
					if (i > num)
					{
						num = i;
						num2 = search;
						if (i > 32)
						{
							break;
						}
						b = _window[_bufPos + i];
					}
				}
				if (--searchDepth == 0)
				{
					break;
				}
				search = _prev[search & 0x1FFF];
			}
			matchPos = _bufPos - num2 - 1;
			if (num == 3 && matchPos >= 16384)
			{
				return 0;
			}
			return num;
		}

		[Conditional("DEBUG")]
		private void DebugAssertVerifyHashes()
		{
		}

		[Conditional("DEBUG")]
		private void DebugAssertRecalculatedHashesAreEqual(int position1, int position2, string message = "")
		{
		}
	}
	internal interface IFileFormatWriter
	{
		byte[] GetHeader();

		void UpdateWithBytesRead(byte[] buffer, int offset, int bytesToCopy);

		byte[] GetFooter();
	}
	internal interface IFileFormatReader
	{
		bool ReadHeader(System.IO.Compression.InputBuffer input);

		bool ReadFooter(System.IO.Compression.InputBuffer input);

		void UpdateWithBytesRead(byte[] buffer, int offset, int bytesToCopy);

		void Validate();
	}
	internal sealed class HuffmanTree
	{
		internal const int MaxLiteralTreeElements = 288;

		internal const int MaxDistTreeElements = 32;

		internal const int EndOfBlockCode = 256;

		internal const int NumberOfCodeLengthTreeElements = 19;

		private readonly int _tableBits;

		private readonly short[] _table;

		private readonly short[] _left;

		private readonly short[] _right;

		private readonly byte[] _codeLengthArray;

		private readonly int _tableMask;

		public static System.IO.Compression.HuffmanTree StaticLiteralLengthTree { get; } = new System.IO.Compression.HuffmanTree(GetStaticLiteralTreeLength());


		public static System.IO.Compression.HuffmanTree StaticDistanceTree { get; } = new System.IO.Compression.HuffmanTree(GetStaticDistanceTreeLength());


		public HuffmanTree(byte[] codeLengths)
		{
			_codeLengthArray = codeLengths;
			if (_codeLengthArray.Length == 288)
			{
				_tableBits = 9;
			}
			else
			{
				_tableBits = 7;
			}
			_tableMask = (1 << _tableBits) - 1;
			_table = new short[1 << _tableBits];
			_left = new short[2 * _codeLengthArray.Length];
			_right = new short[2 * _codeLengthArray.Length];
			CreateTable();
		}

		private static byte[] GetStaticLiteralTreeLength()
		{
			byte[] array = new byte[288];
			for (int i = 0; i <= 143; i++)
			{
				array[i] = 8;
			}
			for (int j = 144; j <= 255; j++)
			{
				array[j] = 9;
			}
			for (int k = 256; k <= 279; k++)
			{
				array[k] = 7;
			}
			for (int l = 280; l <= 287; l++)
			{
				array[l] = 8;
			}
			return array;
		}

		private static byte[] GetStaticDistanceTreeLength()
		{
			byte[] array = new byte[32];
			for (int i = 0; i < 32; i++)
			{
				array[i] = 5;
			}
			return array;
		}

		private uint[] CalculateHuffmanCode()
		{
			uint[] array = new uint[17];
			byte[] codeLengthArray = _codeLengthArray;
			foreach (int num in codeLengthArray)
			{
				array[num]++;
			}
			array[0] = 0u;
			uint[] array2 = new uint[17];
			uint num2 = 0u;
			for (int j = 1; j <= 16; j++)
			{
				num2 = (array2[j] = num2 + array[j - 1] << 1);
			}
			uint[] array3 = new uint[288];
			for (int k = 0; k < _codeLengthArray.Length; k++)
			{
				int num3 = _codeLengthArray[k];
				if (num3 > 0)
				{
					array3[k] = FastEncoderStatics.BitReverse(array2[num3], num3);
					array2[num3]++;
				}
			}
			return array3;
		}

		private void CreateTable()
		{
			uint[] array = CalculateHuffmanCode();
			short num = (short)_codeLengthArray.Length;
			for (int i = 0; i < _codeLengthArray.Length; i++)
			{
				int num2 = _codeLengthArray[i];
				if (num2 <= 0)
				{
					continue;
				}
				int num3 = (int)array[i];
				if (num2 <= _tableBits)
				{
					int num4 = 1 << num2;
					if (num3 >= num4)
					{
						throw new InvalidDataException("Failed to construct a huffman tree using the length array. The stream might be corrupted.");
					}
					int num5 = 1 << _tableBits - num2;
					for (int j = 0; j < num5; j++)
					{
						_table[num3] = (short)i;
						num3 += num4;
					}
					continue;
				}
				int num6 = num2 - _tableBits;
				int num7 = 1 << _tableBits;
				int num8 = num3 & ((1 << _tableBits) - 1);
				short[] array2 = _table;
				do
				{
					short num9 = array2[num8];
					if (num9 == 0)
					{
						array2[num8] = (short)(-num);
						num9 = (short)(-num);
						num++;
					}
					if (num9 > 0)
					{
						throw new InvalidDataException("Failed to construct a huffman tree using the length array. The stream might be corrupted.");
					}
					array2 = (((num3 & num7) != 0) ? _right : _left);
					num8 = -num9;
					num7 <<= 1;
					num6--;
				}
				while (num6 != 0);
				array2[num8] = (short)i;
			}
		}

		public int GetNextSymbol(System.IO.Compression.InputBuffer input)
		{
			uint num = input.TryLoad16Bits();
			if (input.AvailableBits == 0)
			{
				return -1;
			}
			int num2 = _table[num & _tableMask];
			if (num2 < 0)
			{
				uint num3 = (uint)(1 << _tableBits);
				do
				{
					num2 = -num2;
					num2 = (((num & num3) != 0) ? _right[num2] : _left[num2]);
					num3 <<= 1;
				}
				while (num2 < 0);
			}
			int num4 = _codeLengthArray[num2];
			if (num4 <= 0)
			{
				throw new InvalidDataException("Failed to construct a huffman tree using the length array. The stream might be corrupted.");
			}
			if (num4 > input.AvailableBits)
			{
				return -1;
			}
			input.SkipBits(num4);
			return num2;
		}
	}
	internal sealed class InflaterManaged
	{
		private static readonly byte[] s_extraLengthBits = new byte[29]
		{
			0, 0, 0, 0, 0, 0, 0, 0, 1, 1,
			1, 1, 2, 2, 2, 2, 3, 3, 3, 3,
			4, 4, 4, 4, 5, 5, 5, 5, 16
		};

		private static readonly int[] s_lengthBase = new int[29]
		{
			3, 4, 5, 6, 7, 8, 9, 10, 11, 13,
			15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
			67, 83, 99, 115, 131, 163, 195, 227, 3
		};

		private static readonly int[] s_distanceBasePosition = new int[32]
		{
			1, 2, 3, 4, 5, 7, 9, 13, 17, 25,
			33, 49, 65, 97, 129, 193, 257, 385, 513, 769,
			1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
			32769, 49153
		};

		private static readonly byte[] s_codeOrder = new byte[19]
		{
			16, 17, 18, 0, 8, 7, 9, 6, 10, 5,
			11, 4, 12, 3, 13, 2, 14, 1, 15
		};

		private static readonly byte[] s_staticDistanceTreeTable = new byte[32]
		{
			0, 16, 8, 24, 4, 20, 12, 28, 2, 18,
			10, 26, 6, 22, 14, 30, 1, 17, 9, 25,
			5, 21, 13, 29, 3, 19, 11, 27, 7, 23,
			15, 31
		};

		private readonly System.IO.Compression.OutputWindow _output;

		private readonly System.IO.Compression.InputBuffer _input;

		private System.IO.Compression.HuffmanTree _literalLengthTree;

		private System.IO.Compression.HuffmanTree _distanceTree;

		private System.IO.Compression.InflaterState _state;

		private bool _hasFormatReader;

		private int _bfinal;

		private System.IO.Compression.BlockType _blockType;

		private readonly byte[] _blockLengthBuffer = new byte[4];

		private int _blockLength;

		private int _length;

		private int _distanceCode;

		private int _extraBits;

		private int _loopCounter;

		private int _literalLengthCodeCount;

		private int _distanceCodeCount;

		private int _codeLengthCodeCount;

		private int _codeArraySize;

		private int _lengthCode;

		private readonly byte[] _codeList;

		private readonly byte[] _codeLengthTreeCodeLength;

		private readonly bool _deflate64;

		private System.IO.Compression.HuffmanTree _codeLengthTree;

		private IFileFormatReader _formatReader;

		public int AvailableOutput => _output.AvailableBytes;

		internal InflaterManaged(IFileFormatReader reader, bool deflate64)
		{
			_output = new System.IO.Compression.OutputWindow();
			_input = new System.IO.Compression.InputBuffer();
			_codeList = new byte[320];
			_codeLengthTreeCodeLength = new byte[19];
			_deflate64 = deflate64;
			if (reader != null)
			{
				_formatReader = reader;
				_hasFormatReader = true;
			}
			Reset();
		}

		private void Reset()
		{
			_state = ((!_hasFormatReader) ? System.IO.Compression.InflaterState.ReadingBFinal : System.IO.Compression.InflaterState.ReadingHeader);
		}

		public void SetInput(byte[] inputBytes, int offset, int length)
		{
			_input.SetInput(inputBytes, offset, length);
		}

		public bool Finished()
		{
			if (_state != System.IO.Compression.InflaterState.Done)
			{
				return _state == System.IO.Compression.InflaterState.VerifyingFooter;
			}
			return true;
		}

		public int Inflate(byte[] bytes, int offset, int length)
		{
			int num = 0;
			do
			{
				int num2 = _output.CopyTo(bytes, offset, length);
				if (num2 > 0)
				{
					if (_hasFormatReader)
					{
						_formatReader.UpdateWithBytesRead(bytes, offset, num2);
					}
					offset += num2;
					num += num2;
					length -= num2;
				}
			}
			while (length != 0 && !Finished() && Decode());
			if (_state == System.IO.Compression.InflaterState.VerifyingFooter && _output.AvailableBytes == 0)
			{
				_formatReader.Validate();
			}
			return num;
		}

		private bool Decode()
		{
			bool end_of_block_code_seen = false;
			bool flag = false;
			if (Finished())
			{
				return true;
			}
			if (_hasFormatReader)
			{
				if (_state == System.IO.Compression.InflaterState.ReadingHeader)
				{
					if (!_formatReader.ReadHeader(_input))
					{
						return false;
					}
					_state = System.IO.Compression.InflaterState.ReadingBFinal;
				}
				else if (_state == System.IO.Compression.InflaterState.StartReadingFooter || _state == System.IO.Compression.InflaterState.ReadingFooter)
				{
					if (!_formatReader.ReadFooter(_input))
					{
						return false;
					}
					_state = System.IO.Compression.InflaterState.VerifyingFooter;
					return true;
				}
			}
			if (_state == System.IO.Compression.InflaterState.ReadingBFinal)
			{
				if (!_input.EnsureBitsAvailable(1))
				{
					return false;
				}
				_bfinal = _input.GetBits(1);
				_state = System.IO.Compression.InflaterState.ReadingBType;
			}
			if (_state == System.IO.Compression.InflaterState.ReadingBType)
			{
				if (!_input.EnsureBitsAvailable(2))
				{
					_state = System.IO.Compression.InflaterState.ReadingBType;
					return false;
				}
				_blockType = (System.IO.Compression.BlockType)_input.GetBits(2);
				if (_blockType == System.IO.Compression.BlockType.Dynamic)
				{
					_state = System.IO.Compression.InflaterState.ReadingNumLitCodes;
				}
				else if (_blockType == System.IO.Compression.BlockType.Static)
				{
					_literalLengthTree = System.IO.Compression.HuffmanTree.StaticLiteralLengthTree;
					_distanceTree = System.IO.Compression.HuffmanTree.

BepInEx/core/System.IO.Compression.FileSystem.dll

Decompiled 2 weeks ago
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Text;

[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyDefaultAlias("System.IO.Compression.FileSystem.dll")]
[assembly: AssemblyDescription("System.IO.Compression.FileSystem.dll")]
[assembly: AssemblyTitle("System.IO.Compression.FileSystem.dll")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyDelaySign(true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal class SR
{
	public const string IO_DirectoryNameWithData = "Zip entry name ends in directory separator character but contains data.";

	public const string IO_ExtractingResultsInOutside = "Extracting Zip entry would have resulted in a file outside the specified destination directory.";
}
namespace System.IO
{
	internal static class PathInternal
	{
		private static readonly bool s_isCaseSensitive = GetIsCaseSensitive();

		internal static StringComparison StringComparison
		{
			get
			{
				if (!s_isCaseSensitive)
				{
					return StringComparison.OrdinalIgnoreCase;
				}
				return StringComparison.Ordinal;
			}
		}

		internal static bool IsCaseSensitive => s_isCaseSensitive;

		private static bool GetIsCaseSensitive()
		{
			try
			{
				string text = Path.Combine(Path.GetTempPath(), "CASESENSITIVETEST" + Guid.NewGuid().ToString("N"));
				using (new FileStream(text, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 4096, FileOptions.DeleteOnClose))
				{
					return !File.Exists(text.ToLowerInvariant());
				}
			}
			catch (Exception)
			{
				return false;
			}
		}
	}
}
namespace System.IO.Compression
{
	public static class ZipFile
	{
		private const char PathSeparator = '/';

		public static ZipArchive OpenRead(string archiveFileName)
		{
			return Open(archiveFileName, ZipArchiveMode.Read);
		}

		public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode)
		{
			return Open(archiveFileName, mode, null);
		}

		public static ZipArchive Open(string archiveFileName, ZipArchiveMode mode, Encoding entryNameEncoding)
		{
			FileMode mode2;
			FileAccess access;
			FileShare share;
			switch (mode)
			{
			case ZipArchiveMode.Read:
				mode2 = FileMode.Open;
				access = FileAccess.Read;
				share = FileShare.Read;
				break;
			case ZipArchiveMode.Create:
				mode2 = FileMode.CreateNew;
				access = FileAccess.Write;
				share = FileShare.None;
				break;
			case ZipArchiveMode.Update:
				mode2 = FileMode.OpenOrCreate;
				access = FileAccess.ReadWrite;
				share = FileShare.None;
				break;
			default:
				throw new ArgumentOutOfRangeException("mode");
			}
			FileStream fileStream = new FileStream(archiveFileName, mode2, access, share, 4096, useAsync: false);
			try
			{
				return new ZipArchive(fileStream, mode, leaveOpen: false, entryNameEncoding);
			}
			catch
			{
				fileStream.Dispose();
				throw;
			}
		}

		public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName)
		{
			DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, null, includeBaseDirectory: false, null);
		}

		public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory)
		{
			DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, null);
		}

		public static void CreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel compressionLevel, bool includeBaseDirectory, Encoding entryNameEncoding)
		{
			DoCreateFromDirectory(sourceDirectoryName, destinationArchiveFileName, compressionLevel, includeBaseDirectory, entryNameEncoding);
		}

		public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName)
		{
			ExtractToDirectory(sourceArchiveFileName, destinationDirectoryName, null);
		}

		public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName, bool overwrite)
		{
			ExtractToDirectory(sourceArchiveFileName, destinationDirectoryName, null, overwrite);
		}

		public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName, Encoding entryNameEncoding)
		{
			ExtractToDirectory(sourceArchiveFileName, destinationDirectoryName, entryNameEncoding, overwrite: false);
		}

		public static void ExtractToDirectory(string sourceArchiveFileName, string destinationDirectoryName, Encoding entryNameEncoding, bool overwrite)
		{
			if (sourceArchiveFileName == null)
			{
				throw new ArgumentNullException("sourceArchiveFileName");
			}
			using ZipArchive source = Open(sourceArchiveFileName, ZipArchiveMode.Read, entryNameEncoding);
			source.ExtractToDirectory(destinationDirectoryName, overwrite);
		}

		private static void DoCreateFromDirectory(string sourceDirectoryName, string destinationArchiveFileName, CompressionLevel? compressionLevel, bool includeBaseDirectory, Encoding entryNameEncoding)
		{
			sourceDirectoryName = Path.GetFullPath(sourceDirectoryName);
			destinationArchiveFileName = Path.GetFullPath(destinationArchiveFileName);
			using ZipArchive zipArchive = Open(destinationArchiveFileName, ZipArchiveMode.Create, entryNameEncoding);
			bool flag = true;
			DirectoryInfo directoryInfo = new DirectoryInfo(sourceDirectoryName);
			string fullName = directoryInfo.FullName;
			if (includeBaseDirectory && directoryInfo.Parent != null)
			{
				fullName = directoryInfo.Parent.FullName;
			}
			char[] buffer = ArrayPool<char>.Shared.Rent(260);
			try
			{
				foreach (FileSystemInfo item in directoryInfo.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
				{
					flag = false;
					int length = item.FullName.Length - fullName.Length;
					if (item is FileInfo)
					{
						string entryName = EntryFromPath(item.FullName, fullName.Length, length, ref buffer);
						ZipFileExtensions.DoCreateEntryFromFile(zipArchive, item.FullName, entryName, compressionLevel);
					}
					else if (item is DirectoryInfo possiblyEmptyDir && IsDirEmpty(possiblyEmptyDir))
					{
						string entryName2 = EntryFromPath(item.FullName, fullName.Length, length, ref buffer, appendPathSeparator: true);
						zipArchive.CreateEntry(entryName2);
					}
				}
				if (includeBaseDirectory && flag)
				{
					zipArchive.CreateEntry(EntryFromPath(directoryInfo.Name, 0, directoryInfo.Name.Length, ref buffer, appendPathSeparator: true));
				}
			}
			finally
			{
				ArrayPool<char>.Shared.Return(buffer, false);
			}
		}

		private static string EntryFromPath(string entry, int offset, int length, ref char[] buffer, bool appendPathSeparator = false)
		{
			while (length > 0 && (entry[offset] == Path.DirectorySeparatorChar || entry[offset] == Path.AltDirectorySeparatorChar))
			{
				offset++;
				length--;
			}
			if (length == 0)
			{
				if (!appendPathSeparator)
				{
					return string.Empty;
				}
				return '/'.ToString();
			}
			int num = (appendPathSeparator ? (length + 1) : length);
			EnsureCapacity(ref buffer, num);
			entry.CopyTo(offset, buffer, 0, length);
			for (int i = 0; i < length; i++)
			{
				char c = buffer[i];
				if (c == Path.DirectorySeparatorChar || c == Path.AltDirectorySeparatorChar)
				{
					buffer[i] = '/';
				}
			}
			if (appendPathSeparator)
			{
				buffer[length] = '/';
			}
			return new string(buffer, 0, num);
		}

		private static void EnsureCapacity(ref char[] buffer, int min)
		{
			if (buffer.Length < min)
			{
				int num = buffer.Length * 2;
				if (num < min)
				{
					num = min;
				}
				ArrayPool<char>.Shared.Return(buffer, false);
				buffer = ArrayPool<char>.Shared.Rent(num);
			}
		}

		private static bool IsDirEmpty(DirectoryInfo possiblyEmptyDir)
		{
			using IEnumerator<string> enumerator = Directory.EnumerateFileSystemEntries(possiblyEmptyDir.FullName).GetEnumerator();
			return !enumerator.MoveNext();
		}
	}
	[EditorBrowsable(EditorBrowsableState.Never)]
	public static class ZipFileExtensions
	{
		public static ZipArchiveEntry CreateEntryFromFile(this ZipArchive destination, string sourceFileName, string entryName)
		{
			return DoCreateEntryFromFile(destination, sourceFileName, entryName, null);
		}

		public static ZipArchiveEntry CreateEntryFromFile(this ZipArchive destination, string sourceFileName, string entryName, CompressionLevel compressionLevel)
		{
			return DoCreateEntryFromFile(destination, sourceFileName, entryName, compressionLevel);
		}

		public static void ExtractToDirectory(this ZipArchive source, string destinationDirectoryName)
		{
			source.ExtractToDirectory(destinationDirectoryName, overwrite: false);
		}

		public static void ExtractToDirectory(this ZipArchive source, string destinationDirectoryName, bool overwrite)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (destinationDirectoryName == null)
			{
				throw new ArgumentNullException("destinationDirectoryName");
			}
			string text = Directory.CreateDirectory(destinationDirectoryName).FullName;
			if (!text.EndsWith(Path.DirectorySeparatorChar))
			{
				text += Path.DirectorySeparatorChar;
			}
			foreach (ZipArchiveEntry entry in source.Entries)
			{
				string fullPath = Path.GetFullPath(Path.Combine(text, entry.FullName));
				if (!fullPath.StartsWith(text, System.IO.PathInternal.StringComparison))
				{
					throw new IOException("Extracting Zip entry would have resulted in a file outside the specified destination directory.");
				}
				if (Path.GetFileName(fullPath).Length == 0)
				{
					if (entry.Length != 0L)
					{
						throw new IOException("Zip entry name ends in directory separator character but contains data.");
					}
					Directory.CreateDirectory(fullPath);
				}
				else
				{
					Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
					entry.ExtractToFile(fullPath, overwrite);
				}
			}
		}

		internal static ZipArchiveEntry DoCreateEntryFromFile(ZipArchive destination, string sourceFileName, string entryName, CompressionLevel? compressionLevel)
		{
			if (destination == null)
			{
				throw new ArgumentNullException("destination");
			}
			if (sourceFileName == null)
			{
				throw new ArgumentNullException("sourceFileName");
			}
			if (entryName == null)
			{
				throw new ArgumentNullException("entryName");
			}
			using Stream stream = new FileStream(sourceFileName, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, useAsync: false);
			ZipArchiveEntry zipArchiveEntry = (compressionLevel.HasValue ? destination.CreateEntry(entryName, compressionLevel.Value) : destination.CreateEntry(entryName));
			DateTime dateTime = File.GetLastWriteTime(sourceFileName);
			if (dateTime.Year < 1980 || dateTime.Year > 2107)
			{
				dateTime = new DateTime(1980, 1, 1, 0, 0, 0);
			}
			zipArchiveEntry.LastWriteTime = dateTime;
			using (Stream destination2 = zipArchiveEntry.Open())
			{
				stream.CopyTo(destination2);
			}
			return zipArchiveEntry;
		}

		public static void ExtractToFile(this ZipArchiveEntry source, string destinationFileName)
		{
			source.ExtractToFile(destinationFileName, overwrite: false);
		}

		public static void ExtractToFile(this ZipArchiveEntry source, string destinationFileName, bool overwrite)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (destinationFileName == null)
			{
				throw new ArgumentNullException("destinationFileName");
			}
			FileMode mode = ((!overwrite) ? FileMode.CreateNew : FileMode.Create);
			using (Stream destination = new FileStream(destinationFileName, mode, FileAccess.Write, FileShare.None, 4096, useAsync: false))
			{
				using Stream stream = source.Open();
				stream.CopyTo(destination);
			}
			File.SetLastWriteTime(destinationFileName, source.LastWriteTime.DateTime);
		}
	}
}

BepInEx/core/System.IO.Pipelines.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using FxResources.System.IO.Pipelines;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.IO.Pipelines.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.IO.Pipelines")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Single producer single consumer byte buffer management.\r\n\r\nCommonly Used Types:\r\nSystem.IO.Pipelines.Pipe\r\nSystem.IO.Pipelines.PipeWriter\r\nSystem.IO.Pipelines.PipeReader")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.IO.Pipelines")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: AssemblyVersion("10.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(true)]
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]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.System.IO.Pipelines
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string AdvanceToInvalidCursor => GetResourceString("AdvanceToInvalidCursor");

		internal static string ArgumentOutOfRange_NeedPosNum => GetResourceString("ArgumentOutOfRange_NeedPosNum");

		internal static string ConcurrentOperationsNotSupported => GetResourceString("ConcurrentOperationsNotSupported");

		internal static string FlushCanceledOnPipeWriter => GetResourceString("FlushCanceledOnPipeWriter");

		internal static string GetResultBeforeCompleted => GetResourceString("GetResultBeforeCompleted");

		internal static string InvalidExaminedOrConsumedPosition => GetResourceString("InvalidExaminedOrConsumedPosition");

		internal static string InvalidExaminedPosition => GetResourceString("InvalidExaminedPosition");

		internal static string InvalidZeroByteRead => GetResourceString("InvalidZeroByteRead");

		internal static string ObjectDisposed_StreamClosed => GetResourceString("ObjectDisposed_StreamClosed");

		internal static string NoReadingOperationToComplete => GetResourceString("NoReadingOperationToComplete");

		internal static string NotSupported_UnreadableStream => GetResourceString("NotSupported_UnreadableStream");

		internal static string NotSupported_UnwritableStream => GetResourceString("NotSupported_UnwritableStream");

		internal static string ReadCanceledOnPipeReader => GetResourceString("ReadCanceledOnPipeReader");

		internal static string ReaderAndWriterHasToBeCompleted => GetResourceString("ReaderAndWriterHasToBeCompleted");

		internal static string ReadingAfterCompleted => GetResourceString("ReadingAfterCompleted");

		internal static string ReadingIsInProgress => GetResourceString("ReadingIsInProgress");

		internal static string WritingAfterCompleted => GetResourceString("WritingAfterCompleted");

		internal static string UnflushedBytesNotSupported => GetResourceString("UnflushedBytesNotSupported");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string? EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type? StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Threading
{
	internal static class CancellationTokenExtensions
	{
		internal static CancellationTokenRegistration UnsafeRegister(this CancellationToken cancellationToken, Action<object> callback, object state)
		{
			return cancellationToken.Register(callback, state);
		}
	}
}
namespace System.Threading.Tasks
{
	internal static class TaskToAsyncResult
	{
		private sealed class TaskAsyncResult : IAsyncResult
		{
			internal readonly Task _task;

			private readonly AsyncCallback _callback;

			public object AsyncState { get; }

			public bool CompletedSynchronously { get; }

			public bool IsCompleted => _task.IsCompleted;

			public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle;

			internal TaskAsyncResult(Task task, object state, AsyncCallback callback)
			{
				_task = task;
				AsyncState = state;
				if (task.IsCompleted)
				{
					CompletedSynchronously = true;
					callback?.Invoke(this);
				}
				else if (callback != null)
				{
					_callback = callback;
					_task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().OnCompleted(delegate
					{
						_callback(this);
					});
				}
			}
		}

		public static IAsyncResult Begin(Task task, AsyncCallback? callback, object? state)
		{
			ExceptionPolyfills.ThrowIfNull(task, "task");
			return new TaskAsyncResult(task, state, callback);
		}

		public static void End(IAsyncResult asyncResult)
		{
			Unwrap(asyncResult).GetAwaiter().GetResult();
		}

		public static TResult End<TResult>(IAsyncResult asyncResult)
		{
			return Unwrap<TResult>(asyncResult).GetAwaiter().GetResult();
		}

		public static Task Unwrap(IAsyncResult asyncResult)
		{
			ExceptionPolyfills.ThrowIfNull(asyncResult, "asyncResult");
			return (asyncResult as TaskAsyncResult)?._task ?? throw new ArgumentException(null, "asyncResult");
		}

		public static Task<TResult> Unwrap<TResult>(IAsyncResult asyncResult)
		{
			ExceptionPolyfills.ThrowIfNull(asyncResult, "asyncResult");
			return ((asyncResult as TaskAsyncResult)?._task as Task<TResult>) ?? throw new ArgumentException(null, "asyncResult");
		}
	}
}
namespace System.IO
{
	internal static class StreamHelpers
	{
		public static void ValidateCopyToArgs(Stream source, Stream destination, int bufferSize)
		{
			ExceptionPolyfills.ThrowIfNull(destination, "destination");
			if (bufferSize <= 0)
			{
				throw new ArgumentOutOfRangeException("bufferSize", bufferSize, System.SR.ArgumentOutOfRange_NeedPosNum);
			}
			bool canRead = source.CanRead;
			if (!canRead && !source.CanWrite)
			{
				throw new ObjectDisposedException(null, System.SR.ObjectDisposed_StreamClosed);
			}
			bool canWrite = destination.CanWrite;
			if (!canWrite && !destination.CanRead)
			{
				throw new ObjectDisposedException("destination", System.SR.ObjectDisposed_StreamClosed);
			}
			if (!canRead)
			{
				throw new NotSupportedException(System.SR.NotSupported_UnreadableStream);
			}
			if (!canWrite)
			{
				throw new NotSupportedException(System.SR.NotSupported_UnwritableStream);
			}
		}
	}
	internal static class StreamExtensions
	{
		public static ValueTask<int> ReadAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (MemoryMarshal.TryGetArray((ReadOnlyMemory<byte>)buffer, out ArraySegment<byte> segment))
			{
				return new ValueTask<int>(stream.ReadAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));
			}
			byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length);
			return FinishReadAsync(stream.ReadAsync(array, 0, buffer.Length, cancellationToken), array, buffer);
			static async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination)
			{
				try
				{
					int num = await readTask.ConfigureAwait(continueOnCapturedContext: false);
					new Span<byte>(localBuffer, 0, num).CopyTo(localDestination.Span);
					return num;
				}
				finally
				{
					ArrayPool<byte>.Shared.Return(localBuffer);
				}
			}
		}

		public static void Write(this Stream stream, ReadOnlyMemory<byte> buffer)
		{
			if (MemoryMarshal.TryGetArray(buffer, out var segment))
			{
				stream.Write(segment.Array, segment.Offset, segment.Count);
				return;
			}
			byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length);
			try
			{
				buffer.Span.CopyTo(array);
				stream.Write(array, 0, buffer.Length);
			}
			finally
			{
				ArrayPool<byte>.Shared.Return(array);
			}
		}

		public static ValueTask WriteAsync(this Stream stream, ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (MemoryMarshal.TryGetArray(buffer, out var segment))
			{
				return new ValueTask(stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));
			}
			byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length);
			buffer.Span.CopyTo(array);
			return new ValueTask(FinishWriteAsync(stream.WriteAsync(array, 0, buffer.Length, cancellationToken), array));
		}

		private static async Task FinishWriteAsync(Task writeTask, byte[] localBuffer)
		{
			try
			{
				await writeTask.ConfigureAwait(continueOnCapturedContext: false);
			}
			finally
			{
				ArrayPool<byte>.Shared.Return(localBuffer);
			}
		}

		public static Task CopyToAsync(this Stream source, Stream destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			return source.CopyToAsync(destination, 81920, cancellationToken);
		}
	}
}
namespace System.IO.Pipelines
{
	internal sealed class BufferSegment : ReadOnlySequenceSegment<byte>
	{
		private IMemoryOwner<byte> _memoryOwner;

		private byte[] _array;

		private BufferSegment _next;

		private int _end;

		public int End
		{
			get
			{
				return _end;
			}
			set
			{
				_end = value;
				base.Memory = AvailableMemory.Slice(0, value);
			}
		}

		public BufferSegment? NextSegment
		{
			get
			{
				return _next;
			}
			set
			{
				base.Next = value;
				_next = value;
			}
		}

		internal object? MemoryOwner => ((object)_memoryOwner) ?? ((object)_array);

		public Memory<byte> AvailableMemory { get; private set; }

		public int Length => End;

		public int WritableBytes
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			get
			{
				return AvailableMemory.Length - End;
			}
		}

		public void SetOwnedMemory(IMemoryOwner<byte> memoryOwner)
		{
			_memoryOwner = memoryOwner;
			AvailableMemory = memoryOwner.Memory;
		}

		public void SetOwnedMemory(byte[] arrayPoolBuffer)
		{
			_array = arrayPoolBuffer;
			AvailableMemory = arrayPoolBuffer;
		}

		public void Reset()
		{
			ResetMemory();
			base.Next = null;
			base.RunningIndex = 0L;
			_next = null;
		}

		public void ResetMemory()
		{
			IMemoryOwner<byte> memoryOwner = _memoryOwner;
			if (memoryOwner != null)
			{
				_memoryOwner = null;
				memoryOwner.Dispose();
			}
			else
			{
				ArrayPool<byte>.Shared.Return(_array);
				_array = null;
			}
			base.Memory = default(ReadOnlyMemory<byte>);
			_end = 0;
			AvailableMemory = default(Memory<byte>);
		}

		public void SetNext(BufferSegment segment)
		{
			NextSegment = segment;
			segment = this;
			while (segment.Next != null)
			{
				segment.NextSegment.RunningIndex = segment.RunningIndex + segment.Length;
				segment = segment.NextSegment;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static long GetLength(BufferSegment startSegment, int startIndex, BufferSegment endSegment, int endIndex)
		{
			return endSegment.RunningIndex + (uint)endIndex - (startSegment.RunningIndex + (uint)startIndex);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static long GetLength(long startPosition, BufferSegment endSegment, int endIndex)
		{
			return endSegment.RunningIndex + (uint)endIndex - startPosition;
		}
	}
	internal readonly struct CompletionData
	{
		public Action<object?> Completion { get; }

		public object? CompletionState { get; }

		public ExecutionContext? ExecutionContext { get; }

		public SynchronizationContext? SynchronizationContext { get; }

		public CompletionData(Action<object?> completion, object? completionState, ExecutionContext? executionContext, SynchronizationContext? synchronizationContext)
		{
			Completion = completion;
			CompletionState = completionState;
			ExecutionContext = executionContext;
			SynchronizationContext = synchronizationContext;
		}
	}
	public struct FlushResult
	{
		internal ResultFlags _resultFlags;

		public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0;

		public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0;

		public FlushResult(bool isCanceled, bool isCompleted)
		{
			_resultFlags = ResultFlags.None;
			if (isCanceled)
			{
				_resultFlags |= ResultFlags.Canceled;
			}
			if (isCompleted)
			{
				_resultFlags |= ResultFlags.Completed;
			}
		}
	}
	internal sealed class InlineScheduler : PipeScheduler
	{
		public override void Schedule(Action<object?> action, object? state)
		{
			action(state);
		}

		internal override void UnsafeSchedule(Action<object?> action, object? state)
		{
			action(state);
		}
	}
	public interface IDuplexPipe
	{
		PipeReader Input { get; }

		PipeWriter Output { get; }
	}
	internal struct BufferSegmentStack
	{
		private readonly struct SegmentAsValueType
		{
			private readonly BufferSegment _value;

			private SegmentAsValueType(BufferSegment value)
			{
				_value = value;
			}

			public static implicit operator SegmentAsValueType(BufferSegment s)
			{
				return new SegmentAsValueType(s);
			}

			public static implicit operator BufferSegment(SegmentAsValueType s)
			{
				return s._value;
			}
		}

		private SegmentAsValueType[] _array;

		private int _size;

		public int Count => _size;

		public BufferSegmentStack(int size)
		{
			_array = new SegmentAsValueType[size];
			_size = 0;
		}

		public bool TryPop([NotNullWhen(true)] out BufferSegment? result)
		{
			int num = _size - 1;
			SegmentAsValueType[] array = _array;
			if ((uint)num >= (uint)array.Length)
			{
				result = null;
				return false;
			}
			_size = num;
			result = array[num];
			array[num] = default(SegmentAsValueType);
			return true;
		}

		public void Push(BufferSegment item)
		{
			int size = _size;
			SegmentAsValueType[] array = _array;
			if ((uint)size < (uint)array.Length)
			{
				array[size] = item;
				_size = size + 1;
			}
			else
			{
				PushWithResize(item);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void PushWithResize(BufferSegment item)
		{
			Array.Resize(ref _array, 2 * _array.Length);
			_array[_size] = item;
			_size++;
		}
	}
	public sealed class Pipe
	{
		private sealed class DefaultPipeReader : PipeReader, IValueTaskSource<ReadResult>
		{
			private readonly Pipe _pipe;

			public DefaultPipeReader(Pipe pipe)
			{
				_pipe = pipe;
			}

			public override bool TryRead(out ReadResult result)
			{
				return _pipe.TryRead(out result);
			}

			public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.ReadAsync(cancellationToken);
			}

			protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumBytes, CancellationToken cancellationToken)
			{
				return _pipe.ReadAtLeastAsync(minimumBytes, cancellationToken);
			}

			public override void AdvanceTo(SequencePosition consumed)
			{
				_pipe.AdvanceReader(in consumed);
			}

			public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
			{
				_pipe.AdvanceReader(in consumed, in examined);
			}

			public override void CancelPendingRead()
			{
				_pipe.CancelPendingRead();
			}

			public override void Complete(Exception exception = null)
			{
				_pipe.CompleteReader(exception);
			}

			public override void OnWriterCompleted(Action<Exception, object> callback, object state)
			{
				_pipe.OnWriterCompleted(callback, state);
			}

			public ValueTaskSourceStatus GetStatus(short token)
			{
				return _pipe.GetReadAsyncStatus();
			}

			public ReadResult GetResult(short token)
			{
				return _pipe.GetReadAsyncResult();
			}

			public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				_pipe.OnReadAsyncCompleted(continuation, state, flags);
			}
		}

		private sealed class DefaultPipeWriter : PipeWriter, IValueTaskSource<FlushResult>
		{
			private readonly Pipe _pipe;

			public override bool CanGetUnflushedBytes => true;

			public override long UnflushedBytes => _pipe.GetUnflushedBytes();

			public DefaultPipeWriter(Pipe pipe)
			{
				_pipe = pipe;
			}

			public override void Complete(Exception exception = null)
			{
				_pipe.CompleteWriter(exception);
			}

			public override void CancelPendingFlush()
			{
				_pipe.CancelPendingFlush();
			}

			public override void OnReaderCompleted(Action<Exception, object> callback, object state)
			{
				_pipe.OnReaderCompleted(callback, state);
			}

			public override ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.FlushAsync(cancellationToken);
			}

			public override void Advance(int bytes)
			{
				_pipe.Advance(bytes);
			}

			public override Memory<byte> GetMemory(int sizeHint = 0)
			{
				return _pipe.GetMemory(sizeHint);
			}

			public override Span<byte> GetSpan(int sizeHint = 0)
			{
				return _pipe.GetSpan(sizeHint);
			}

			public ValueTaskSourceStatus GetStatus(short token)
			{
				return _pipe.GetFlushAsyncStatus();
			}

			public FlushResult GetResult(short token)
			{
				return _pipe.GetFlushAsyncResult();
			}

			public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
			{
				_pipe.OnFlushAsyncCompleted(continuation, state, flags);
			}

			public override ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
			{
				return _pipe.WriteAsync(source, cancellationToken);
			}
		}

		private static readonly Action<object> s_signalReaderAwaitable = delegate(object state)
		{
			((Pipe)state).ReaderCancellationRequested();
		};

		private static readonly Action<object> s_signalWriterAwaitable = delegate(object state)
		{
			((Pipe)state).WriterCancellationRequested();
		};

		private static readonly Action<object> s_invokeCompletionCallbacks = delegate(object state)
		{
			((PipeCompletionCallbacks)state).Execute();
		};

		private static readonly ContextCallback s_executionContextRawCallback = ExecuteWithoutExecutionContext;

		private static readonly SendOrPostCallback s_syncContextExecutionContextCallback = ExecuteWithExecutionContext;

		private static readonly SendOrPostCallback s_syncContextExecuteWithoutExecutionContextCallback = ExecuteWithoutExecutionContext;

		private static readonly Action<object> s_scheduleWithExecutionContextCallback = ExecuteWithExecutionContext;

		private BufferSegmentStack _bufferSegmentPool;

		private readonly DefaultPipeReader _reader;

		private readonly DefaultPipeWriter _writer;

		private readonly PipeOptions _options;

		private readonly object _sync = new object();

		private long _unconsumedBytes;

		private long _unflushedBytes;

		private PipeAwaitable _readerAwaitable;

		private PipeAwaitable _writerAwaitable;

		private PipeCompletion _writerCompletion;

		private PipeCompletion _readerCompletion;

		private long _lastExaminedIndex = -1L;

		private BufferSegment _readHead;

		private int _readHeadIndex;

		private bool _disposed;

		private BufferSegment _readTail;

		private int _readTailIndex;

		private int _minimumReadBytes;

		private BufferSegment _writingHead;

		private Memory<byte> _writingHeadMemory;

		private int _writingHeadBytesBuffered;

		private PipeOperationState _operationState;

		private bool UseSynchronizationContext => _options.UseSynchronizationContext;

		private int MinimumSegmentSize => _options.MinimumSegmentSize;

		private long PauseWriterThreshold => _options.PauseWriterThreshold;

		private long ResumeWriterThreshold => _options.ResumeWriterThreshold;

		private PipeScheduler ReaderScheduler => _options.ReaderScheduler;

		private PipeScheduler WriterScheduler => _options.WriterScheduler;

		private object SyncObj => _sync;

		internal long Length => _unconsumedBytes;

		public PipeReader Reader => _reader;

		public PipeWriter Writer => _writer;

		public Pipe()
			: this(PipeOptions.Default)
		{
		}

		public Pipe(PipeOptions options)
		{
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			_bufferSegmentPool = new BufferSegmentStack(options.InitialSegmentPoolSize);
			_operationState = default(PipeOperationState);
			_readerCompletion = default(PipeCompletion);
			_writerCompletion = default(PipeCompletion);
			_options = options;
			_readerAwaitable = new PipeAwaitable(completed: false, UseSynchronizationContext);
			_writerAwaitable = new PipeAwaitable(completed: true, UseSynchronizationContext);
			_reader = new DefaultPipeReader(this);
			_writer = new DefaultPipeWriter(this);
		}

		private void ResetState()
		{
			_readerCompletion.Reset();
			_writerCompletion.Reset();
			_readerAwaitable = new PipeAwaitable(completed: false, UseSynchronizationContext);
			_writerAwaitable = new PipeAwaitable(completed: true, UseSynchronizationContext);
			_readTailIndex = 0;
			_readHeadIndex = 0;
			_lastExaminedIndex = -1L;
			_unflushedBytes = 0L;
			_unconsumedBytes = 0L;
		}

		internal Memory<byte> GetMemory(int sizeHint)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateWriteHeadIfNeeded(sizeHint);
			return _writingHeadMemory;
		}

		internal Span<byte> GetSpan(int sizeHint)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateWriteHeadIfNeeded(sizeHint);
			return _writingHeadMemory.Span;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AllocateWriteHeadIfNeeded(int sizeHint)
		{
			if (!_operationState.IsWritingActive || _writingHeadMemory.Length == 0 || _writingHeadMemory.Length < sizeHint)
			{
				AllocateWriteHeadSynchronized(sizeHint);
			}
		}

		private void AllocateWriteHeadSynchronized(int sizeHint)
		{
			lock (SyncObj)
			{
				_operationState.BeginWrite();
				if (_writingHead == null)
				{
					BufferSegment readTail = AllocateSegment(sizeHint);
					_writingHead = (_readHead = (_readTail = readTail));
					_lastExaminedIndex = 0L;
					return;
				}
				int length = _writingHeadMemory.Length;
				if (length == 0 || length < sizeHint)
				{
					if (_writingHeadBytesBuffered > 0)
					{
						_writingHead.End += _writingHeadBytesBuffered;
						_writingHeadBytesBuffered = 0;
					}
					if (_writingHead.Length == 0)
					{
						_writingHead.ResetMemory();
						RentMemory(_writingHead, sizeHint);
					}
					else
					{
						BufferSegment bufferSegment = AllocateSegment(sizeHint);
						_writingHead.SetNext(bufferSegment);
						_writingHead = bufferSegment;
					}
				}
			}
		}

		private BufferSegment AllocateSegment(int sizeHint)
		{
			BufferSegment bufferSegment = CreateSegmentUnsynchronized();
			RentMemory(bufferSegment, sizeHint);
			return bufferSegment;
		}

		private void RentMemory(BufferSegment segment, int sizeHint)
		{
			MemoryPool<byte> memoryPool = null;
			int num = -1;
			if (!_options.IsDefaultSharedMemoryPool)
			{
				memoryPool = _options.Pool;
				num = memoryPool.MaxBufferSize;
			}
			if (sizeHint <= num)
			{
				segment.SetOwnedMemory(memoryPool.Rent(GetSegmentSize(sizeHint, num)));
			}
			else
			{
				int segmentSize = GetSegmentSize(sizeHint);
				segment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize));
			}
			_writingHeadMemory = segment.AvailableMemory;
		}

		private int GetSegmentSize(int sizeHint, int maxBufferSize = int.MaxValue)
		{
			sizeHint = Math.Max(MinimumSegmentSize, sizeHint);
			return Math.Min(maxBufferSize, sizeHint);
		}

		private BufferSegment CreateSegmentUnsynchronized()
		{
			if (_bufferSegmentPool.TryPop(out BufferSegment result))
			{
				return result;
			}
			return new BufferSegment();
		}

		private void ReturnSegmentUnsynchronized(BufferSegment segment)
		{
			if (_bufferSegmentPool.Count < _options.MaxSegmentPoolSize)
			{
				_bufferSegmentPool.Push(segment);
			}
		}

		internal bool CommitUnsynchronized()
		{
			_operationState.EndWrite();
			if (_unflushedBytes == 0L)
			{
				return false;
			}
			_writingHead.End += _writingHeadBytesBuffered;
			_readTail = _writingHead;
			_readTailIndex = _writingHead.End;
			long unconsumedBytes = _unconsumedBytes;
			_unconsumedBytes += _unflushedBytes;
			bool result = true;
			if (_unconsumedBytes < _minimumReadBytes)
			{
				result = false;
			}
			else if (PauseWriterThreshold > 0 && unconsumedBytes < PauseWriterThreshold && _unconsumedBytes >= PauseWriterThreshold && !_readerCompletion.IsCompleted)
			{
				_writerAwaitable.SetUncompleted();
			}
			_unflushedBytes = 0L;
			_writingHeadBytesBuffered = 0;
			return result;
		}

		internal void Advance(int bytes)
		{
			lock (SyncObj)
			{
				if ((uint)bytes > (uint)_writingHeadMemory.Length)
				{
					ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes);
				}
				if (!_readerCompletion.IsCompleted)
				{
					AdvanceCore(bytes);
				}
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void AdvanceCore(int bytesWritten)
		{
			_unflushedBytes += bytesWritten;
			_writingHeadBytesBuffered += bytesWritten;
			_writingHeadMemory = _writingHeadMemory.Slice(bytesWritten);
		}

		internal ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken)
		{
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken));
			}
			CompletionData completionData;
			ValueTask<FlushResult> result;
			lock (SyncObj)
			{
				PrepareFlushUnsynchronized(out completionData, out result, cancellationToken);
			}
			TrySchedule(ReaderScheduler, in completionData);
			return result;
		}

		private void PrepareFlushUnsynchronized(out CompletionData completionData, out ValueTask<FlushResult> result, CancellationToken cancellationToken)
		{
			bool num = CommitUnsynchronized();
			_writerAwaitable.BeginOperation(cancellationToken, s_signalWriterAwaitable, this);
			if (_writerAwaitable.IsCompleted)
			{
				FlushResult result2 = default(FlushResult);
				GetFlushResult(ref result2);
				result = new ValueTask<FlushResult>(result2);
			}
			else
			{
				result = new ValueTask<FlushResult>(_writer, 0);
			}
			if (num)
			{
				_readerAwaitable.Complete(out completionData);
			}
			else
			{
				completionData = default(CompletionData);
			}
		}

		internal void CompleteWriter(Exception? exception)
		{
			PipeCompletionCallbacks pipeCompletionCallbacks;
			CompletionData completionData;
			bool isCompleted;
			lock (SyncObj)
			{
				CommitUnsynchronized();
				pipeCompletionCallbacks = _writerCompletion.TryComplete(exception);
				_readerAwaitable.Complete(out completionData);
				isCompleted = _readerCompletion.IsCompleted;
			}
			if (isCompleted)
			{
				CompletePipe();
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(ReaderScheduler, pipeCompletionCallbacks);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal void AdvanceReader(in SequencePosition consumed)
		{
			AdvanceReader(in consumed, in consumed);
		}

		internal void AdvanceReader(in SequencePosition consumed, in SequencePosition examined)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			AdvanceReader((BufferSegment)consumed.GetObject(), consumed.GetInteger(), (BufferSegment)examined.GetObject(), examined.GetInteger());
		}

		private void AdvanceReader(BufferSegment consumedSegment, int consumedIndex, BufferSegment examinedSegment, int examinedIndex)
		{
			if (consumedSegment != null && examinedSegment != null && BufferSegment.GetLength(consumedSegment, consumedIndex, examinedSegment, examinedIndex) < 0)
			{
				ThrowHelper.ThrowInvalidOperationException_InvalidExaminedOrConsumedPosition();
			}
			BufferSegment bufferSegment = null;
			BufferSegment returnEnd = null;
			CompletionData completionData = default(CompletionData);
			lock (SyncObj)
			{
				bool flag = false;
				if (examinedSegment == _readTail)
				{
					flag = examinedIndex == _readTailIndex;
				}
				if (examinedSegment != null && _lastExaminedIndex >= 0)
				{
					long length = BufferSegment.GetLength(_lastExaminedIndex, examinedSegment, examinedIndex);
					long unconsumedBytes = _unconsumedBytes;
					_unconsumedBytes -= length;
					_lastExaminedIndex = examinedSegment.RunningIndex + examinedIndex;
					if (unconsumedBytes >= ResumeWriterThreshold && _unconsumedBytes < ResumeWriterThreshold)
					{
						_writerAwaitable.Complete(out completionData);
					}
				}
				if (consumedSegment != null)
				{
					if (_readHead == null)
					{
						ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor();
						return;
					}
					bufferSegment = _readHead;
					returnEnd = consumedSegment;
					if (consumedIndex == returnEnd.Length)
					{
						if (_writingHead != returnEnd)
						{
							MoveReturnEndToNextBlock();
						}
						else if (_writingHeadBytesBuffered == 0 && !_operationState.IsWritingActive)
						{
							_writingHead = null;
							_writingHeadMemory = default(Memory<byte>);
							MoveReturnEndToNextBlock();
						}
						else
						{
							_readHead = consumedSegment;
							_readHeadIndex = consumedIndex;
						}
					}
					else
					{
						_readHead = consumedSegment;
						_readHeadIndex = consumedIndex;
					}
				}
				if (flag && !_writerCompletion.IsCompleted)
				{
					_readerAwaitable.SetUncompleted();
				}
				while (bufferSegment != null && bufferSegment != returnEnd)
				{
					BufferSegment? nextSegment = bufferSegment.NextSegment;
					bufferSegment.Reset();
					ReturnSegmentUnsynchronized(bufferSegment);
					bufferSegment = nextSegment;
				}
				_operationState.EndRead();
			}
			TrySchedule(WriterScheduler, in completionData);
			void MoveReturnEndToNextBlock()
			{
				BufferSegment nextSegment2 = returnEnd.NextSegment;
				if (_readTail == returnEnd)
				{
					_readTail = nextSegment2;
					_readTailIndex = 0;
				}
				_readHead = nextSegment2;
				_readHeadIndex = 0;
				returnEnd = nextSegment2;
			}
		}

		internal void CompleteReader(Exception? exception)
		{
			PipeCompletionCallbacks pipeCompletionCallbacks;
			CompletionData completionData;
			bool isCompleted;
			lock (SyncObj)
			{
				if (_operationState.IsReadingActive)
				{
					_operationState.EndRead();
				}
				pipeCompletionCallbacks = _readerCompletion.TryComplete(exception);
				_writerAwaitable.Complete(out completionData);
				isCompleted = _writerCompletion.IsCompleted;
			}
			if (isCompleted)
			{
				CompletePipe();
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(WriterScheduler, pipeCompletionCallbacks);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		internal void OnWriterCompleted(Action<Exception?, object?> callback, object? state)
		{
			if (callback == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback);
			}
			PipeCompletionCallbacks pipeCompletionCallbacks;
			lock (SyncObj)
			{
				pipeCompletionCallbacks = _writerCompletion.AddCallback(callback, state);
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(ReaderScheduler, pipeCompletionCallbacks);
			}
		}

		internal void CancelPendingRead()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_readerAwaitable.Cancel(out completionData);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal void CancelPendingFlush()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_writerAwaitable.Cancel(out completionData);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		internal void OnReaderCompleted(Action<Exception?, object?> callback, object? state)
		{
			if (callback == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callback);
			}
			PipeCompletionCallbacks pipeCompletionCallbacks;
			lock (SyncObj)
			{
				pipeCompletionCallbacks = _readerCompletion.AddCallback(callback, state);
			}
			if (pipeCompletionCallbacks != null)
			{
				ScheduleCallbacks(WriterScheduler, pipeCompletionCallbacks);
			}
		}

		internal ValueTask<ReadResult> ReadAtLeastAsync(int minimumBytes, CancellationToken token)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			if (token.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(token));
			}
			CompletionData completionData = default(CompletionData);
			ValueTask<ReadResult> result2;
			lock (SyncObj)
			{
				_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				if (_readerAwaitable.IsCompleted)
				{
					GetReadResult(out var result);
					if (_unconsumedBytes >= minimumBytes || result.IsCanceled || result.IsCompleted)
					{
						return new ValueTask<ReadResult>(result);
					}
					_readerAwaitable.SetUncompleted();
					_operationState.EndRead();
					_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				}
				if (!_writerAwaitable.IsCompleted)
				{
					_writerAwaitable.Complete(out completionData);
				}
				_minimumReadBytes = minimumBytes;
				result2 = new ValueTask<ReadResult>(_reader, 0);
			}
			TrySchedule(WriterScheduler, in completionData);
			return result2;
		}

		internal ValueTask<ReadResult> ReadAsync(CancellationToken token)
		{
			if (_readerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
			if (token.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(token));
			}
			lock (SyncObj)
			{
				_readerAwaitable.BeginOperation(token, s_signalReaderAwaitable, this);
				if (_readerAwaitable.IsCompleted)
				{
					GetReadResult(out var result);
					return new ValueTask<ReadResult>(result);
				}
				return new ValueTask<ReadResult>(_reader, 0);
			}
		}

		internal bool TryRead(out ReadResult result)
		{
			lock (SyncObj)
			{
				if (_readerCompletion.IsCompleted)
				{
					ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
				}
				if (_unconsumedBytes > 0 || _readerAwaitable.IsCompleted)
				{
					GetReadResult(out result);
					return true;
				}
				if (_readerAwaitable.IsRunning)
				{
					ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
				}
				_operationState.BeginReadTentative();
				result = default(ReadResult);
				return false;
			}
		}

		private static void ScheduleCallbacks(PipeScheduler scheduler, PipeCompletionCallbacks completionCallbacks)
		{
			scheduler.UnsafeSchedule(s_invokeCompletionCallbacks, completionCallbacks);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static void TrySchedule(PipeScheduler scheduler, in CompletionData completionData)
		{
			Action<object> completion = completionData.Completion;
			if (completion != null)
			{
				if (completionData.SynchronizationContext == null && completionData.ExecutionContext == null)
				{
					scheduler.UnsafeSchedule(completion, completionData.CompletionState);
				}
				else
				{
					ScheduleWithContext(scheduler, in completionData);
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void ScheduleWithContext(PipeScheduler scheduler, in CompletionData completionData)
		{
			if (completionData.SynchronizationContext == null)
			{
				scheduler.UnsafeSchedule(s_scheduleWithExecutionContextCallback, completionData);
			}
			else if (completionData.ExecutionContext == null)
			{
				completionData.SynchronizationContext.Post(s_syncContextExecuteWithoutExecutionContextCallback, completionData);
			}
			else
			{
				completionData.SynchronizationContext.Post(s_syncContextExecutionContextCallback, completionData);
			}
		}

		private static void ExecuteWithoutExecutionContext(object state)
		{
			CompletionData completionData = (CompletionData)state;
			completionData.Completion(completionData.CompletionState);
		}

		private static void ExecuteWithExecutionContext(object state)
		{
			ExecutionContext.Run(((CompletionData)state).ExecutionContext, s_executionContextRawCallback, state);
		}

		private void CompletePipe()
		{
			lock (SyncObj)
			{
				if (!_disposed)
				{
					_disposed = true;
					BufferSegment bufferSegment = _readHead ?? _readTail;
					while (bufferSegment != null)
					{
						BufferSegment bufferSegment2 = bufferSegment;
						bufferSegment = bufferSegment.NextSegment;
						bufferSegment2.Reset();
					}
					_writingHead = null;
					_writingHeadMemory = default(Memory<byte>);
					_readHead = null;
					_readTail = null;
					_lastExaminedIndex = -1L;
				}
			}
		}

		internal ValueTaskSourceStatus GetReadAsyncStatus()
		{
			if (_readerAwaitable.IsCompleted)
			{
				if (_writerCompletion.IsFaulted)
				{
					return ValueTaskSourceStatus.Faulted;
				}
				return ValueTaskSourceStatus.Succeeded;
			}
			return ValueTaskSourceStatus.Pending;
		}

		internal void OnReadAsyncCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags)
		{
			CompletionData completionData;
			bool doubleCompletion;
			lock (SyncObj)
			{
				_readerAwaitable.OnCompleted(continuation, state, flags, out completionData, out doubleCompletion);
			}
			if (doubleCompletion)
			{
				Writer.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation());
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		internal ReadResult GetReadAsyncResult()
		{
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			CancellationToken cancellationToken = default(CancellationToken);
			ReadResult result;
			try
			{
				lock (SyncObj)
				{
					if (!_readerAwaitable.IsCompleted)
					{
						ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted();
					}
					cancellationTokenRegistration = _readerAwaitable.ReleaseCancellationTokenRegistration(out cancellationToken);
					GetReadResult(out result);
				}
			}
			finally
			{
				cancellationTokenRegistration.Dispose();
			}
			if (result.IsCanceled)
			{
				cancellationToken.ThrowIfCancellationRequested();
			}
			return result;
		}

		private void GetReadResult(out ReadResult result)
		{
			bool isCompleted = _writerCompletion.IsCompletedOrThrow();
			bool flag = _readerAwaitable.ObserveCancellation();
			BufferSegment readHead = _readHead;
			if (readHead != null)
			{
				ReadOnlySequence<byte> buffer = new ReadOnlySequence<byte>(readHead, _readHeadIndex, _readTail, _readTailIndex);
				result = new ReadResult(buffer, flag, isCompleted);
			}
			else
			{
				result = new ReadResult(default(ReadOnlySequence<byte>), flag, isCompleted);
			}
			if (flag)
			{
				_operationState.BeginReadTentative();
			}
			else
			{
				_operationState.BeginRead();
			}
			_minimumReadBytes = 0;
		}

		internal ValueTaskSourceStatus GetFlushAsyncStatus()
		{
			if (_writerAwaitable.IsCompleted)
			{
				if (_readerCompletion.IsFaulted)
				{
					return ValueTaskSourceStatus.Faulted;
				}
				return ValueTaskSourceStatus.Succeeded;
			}
			return ValueTaskSourceStatus.Pending;
		}

		internal FlushResult GetFlushAsyncResult()
		{
			FlushResult result = default(FlushResult);
			CancellationToken cancellationToken = default(CancellationToken);
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			try
			{
				lock (SyncObj)
				{
					if (!_writerAwaitable.IsCompleted)
					{
						ThrowHelper.ThrowInvalidOperationException_GetResultNotCompleted();
					}
					GetFlushResult(ref result);
					cancellationTokenRegistration = _writerAwaitable.ReleaseCancellationTokenRegistration(out cancellationToken);
					return result;
				}
			}
			finally
			{
				cancellationTokenRegistration.Dispose();
				cancellationToken.ThrowIfCancellationRequested();
			}
		}

		internal long GetUnflushedBytes()
		{
			return _unflushedBytes;
		}

		private void GetFlushResult(ref FlushResult result)
		{
			if (_writerAwaitable.ObserveCancellation())
			{
				result._resultFlags |= ResultFlags.Canceled;
			}
			if (_readerCompletion.IsCompletedOrThrow())
			{
				result._resultFlags |= ResultFlags.Completed;
			}
		}

		internal ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken)
		{
			if (_writerCompletion.IsCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (_readerCompletion.IsCompletedOrThrow())
			{
				return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: true));
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<FlushResult>(Task.FromCanceled<FlushResult>(cancellationToken));
			}
			CompletionData completionData;
			ValueTask<FlushResult> result;
			lock (SyncObj)
			{
				AllocateWriteHeadIfNeeded(0);
				if (source.Length <= _writingHeadMemory.Length)
				{
					source.CopyTo(_writingHeadMemory);
					AdvanceCore(source.Length);
				}
				else
				{
					WriteMultiSegment(source.Span);
				}
				PrepareFlushUnsynchronized(out completionData, out result, cancellationToken);
			}
			TrySchedule(ReaderScheduler, in completionData);
			return result;
		}

		private void WriteMultiSegment(ReadOnlySpan<byte> source)
		{
			Span<byte> span = _writingHeadMemory.Span;
			while (true)
			{
				int num = Math.Min(span.Length, source.Length);
				source.Slice(0, num).CopyTo(span);
				source = source.Slice(num);
				AdvanceCore(num);
				if (source.Length != 0)
				{
					_writingHead.End += _writingHeadBytesBuffered;
					_writingHeadBytesBuffered = 0;
					BufferSegment bufferSegment = AllocateSegment(0);
					_writingHead.SetNext(bufferSegment);
					_writingHead = bufferSegment;
					span = _writingHeadMemory.Span;
					continue;
				}
				break;
			}
		}

		internal void OnFlushAsyncCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags)
		{
			CompletionData completionData;
			bool doubleCompletion;
			lock (SyncObj)
			{
				_writerAwaitable.OnCompleted(continuation, state, flags, out completionData, out doubleCompletion);
			}
			if (doubleCompletion)
			{
				Reader.Complete(ThrowHelper.CreateInvalidOperationException_NoConcurrentOperation());
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		private void ReaderCancellationRequested()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_readerAwaitable.CancellationTokenFired(out completionData);
			}
			TrySchedule(ReaderScheduler, in completionData);
		}

		private void WriterCancellationRequested()
		{
			CompletionData completionData;
			lock (SyncObj)
			{
				_writerAwaitable.CancellationTokenFired(out completionData);
			}
			TrySchedule(WriterScheduler, in completionData);
		}

		public void Reset()
		{
			lock (SyncObj)
			{
				if (!_disposed)
				{
					ThrowHelper.ThrowInvalidOperationException_ResetIncompleteReaderWriter();
				}
				_disposed = false;
				ResetState();
			}
		}
	}
	[DebuggerDisplay("CanceledState = {_awaitableState}, IsCompleted = {IsCompleted}")]
	internal struct PipeAwaitable
	{
		[Flags]
		private enum AwaitableState
		{
			None = 0,
			Completed = 1,
			Running = 2,
			Canceled = 4,
			UseSynchronizationContext = 8
		}

		private sealed class SchedulingContext
		{
			public SynchronizationContext SynchronizationContext { get; set; }

			public ExecutionContext ExecutionContext { get; set; }
		}

		private AwaitableState _awaitableState;

		private Action<object> _completion;

		private object _completionState;

		private SchedulingContext _schedulingContext;

		private CancellationTokenRegistration _cancellationTokenRegistration;

		private CancellationToken _cancellationToken;

		private CancellationToken CancellationToken => _cancellationToken;

		public bool IsCompleted => (_awaitableState & (AwaitableState.Completed | AwaitableState.Canceled)) != 0;

		public bool IsRunning => (_awaitableState & AwaitableState.Running) != 0;

		public PipeAwaitable(bool completed, bool useSynchronizationContext)
		{
			_awaitableState = (completed ? AwaitableState.Completed : AwaitableState.None) | (useSynchronizationContext ? AwaitableState.UseSynchronizationContext : AwaitableState.None);
			_completion = null;
			_completionState = null;
			_cancellationTokenRegistration = default(CancellationTokenRegistration);
			_schedulingContext = null;
			_cancellationToken = CancellationToken.None;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginOperation(CancellationToken cancellationToken, Action<object?> callback, object? state)
		{
			if (cancellationToken.CanBeCanceled && !IsCompleted)
			{
				_cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, callback, state);
				if (_cancellationTokenRegistration == default(CancellationTokenRegistration))
				{
					cancellationToken.ThrowIfCancellationRequested();
				}
				_cancellationToken = cancellationToken;
			}
			_awaitableState |= AwaitableState.Running;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Complete(out CompletionData completionData)
		{
			ExtractCompletion(out completionData);
			_awaitableState |= AwaitableState.Completed;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private void ExtractCompletion(out CompletionData completionData)
		{
			Action<object> completion = _completion;
			object completionState = _completionState;
			SchedulingContext schedulingContext = _schedulingContext;
			ExecutionContext executionContext = schedulingContext?.ExecutionContext;
			SynchronizationContext synchronizationContext = schedulingContext?.SynchronizationContext;
			_completion = null;
			_completionState = null;
			_schedulingContext = null;
			completionData = ((completion != null) ? new CompletionData(completion, completionState, executionContext, synchronizationContext) : default(CompletionData));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void SetUncompleted()
		{
			_awaitableState &= ~AwaitableState.Completed;
		}

		public void OnCompleted(Action<object?> continuation, object? state, ValueTaskSourceOnCompletedFlags flags, out CompletionData completionData, out bool doubleCompletion)
		{
			completionData = default(CompletionData);
			doubleCompletion = _completion != null;
			if (IsCompleted | doubleCompletion)
			{
				completionData = new CompletionData(continuation, state, _schedulingContext?.ExecutionContext, _schedulingContext?.SynchronizationContext);
				return;
			}
			_completion = continuation;
			_completionState = state;
			if ((_awaitableState & AwaitableState.UseSynchronizationContext) != 0 && (flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
			{
				SynchronizationContext current = SynchronizationContext.Current;
				if (current != null && current.GetType() != typeof(SynchronizationContext))
				{
					if (_schedulingContext == null)
					{
						_schedulingContext = new SchedulingContext();
					}
					_schedulingContext.SynchronizationContext = current;
				}
			}
			if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)
			{
				if (_schedulingContext == null)
				{
					_schedulingContext = new SchedulingContext();
				}
				_schedulingContext.ExecutionContext = ExecutionContext.Capture();
			}
		}

		public void Cancel(out CompletionData completionData)
		{
			ExtractCompletion(out completionData);
			_awaitableState |= AwaitableState.Canceled;
		}

		public void CancellationTokenFired(out CompletionData completionData)
		{
			if (CancellationToken.IsCancellationRequested)
			{
				Cancel(out completionData);
			}
			else
			{
				completionData = default(CompletionData);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool ObserveCancellation()
		{
			bool result = (_awaitableState & AwaitableState.Canceled) == AwaitableState.Canceled;
			_awaitableState &= ~(AwaitableState.Running | AwaitableState.Canceled);
			return result;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public CancellationTokenRegistration ReleaseCancellationTokenRegistration(out CancellationToken cancellationToken)
		{
			cancellationToken = CancellationToken;
			CancellationTokenRegistration cancellationTokenRegistration = _cancellationTokenRegistration;
			_cancellationToken = default(CancellationToken);
			_cancellationTokenRegistration = default(CancellationTokenRegistration);
			return cancellationTokenRegistration;
		}
	}
	[DebuggerDisplay("IsCompleted = {IsCompleted}")]
	internal struct PipeCompletion
	{
		private static readonly object s_completedSuccessfully = new object();

		private object _state;

		private List<PipeCompletionCallback> _callbacks;

		public bool IsCompleted => _state != null;

		public bool IsFaulted => _state is ExceptionDispatchInfo;

		public PipeCompletionCallbacks? TryComplete(Exception? exception = null)
		{
			if (_state == null)
			{
				if (exception != null)
				{
					_state = ExceptionDispatchInfo.Capture(exception);
				}
				else
				{
					_state = s_completedSuccessfully;
				}
			}
			return GetCallbacks();
		}

		public PipeCompletionCallbacks? AddCallback(Action<Exception?, object?> callback, object? state)
		{
			if (_callbacks == null)
			{
				_callbacks = new List<PipeCompletionCallback>();
			}
			_callbacks.Add(new PipeCompletionCallback(callback, state));
			if (IsCompleted)
			{
				return GetCallbacks();
			}
			return null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool IsCompletedOrThrow()
		{
			if (!IsCompleted)
			{
				return false;
			}
			if (_state is ExceptionDispatchInfo exceptionDispatchInfo)
			{
				exceptionDispatchInfo.Throw();
			}
			return true;
		}

		private PipeCompletionCallbacks GetCallbacks()
		{
			List<PipeCompletionCallback> callbacks = _callbacks;
			if (callbacks == null)
			{
				return null;
			}
			_callbacks = null;
			return new PipeCompletionCallbacks(callbacks, _state as ExceptionDispatchInfo);
		}

		public void Reset()
		{
			_state = null;
		}

		public override string ToString()
		{
			return string.Format("{0}: {1}", "IsCompleted", IsCompleted);
		}
	}
	internal readonly struct PipeCompletionCallback
	{
		public readonly Action<Exception?, object?> Callback;

		public readonly object? State;

		public PipeCompletionCallback(Action<Exception?, object?> callback, object? state)
		{
			Callback = callback;
			State = state;
		}
	}
	internal sealed class PipeCompletionCallbacks
	{
		private readonly List<PipeCompletionCallback> _callbacks;

		private readonly Exception _exception;

		public PipeCompletionCallbacks(List<PipeCompletionCallback> callbacks, ExceptionDispatchInfo? edi)
		{
			_callbacks = callbacks;
			_exception = edi?.SourceException;
		}

		public void Execute()
		{
			int count = _callbacks.Count;
			if (count != 0)
			{
				List<Exception> exceptions = null;
				for (int i = 0; i < count; i++)
				{
					PipeCompletionCallback callback = _callbacks[i];
					Execute(callback, ref exceptions);
				}
				if (exceptions != null)
				{
					throw new AggregateException(exceptions);
				}
			}
		}

		private void Execute(PipeCompletionCallback callback, ref List<Exception> exceptions)
		{
			try
			{
				callback.Callback(_exception, callback.State);
			}
			catch (Exception item)
			{
				if (exceptions == null)
				{
					exceptions = new List<Exception>();
				}
				exceptions.Add(item);
			}
		}
	}
	public class PipeOptions
	{
		private const int DefaultMinimumSegmentSize = 4096;

		public static PipeOptions Default { get; } = new PipeOptions(null, null, null, -1L, -1L);


		public bool UseSynchronizationContext { get; }

		public long PauseWriterThreshold { get; }

		public long ResumeWriterThreshold { get; }

		public int MinimumSegmentSize { get; }

		public PipeScheduler WriterScheduler { get; }

		public PipeScheduler ReaderScheduler { get; }

		public MemoryPool<byte> Pool { get; }

		internal bool IsDefaultSharedMemoryPool { get; }

		internal int InitialSegmentPoolSize { get; }

		internal int MaxSegmentPoolSize { get; }

		public PipeOptions(MemoryPool<byte>? pool = null, PipeScheduler? readerScheduler = null, PipeScheduler? writerScheduler = null, long pauseWriterThreshold = -1L, long resumeWriterThreshold = -1L, int minimumSegmentSize = -1, bool useSynchronizationContext = true)
		{
			MinimumSegmentSize = ((minimumSegmentSize == -1) ? 4096 : minimumSegmentSize);
			InitialSegmentPoolSize = 4;
			MaxSegmentPoolSize = 256;
			if (pauseWriterThreshold == -1)
			{
				pauseWriterThreshold = 65536L;
			}
			else if (pauseWriterThreshold < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.pauseWriterThreshold);
			}
			switch (resumeWriterThreshold)
			{
			case -1L:
				resumeWriterThreshold = 32768L;
				break;
			case 0L:
				resumeWriterThreshold = 1L;
				break;
			}
			if (resumeWriterThreshold < 0 || (pauseWriterThreshold > 0 && resumeWriterThreshold > pauseWriterThreshold))
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.resumeWriterThreshold);
			}
			Pool = pool ?? MemoryPool<byte>.Shared;
			IsDefaultSharedMemoryPool = Pool == MemoryPool<byte>.Shared;
			ReaderScheduler = readerScheduler ?? PipeScheduler.ThreadPool;
			WriterScheduler = writerScheduler ?? PipeScheduler.ThreadPool;
			PauseWriterThreshold = pauseWriterThreshold;
			ResumeWriterThreshold = resumeWriterThreshold;
			UseSynchronizationContext = useSynchronizationContext;
		}
	}
	public abstract class PipeReader
	{
		private PipeReaderStream _stream;

		public abstract bool TryRead(out ReadResult result);

		public abstract ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken));

		public ValueTask<ReadResult> ReadAtLeastAsync(int minimumSize, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (minimumSize < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.minimumSize);
			}
			return ReadAtLeastAsyncCore(minimumSize, cancellationToken);
		}

		protected virtual async ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken)
		{
			ReadResult result;
			while (true)
			{
				result = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				ReadOnlySequence<byte> buffer = result.Buffer;
				if (buffer.Length >= minimumSize || result.IsCompleted || result.IsCanceled)
				{
					break;
				}
				AdvanceTo(buffer.Start, buffer.End);
			}
			return result;
		}

		public abstract void AdvanceTo(SequencePosition consumed);

		public abstract void AdvanceTo(SequencePosition consumed, SequencePosition examined);

		public virtual Stream AsStream(bool leaveOpen = false)
		{
			if (_stream == null)
			{
				_stream = new PipeReaderStream(this, leaveOpen);
			}
			else if (leaveOpen)
			{
				_stream.LeaveOpen = leaveOpen;
			}
			return _stream;
		}

		public abstract void CancelPendingRead();

		public abstract void Complete(Exception? exception = null);

		public virtual ValueTask CompleteAsync(Exception? exception = null)
		{
			try
			{
				Complete(exception);
				return default(ValueTask);
			}
			catch (Exception exception2)
			{
				return new ValueTask(Task.FromException(exception2));
			}
		}

		[Obsolete("OnWriterCompleted has been deprecated and may not be invoked on all implementations of PipeReader.")]
		public virtual void OnWriterCompleted(Action<Exception?, object?> callback, object? state)
		{
		}

		public static PipeReader Create(Stream stream, StreamPipeReaderOptions? readerOptions = null)
		{
			return new StreamPipeReader(stream, readerOptions ?? StreamPipeReaderOptions.s_default);
		}

		public static PipeReader Create(ReadOnlySequence<byte> sequence)
		{
			return new SequencePipeReader(sequence);
		}

		public virtual Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return CopyToAsyncCore(destination, (PipeWriter destination, ReadOnlyMemory<byte> memory, CancellationToken cancellationToken) => destination.WriteAsync(memory, cancellationToken), cancellationToken);
		}

		public virtual Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return CopyToAsyncCore(destination, delegate(Stream destination, ReadOnlyMemory<byte> memory, CancellationToken cancellationToken)
			{
				ValueTask writeTask2 = StreamExtensions.WriteAsync(destination, memory, cancellationToken);
				if (writeTask2.IsCompletedSuccessfully)
				{
					writeTask2.GetAwaiter().GetResult();
					return new ValueTask<FlushResult>(new FlushResult(isCanceled: false, isCompleted: false));
				}
				return Awaited(writeTask2);
			}, cancellationToken);
			static async ValueTask<FlushResult> Awaited(ValueTask writeTask)
			{
				await writeTask.ConfigureAwait(continueOnCapturedContext: false);
				return new FlushResult(isCanceled: false, isCompleted: false);
			}
		}

		private async Task CopyToAsyncCore<TStream>(TStream destination, Func<TStream, ReadOnlyMemory<byte>, CancellationToken, ValueTask<FlushResult>> writeAsync, CancellationToken cancellationToken)
		{
			while (true)
			{
				ReadResult result = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				ReadOnlySequence<byte> buffer = result.Buffer;
				SequencePosition position = buffer.Start;
				SequencePosition consumed = position;
				try
				{
					if (result.IsCanceled)
					{
						ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
					}
					ReadOnlyMemory<byte> memory;
					while (buffer.TryGet(ref position, out memory))
					{
						if (memory.IsEmpty)
						{
							consumed = position;
							continue;
						}
						FlushResult flushResult = await writeAsync(destination, memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						if (flushResult.IsCanceled)
						{
							ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
						}
						consumed = position;
						if (!flushResult.IsCompleted)
						{
							continue;
						}
						return;
					}
					consumed = buffer.End;
					if (result.IsCompleted)
					{
						break;
					}
				}
				finally
				{
					AdvanceTo(consumed);
				}
			}
		}
	}
	[DebuggerDisplay("State = {_state}")]
	internal struct PipeOperationState
	{
		[Flags]
		internal enum State : byte
		{
			Reading = 1,
			ReadingTentative = 2,
			Writing = 4
		}

		private State _state;

		public bool IsWritingActive => (_state & State.Writing) == State.Writing;

		public bool IsReadingActive => (_state & State.Reading) == State.Reading;

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginRead()
		{
			if ((_state & State.Reading) == State.Reading)
			{
				ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
			}
			_state |= State.Reading;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginReadTentative()
		{
			if ((_state & State.Reading) == State.Reading)
			{
				ThrowHelper.ThrowInvalidOperationException_AlreadyReading();
			}
			_state |= State.ReadingTentative;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void EndRead()
		{
			if ((_state & State.Reading) != State.Reading && (_state & State.ReadingTentative) != State.ReadingTentative)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadToComplete();
			}
			_state &= ~(State.Reading | State.ReadingTentative);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void BeginWrite()
		{
			_state |= State.Writing;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void EndWrite()
		{
			_state &= ~State.Writing;
		}
	}
	internal sealed class PipeReaderStream : Stream
	{
		private readonly PipeReader _pipeReader;

		public override bool CanRead => true;

		public override bool CanSeek => false;

		public override bool CanWrite => false;

		public override long Length
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public override long Position
		{
			get
			{
				throw new NotSupportedException();
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		internal bool LeaveOpen { get; set; }

		public PipeReaderStream(PipeReader pipeReader, bool leaveOpen)
		{
			_pipeReader = pipeReader;
			LeaveOpen = leaveOpen;
		}

		protected override void Dispose(bool disposing)
		{
			if (!LeaveOpen)
			{
				_pipeReader.Complete();
			}
			base.Dispose(disposing);
		}

		public override void Flush()
		{
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return ReadInternal(new Span<byte>(buffer, offset, count));
		}

		public override int ReadByte()
		{
			Span<byte> buffer = stackalloc byte[1];
			if (ReadInternal(buffer) != 0)
			{
				return buffer[0];
			}
			return -1;
		}

		private int ReadInternal(Span<byte> buffer)
		{
			ValueTask<ReadResult> valueTask = _pipeReader.ReadAsync();
			ReadResult result = (valueTask.IsCompletedSuccessfully ? valueTask.Result : valueTask.AsTask().GetAwaiter().GetResult());
			return HandleReadResult(result, buffer);
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		public sealed override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
		{
			return TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count, default(CancellationToken)), callback, state);
		}

		public sealed override int EndRead(IAsyncResult asyncResult)
		{
			return TaskToAsyncResult.End<int>(asyncResult);
		}

		public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return ReadAsyncInternal(new Memory<byte>(buffer, offset, count), cancellationToken).AsTask();
		}

		private async ValueTask<int> ReadAsyncInternal(Memory<byte> buffer, CancellationToken cancellationToken)
		{
			return HandleReadResult(await _pipeReader.ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false), buffer.Span);
		}

		private int HandleReadResult(ReadResult result, Span<byte> buffer)
		{
			if (result.IsCanceled)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			ReadOnlySequence<byte> buffer2 = result.Buffer;
			long length = buffer2.Length;
			SequencePosition consumed = buffer2.Start;
			try
			{
				if (length != 0L)
				{
					int num = (int)Math.Min(length, buffer.Length);
					ReadOnlySequence<byte> source = ((num == length) ? buffer2 : buffer2.Slice(0, num));
					consumed = source.End;
					source.CopyTo(buffer);
					return num;
				}
				if (result.IsCompleted)
				{
					return 0;
				}
			}
			finally
			{
				_pipeReader.AdvanceTo(consumed);
			}
			ThrowHelper.ThrowInvalidOperationException_InvalidZeroByteRead();
			return 0;
		}

		public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
		{
			StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
			return _pipeReader.CopyToAsync(destination, cancellationToken);
		}
	}
	public abstract class PipeScheduler
	{
		private static readonly ThreadPoolScheduler s_threadPoolScheduler = new ThreadPoolScheduler();

		private static readonly InlineScheduler s_inlineScheduler = new InlineScheduler();

		public static PipeScheduler ThreadPool => s_threadPoolScheduler;

		public static PipeScheduler Inline => s_inlineScheduler;

		public abstract void Schedule(Action<object?> action, object? state);

		internal virtual void UnsafeSchedule(Action<object?> action, object? state)
		{
			Schedule(action, state);
		}
	}
	public abstract class PipeWriter : IBufferWriter<byte>
	{
		private PipeWriterStream _stream;

		public virtual bool CanGetUnflushedBytes => false;

		public virtual long UnflushedBytes
		{
			get
			{
				throw ThrowHelper.CreateNotSupportedException_UnflushedBytes();
			}
		}

		public abstract void Complete(Exception? exception = null);

		public virtual ValueTask CompleteAsync(Exception? exception = null)
		{
			try
			{
				Complete(exception);
				return default(ValueTask);
			}
			catch (Exception exception2)
			{
				return new ValueTask(Task.FromException(exception2));
			}
		}

		public abstract void CancelPendingFlush();

		[Obsolete("OnReaderCompleted has been deprecated and may not be invoked on all implementations of PipeWriter.")]
		public virtual void OnReaderCompleted(Action<Exception?, object?> callback, object? state)
		{
		}

		public abstract ValueTask<FlushResult> FlushAsync(CancellationToken cancellationToken = default(CancellationToken));

		public abstract void Advance(int bytes);

		public abstract Memory<byte> GetMemory(int sizeHint = 0);

		public abstract Span<byte> GetSpan(int sizeHint = 0);

		public virtual Stream AsStream(bool leaveOpen = false)
		{
			if (_stream == null)
			{
				_stream = new PipeWriterStream(this, leaveOpen);
			}
			else if (leaveOpen)
			{
				_stream.LeaveOpen = leaveOpen;
			}
			return _stream;
		}

		public static PipeWriter Create(Stream stream, StreamPipeWriterOptions? writerOptions = null)
		{
			return new StreamPipeWriter(stream, writerOptions ?? StreamPipeWriterOptions.s_default);
		}

		public virtual ValueTask<FlushResult> WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken))
		{
			this.Write(source.Span);
			return FlushAsync(cancellationToken);
		}

		protected internal virtual async Task CopyFromAsync(Stream source, CancellationToken cancellationToken = default(CancellationToken))
		{
			FlushResult flushResult;
			do
			{
				Memory<byte> memory = GetMemory();
				int num = await StreamExtensions.ReadAsync(source, memory, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				if (num != 0)
				{
					Advance(num);
					flushResult = await FlushAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					if (flushResult.IsCanceled)
					{
						ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
					}
					continue;
				}
				break;
			}
			while (!flushResult.IsCompleted);
		}
	}
	internal sealed class PipeWriterStream : Stream
	{
		private readonly PipeWriter _pipeWriter;

		internal bool LeaveOpen { get; set; }

		public override bool CanRead => false;

		public override bool CanSeek => false;

		public override bool CanWrite => true;

		public override long Length
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public override long Position
		{
			get
			{
				throw new NotSupportedException();
			}
			set
			{
				throw new NotSupportedException();
			}
		}

		public PipeWriterStream(PipeWriter pipeWriter, bool leaveOpen)
		{
			_pipeWriter = pipeWriter;
			LeaveOpen = leaveOpen;
		}

		protected override void Dispose(bool disposing)
		{
			if (!LeaveOpen)
			{
				_pipeWriter.Complete();
			}
		}

		public override void Flush()
		{
			FlushAsync().GetAwaiter().GetResult();
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw new NotSupportedException();
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public sealed override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state)
		{
			return TaskToAsyncResult.Begin(WriteAsync(buffer, offset, count, default(CancellationToken)), callback, state);
		}

		public sealed override void EndWrite(IAsyncResult asyncResult)
		{
			TaskToAsyncResult.End(asyncResult);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			WriteAsync(buffer, offset, count).GetAwaiter().GetResult();
		}

		public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			if (buffer == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer);
			}
			return GetFlushResultAsTask(_pipeWriter.WriteAsync(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken));
		}

		public override Task FlushAsync(CancellationToken cancellationToken)
		{
			return GetFlushResultAsTask(_pipeWriter.FlushAsync(cancellationToken));
		}

		private static Task GetFlushResultAsTask(ValueTask<FlushResult> valueTask)
		{
			if (valueTask.IsCompletedSuccessfully)
			{
				if (valueTask.Result.IsCanceled)
				{
					ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
				}
				return Task.CompletedTask;
			}
			return AwaitTask(valueTask);
			static async Task AwaitTask(ValueTask<FlushResult> valueTask)
			{
				if ((await valueTask.ConfigureAwait(continueOnCapturedContext: false)).IsCanceled)
				{
					ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
				}
			}
		}
	}
	public readonly struct ReadResult
	{
		internal readonly ReadOnlySequence<byte> _resultBuffer;

		internal readonly ResultFlags _resultFlags;

		public ReadOnlySequence<byte> Buffer => _resultBuffer;

		public bool IsCanceled => (_resultFlags & ResultFlags.Canceled) != 0;

		public bool IsCompleted => (_resultFlags & ResultFlags.Completed) != 0;

		public ReadResult(ReadOnlySequence<byte> buffer, bool isCanceled, bool isCompleted)
		{
			_resultBuffer = buffer;
			_resultFlags = ResultFlags.None;
			if (isCompleted)
			{
				_resultFlags |= ResultFlags.Completed;
			}
			if (isCanceled)
			{
				_resultFlags |= ResultFlags.Canceled;
			}
		}
	}
	[Flags]
	internal enum ResultFlags : byte
	{
		None = 0,
		Canceled = 1,
		Completed = 2
	}
	internal sealed class SequencePipeReader : PipeReader
	{
		private ReadOnlySequence<byte> _sequence;

		private bool _isReaderCompleted;

		private int _cancelNext;

		public SequencePipeReader(ReadOnlySequence<byte> sequence)
		{
			_sequence = sequence;
		}

		public override void AdvanceTo(SequencePosition consumed)
		{
			AdvanceTo(consumed, consumed);
		}

		public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
		{
			ThrowIfCompleted();
			if (consumed.Equals(_sequence.End))
			{
				_sequence = ReadOnlySequence<byte>.Empty;
			}
			else
			{
				_sequence = _sequence.Slice(consumed);
			}
		}

		public override void CancelPendingRead()
		{
			Interlocked.Exchange(ref _cancelNext, 1);
		}

		public override void Complete(Exception? exception = null)
		{
			if (!_isReaderCompleted)
			{
				_isReaderCompleted = true;
				_sequence = ReadOnlySequence<byte>.Empty;
			}
		}

		public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TryRead(out var result))
			{
				return new ValueTask<ReadResult>(result);
			}
			result = new ReadResult(ReadOnlySequence<byte>.Empty, isCanceled: false, isCompleted: true);
			return new ValueTask<ReadResult>(result);
		}

		public override bool TryRead(out ReadResult result)
		{
			ThrowIfCompleted();
			bool flag = Interlocked.Exchange(ref _cancelNext, 0) == 1;
			if (flag || _sequence.Length > 0)
			{
				result = new ReadResult(_sequence, flag, isCompleted: true);
				return true;
			}
			result = default(ReadResult);
			return false;
		}

		private void ThrowIfCompleted()
		{
			if (_isReaderCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
		}
	}
	public static class StreamPipeExtensions
	{
		public static Task CopyToAsync(this Stream source, PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
			}
			if (destination == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.destination);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return destination.CopyFromAsync(source, cancellationToken);
		}
	}
	internal sealed class StreamPipeReader : PipeReader
	{
		internal const int InitialSegmentPoolSize = 4;

		internal const int MaxSegmentPoolSize = 256;

		private CancellationTokenSource _internalTokenSource;

		private bool _isReaderCompleted;

		private bool _isStreamCompleted;

		private BufferSegment _readHead;

		private int _readIndex;

		private BufferSegment _readTail;

		private long _bufferedBytes;

		private bool _examinedEverything;

		private readonly object _lock = new object();

		private BufferSegmentStack _bufferSegmentPool;

		private readonly StreamPipeReaderOptions _options;

		private bool LeaveOpen => _options.LeaveOpen;

		private bool UseZeroByteReads => _options.UseZeroByteReads;

		private int BufferSize => _options.BufferSize;

		private int MaxBufferSize => _options.MaxBufferSize;

		private int MinimumReadThreshold => _options.MinimumReadSize;

		private MemoryPool<byte> Pool => _options.Pool;

		public Stream InnerStream { get; }

		private CancellationTokenSource InternalTokenSource
		{
			get
			{
				lock (_lock)
				{
					return _internalTokenSource ?? (_internalTokenSource = new CancellationTokenSource());
				}
			}
		}

		public StreamPipeReader(Stream readingStream, StreamPipeReaderOptions options)
		{
			if (readingStream == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.readingStream);
			}
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			InnerStream = readingStream;
			_options = options;
			_bufferSegmentPool = new BufferSegmentStack(4);
		}

		public override void AdvanceTo(SequencePosition consumed)
		{
			AdvanceTo(consumed, consumed);
		}

		public override void AdvanceTo(SequencePosition consumed, SequencePosition examined)
		{
			ThrowIfCompleted();
			AdvanceTo((BufferSegment)consumed.GetObject(), consumed.GetInteger(), (BufferSegment)examined.GetObject(), examined.GetInteger());
		}

		private void AdvanceTo(BufferSegment consumedSegment, int consumedIndex, BufferSegment examinedSegment, int examinedIndex)
		{
			if (consumedSegment != null && examinedSegment != null)
			{
				if (_readHead == null)
				{
					ThrowHelper.ThrowInvalidOperationException_AdvanceToInvalidCursor();
				}
				BufferSegment bufferSegment = _readHead;
				BufferSegment bufferSegment2 = consumedSegment;
				long length = BufferSegment.GetLength(bufferSegment, _readIndex, consumedSegment, consumedIndex);
				_bufferedBytes -= length;
				_examinedEverything = false;
				if (examinedSegment == _readTail)
				{
					_examinedEverything = examinedIndex == _readTail.End;
				}
				if (_bufferedBytes == 0L)
				{
					bufferSegment2 = null;
					_readHead = null;
					_readTail = null;
					_readIndex = 0;
				}
				else if (consumedIndex == bufferSegment2.Length)
				{
					BufferSegment bufferSegment3 = (_readHead = bufferSegment2.NextSegment);
					_readIndex = 0;
					bufferSegment2 = bufferSegment3;
				}
				else
				{
					_readHead = consumedSegment;
					_readIndex = consumedIndex;
				}
				while (bufferSegment != bufferSegment2)
				{
					BufferSegment? nextSegment = bufferSegment.NextSegment;
					ReturnSegmentUnsynchronized(bufferSegment);
					bufferSegment = nextSegment;
				}
			}
		}

		public override void CancelPendingRead()
		{
			InternalTokenSource.Cancel();
		}

		public override void Complete(Exception? exception = null)
		{
			if (CompleteAndGetNeedsDispose())
			{
				InnerStream.Dispose();
			}
		}

		private bool CompleteAndGetNeedsDispose()
		{
			if (_isReaderCompleted)
			{
				return false;
			}
			_isReaderCompleted = true;
			BufferSegment bufferSegment = _readHead;
			while (bufferSegment != null)
			{
				BufferSegment bufferSegment2 = bufferSegment;
				bufferSegment = bufferSegment.NextSegment;
				bufferSegment2.Reset();
			}
			return !LeaveOpen;
		}

		public override ValueTask<ReadResult> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return ReadInternalAsync(null, cancellationToken);
		}

		protected override ValueTask<ReadResult> ReadAtLeastAsyncCore(int minimumSize, CancellationToken cancellationToken)
		{
			return ReadInternalAsync(minimumSize, cancellationToken);
		}

		private ValueTask<ReadResult> ReadInternalAsync(int? minimumSize, CancellationToken cancellationToken)
		{
			ThrowIfCompleted();
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<ReadResult>(Task.FromCanceled<ReadResult>(cancellationToken));
			}
			CancellationTokenSource internalTokenSource = InternalTokenSource;
			if (TryReadInternal(internalTokenSource, out var result) && (!minimumSize.HasValue || result.Buffer.Length >= minimumSize || result.IsCompleted || result.IsCanceled))
			{
				return new ValueTask<ReadResult>(result);
			}
			if (_isStreamCompleted)
			{
				return new ValueTask<ReadResult>(new ReadResult(default(ReadOnlySequence<byte>), isCanceled: false, isCompleted: true));
			}
			return Core(this, minimumSize, internalTokenSource, cancellationToken);
			static async ValueTask<ReadResult> Core(StreamPipeReader reader, int? minimumSize, CancellationTokenSource tokenSource, CancellationToken cancellationToken)
			{
				CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
				if (cancellationToken.CanBeCanceled)
				{
					cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
					{
						((StreamPipeReader)state).Cancel();
					}, reader);
				}
				using (cancellationTokenRegistration)
				{
					bool isCanceled = false;
					try
					{
						if (reader.UseZeroByteReads && reader._bufferedBytes == 0L)
						{
							await StreamExtensions.ReadAsync(reader.InnerStream, Memory<byte>.Empty, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
						}
						do
						{
							reader.AllocateReadTail(minimumSize);
							Memory<byte> buffer = reader._readTail.AvailableMemory.Slice(reader._readTail.End);
							int num = await StreamExtensions.ReadAsync(reader.InnerStream, buffer, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							reader._readTail.End += num;
							reader._bufferedBytes += num;
							if (num == 0)
							{
								reader._isStreamCompleted = true;
								break;
							}
						}
						while (minimumSize.HasValue && reader._bufferedBytes < minimumSize);
					}
					catch (OperationCanceledException ex)
					{
						reader.ClearCancellationToken();
						if (cancellationToken.IsCancellationRequested)
						{
							throw new OperationCanceledException(ex.Message, ex, cancellationToken);
						}
						if (!tokenSource.IsCancellationRequested)
						{
							throw;
						}
						isCanceled = true;
					}
					return new ReadResult(reader.GetCurrentReadOnlySequence(), isCanceled, reader._isStreamCompleted);
				}
			}
		}

		public override async Task CopyToAsync(PipeWriter destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			ThrowIfCompleted();
			CancellationTokenSource tokenSource = InternalTokenSource;
			if (tokenSource.IsCancellationRequested)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
				{
					((StreamPipeReader)state).Cancel();
				}, this);
			}
			using (cancellationTokenRegistration)
			{
				_ = 1;
				try
				{
					BufferSegment segment = _readHead;
					int start = _readIndex;
					try
					{
						while (segment != null)
						{
							FlushResult flushResult = await destination.WriteAsync(segment.Memory.Slice(start), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							if (flushResult.IsCanceled)
							{
								ThrowHelper.ThrowOperationCanceledException_FlushCanceled();
							}
							segment = segment.NextSegment;
							start = 0;
							if (flushResult.IsCompleted)
							{
								return;
							}
						}
					}
					finally
					{
						if (segment != null)
						{
							AdvanceTo(segment, segment.End, segment, segment.End);
						}
					}
					if (!_isStreamCompleted)
					{
						await InnerStream.CopyToAsync(destination, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
					}
				}
				catch (OperationCanceledException)
				{
					ClearCancellationToken();
					throw;
				}
			}
		}

		public override async Task CopyToAsync(Stream destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			ThrowIfCompleted();
			CancellationTokenSource tokenSource = InternalTokenSource;
			if (tokenSource.IsCancellationRequested)
			{
				ThrowHelper.ThrowOperationCanceledException_ReadCanceled();
			}
			CancellationTokenRegistration cancellationTokenRegistration = default(CancellationTokenRegistration);
			if (cancellationToken.CanBeCanceled)
			{
				cancellationTokenRegistration = CancellationTokenExtensions.UnsafeRegister(cancellationToken, delegate(object state)
				{
					((StreamPipeReader)state).Cancel();
				}, this);
			}
			using (cancellationTokenRegistration)
			{
				_ = 1;
				try
				{
					BufferSegment segment = _readHead;
					int start = _readIndex;
					try
					{
						while (segment != null)
						{
							await StreamExtensions.WriteAsync(destination, segment.Memory.Slice(start), tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
							segment = segment.NextSegment;
							start = 0;
						}
					}
					finally
					{
						if (segment != null)
						{
							AdvanceTo(segment, segment.End, segment, segment.End);
						}
					}
					if (!_isStreamCompleted)
					{
						await StreamExtensions.CopyToAsync(InnerStream, destination, tokenSource.Token).ConfigureAwait(continueOnCapturedContext: false);
					}
				}
				catch (OperationCanceledException)
				{
					ClearCancellationToken();
					throw;
				}
			}
		}

		private void ClearCancellationToken()
		{
			lock (_lock)
			{
				_internalTokenSource = null;
			}
		}

		private void ThrowIfCompleted()
		{
			if (_isReaderCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoReadingAllowed();
			}
		}

		public override bool TryRead(out ReadResult result)
		{
			ThrowIfCompleted();
			return TryReadInternal(InternalTokenSource, out result);
		}

		private bool TryReadInternal(CancellationTokenSource source, out ReadResult result)
		{
			bool isCancellationRequested = source.IsCancellationRequested;
			if (isCancellationRequested || (_bufferedBytes > 0 && (!_examinedEverything || _isStreamCompleted)))
			{
				if (isCancellationRequested)
				{
					ClearCancellationToken();
				}
				ReadOnlySequence<byte> currentReadOnlySequence = GetCurrentReadOnlySequence();
				result = new ReadResult(currentReadOnlySequence, isCancellationRequested, _isStreamCompleted);
				return true;
			}
			result = default(ReadResult);
			return false;
		}

		private ReadOnlySequence<byte> GetCurrentReadOnlySequence()
		{
			if (_readHead != null)
			{
				return new ReadOnlySequence<byte>(_readHead, _readIndex, _readTail, _readTail.End);
			}
			return default(ReadOnlySequence<byte>);
		}

		private void AllocateReadTail(int? minimumSize = null)
		{
			if (_readHead == null)
			{
				_readHead = AllocateSegment(minimumSize);
				_readTail = _readHead;
			}
			else if (_readTail.WritableBytes < MinimumReadThreshold)
			{
				BufferSegment bufferSegment = AllocateSegment(minimumSize);
				_readTail.SetNext(bufferSegment);
				_readTail = bufferSegment;
			}
		}

		private BufferSegment AllocateSegment(int? minimumSize = null)
		{
			BufferSegment bufferSegment = CreateSegmentUnsynchronized();
			int num = minimumSize ?? BufferSize;
			int num2 = ((!_options.IsDefaultSharedMemoryPool) ? _options.Pool.MaxBufferSize : (-1));
			if (num <= num2)
			{
				int segmentSize = GetSegmentSize(num, num2);
				bufferSegment.SetOwnedMemory(_options.Pool.Rent(segmentSize));
			}
			else
			{
				int segmentSize2 = GetSegmentSize(num, MaxBufferSize);
				bufferSegment.SetOwnedMemory(ArrayPool<byte>.Shared.Rent(segmentSize2));
			}
			return bufferSegment;
		}

		private int GetSegmentSize(int sizeHint, int maxBufferSize)
		{
			sizeHint = Math.Max(BufferSize, sizeHint);
			return Math.Min(maxBufferSize, sizeHint);
		}

		private BufferSegment CreateSegmentUnsynchronized()
		{
			if (_bufferSegmentPool.TryPop(out BufferSegment result))
			{
				return result;
			}
			return new BufferSegment();
		}

		private void ReturnSegmentUnsynchronized(BufferSegment segment)
		{
			segment.Reset();
			if (_bufferSegmentPool.Count < 256)
			{
				_bufferSegmentPool.Push(segment);
			}
		}

		private void Cancel()
		{
			InternalTokenSource.Cancel();
		}
	}
	public class StreamPipeReaderOptions
	{
		private const int DefaultBufferSize = 4096;

		internal const int DefaultMaxBufferSize = 2097152;

		private const int DefaultMinimumReadSize = 1024;

		internal static readonly StreamPipeReaderOptions s_default = new StreamPipeReaderOptions();

		public int BufferSize { get; }

		internal int MaxBufferSize { get; } = 2097152;


		public int MinimumReadSize { get; }

		public MemoryPool<byte> Pool { get; }

		public bool LeaveOpen { get; }

		public bool UseZeroByteReads { get; }

		internal bool IsDefaultSharedMemoryPool { get; }

		public StreamPipeReaderOptions(MemoryPool<byte>? pool, int bufferSize, int minimumReadSize, bool leaveOpen)
			: this(pool, bufferSize, minimumReadSize, leaveOpen, useZeroByteReads: false)
		{
		}

		public StreamPipeReaderOptions(MemoryPool<byte>? pool = null, int bufferSize = -1, int minimumReadSize = -1, bool leaveOpen = false, bool useZeroByteReads = false)
		{
			Pool = pool ?? MemoryPool<byte>.Shared;
			IsDefaultSharedMemoryPool = Pool == MemoryPool<byte>.Shared;
			int num;
			if (bufferSize != -1)
			{
				if (bufferSize <= 0)
				{
					throw new ArgumentOutOfRangeException("bufferSize");
				}
				num = bufferSize;
			}
			else
			{
				num = 4096;
			}
			BufferSize = num;
			int num2;
			if (minimumReadSize != -1)
			{
				if (minimumReadSize <= 0)
				{
					throw new ArgumentOutOfRangeException("minimumReadSize");
				}
				num2 = minimumReadSize;
			}
			else
			{
				num2 = 1024;
			}
			MinimumReadSize = num2;
			LeaveOpen = leaveOpen;
			UseZeroByteReads = useZeroByteReads;
		}
	}
	internal sealed class StreamPipeWriter : PipeWriter
	{
		internal const int InitialSegmentPoolSize = 4;

		internal const int MaxSegmentPoolSize = 256;

		private readonly int _minimumBufferSize;

		private BufferSegment _head;

		private BufferSegment _tail;

		private Memory<byte> _tailMemory;

		private int _tailBytesBuffered;

		private long _bytesBuffered;

		private readonly MemoryPool<byte> _pool;

		private readonly int _maxPooledBufferSize;

		private CancellationTokenSource _internalTokenSource;

		private bool _isCompleted;

		private readonly object _lockObject = new object();

		private BufferSegmentStack _bufferSegmentPool;

		private readonly bool _leaveOpen;

		private CancellationTokenSource InternalTokenSource
		{
			get
			{
				lock (_lockObject)
				{
					return _internalTokenSource ?? (_internalTokenSource = new CancellationTokenSource());
				}
			}
		}

		public Stream InnerStream { get; }

		public override bool CanGetUnflushedBytes => true;

		public override long UnflushedBytes => _bytesBuffered;

		public StreamPipeWriter(Stream writingStream, StreamPipeWriterOptions options)
		{
			if (writingStream == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.writingStream);
			}
			if (options == null)
			{
				ThrowHelper.ThrowArgumentNullException(ExceptionArgument.options);
			}
			InnerStream = writingStream;
			_minimumBufferSize = options.MinimumBufferSize;
			_pool = ((options.Pool == MemoryPool<byte>.Shared) ? null : options.Pool);
			_maxPooledBufferSize = _pool?.MaxBufferSize ?? (-1);
			_bufferSegmentPool = new BufferSegmentStack(4);
			_leaveOpen = options.LeaveOpen;
		}

		public override void Advance(int bytes)
		{
			if ((uint)bytes > (uint)_tailMemory.Length)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes);
			}
			_tailBytesBuffered += bytes;
			_bytesBuffered += bytes;
			_tailMemory = _tailMemory.Slice(bytes);
		}

		public override Memory<byte> GetMemory(int sizeHint = 0)
		{
			if (_isCompleted)
			{
				ThrowHelper.ThrowInvalidOperationException_NoWritingAllowed();
			}
			if (sizeHint < 0)
			{
				ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.sizeHint);
			}
			AllocateMemory(sizeHi

BepInEx/core/System.Memory.Data.dll

Decompiled 2 weeks ago
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Threading;
using System.Threading.Tasks;
using FxResources.System.Memory.Data;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Memory.Data")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("A lightweight abstraction for a payload of bytes. Provides methods for converting between strings, streams, JSON, and bytes.\r\n\r\nCommonly Used Types:\r\nSystem.BinaryData")]
[assembly: AssemblyFileVersion("8.0.1024.46610")]
[assembly: AssemblyInformationalVersion("8.0.10+81cabf2857a01351e5ab578947c7403a5b128ad1")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Memory.Data")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("8.0.0.1")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.System.Memory.Data
{
	internal static class SR
	{
	}
}
namespace System
{
	[JsonConverter(typeof(BinaryDataJsonConverter))]
	public class BinaryData
	{
		private const string JsonSerializerRequiresDynamicCode = "JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.";

		private const string JsonSerializerRequiresUnreferencedCode = "JSON serialization and deserialization might require types that cannot be statically analyzed.";

		private const string MediaTypeApplicationJson = "application/json";

		private readonly ReadOnlyMemory<byte> _bytes;

		public static BinaryData Empty { get; } = new BinaryData(ReadOnlyMemory<byte>.Empty);


		public int Length => _bytes.Length;

		public bool IsEmpty => _bytes.IsEmpty;

		public string? MediaType { get; }

		public BinaryData(byte[] data)
		{
			_bytes = data ?? throw new ArgumentNullException("data");
		}

		public BinaryData(byte[] data, string? mediaType)
			: this(data)
		{
			MediaType = mediaType;
		}

		[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.")]
		[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
		public BinaryData(object? jsonSerializable, JsonSerializerOptions? options = null, Type? type = null)
			: this(JsonSerializer.SerializeToUtf8Bytes(jsonSerializable, type ?? jsonSerializable?.GetType() ?? typeof(object), options), "application/json")
		{
		}

		public BinaryData(object? jsonSerializable, JsonSerializerContext context, Type? type = null)
			: this(JsonSerializer.SerializeToUtf8Bytes(jsonSerializable, type ?? jsonSerializable?.GetType() ?? typeof(object), context), "application/json")
		{
		}

		public BinaryData(ReadOnlyMemory<byte> data)
		{
			_bytes = data;
		}

		public BinaryData(ReadOnlyMemory<byte> data, string? mediaType)
			: this(data)
		{
			MediaType = mediaType;
		}

		public BinaryData(string data)
		{
			if (data == null)
			{
				throw new ArgumentNullException("data");
			}
			_bytes = Encoding.UTF8.GetBytes(data);
		}

		public BinaryData(string data, string? mediaType)
			: this(data)
		{
			MediaType = mediaType;
		}

		public static BinaryData FromBytes(ReadOnlyMemory<byte> data)
		{
			return new BinaryData(data);
		}

		public static BinaryData FromBytes(ReadOnlyMemory<byte> data, string? mediaType)
		{
			return new BinaryData(data, mediaType);
		}

		public static BinaryData FromBytes(byte[] data)
		{
			return new BinaryData(data);
		}

		public static BinaryData FromBytes(byte[] data, string? mediaType)
		{
			return new BinaryData(data, mediaType);
		}

		public static BinaryData FromString(string data)
		{
			return new BinaryData(data);
		}

		public static BinaryData FromString(string data, string? mediaType)
		{
			return new BinaryData(data, mediaType);
		}

		public static BinaryData FromStream(Stream stream)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			return FromStreamAsync(stream, async: false).GetAwaiter().GetResult();
		}

		public static BinaryData FromStream(Stream stream, string? mediaType)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			return FromStreamAsync(stream, async: false, mediaType).GetAwaiter().GetResult();
		}

		public static Task<BinaryData> FromStreamAsync(Stream stream, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			return FromStreamAsync(stream, async: true, null, cancellationToken);
		}

		public static Task<BinaryData> FromStreamAsync(Stream stream, string? mediaType, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			return FromStreamAsync(stream, async: true, mediaType, cancellationToken);
		}

		private static async Task<BinaryData> FromStreamAsync(Stream stream, bool async, string mediaType = null, CancellationToken cancellationToken = default(CancellationToken))
		{
			int bufferSize = 81920;
			MemoryStream memoryStream;
			if (stream.CanSeek)
			{
				long num = stream.Length - stream.Position;
				if (num > int.MaxValue || num < 0)
				{
					throw new ArgumentOutOfRangeException("stream", System.SR.ArgumentOutOfRange_StreamLengthMustBeNonNegativeInt32);
				}
				bufferSize = ((num == 0L) ? 1 : Math.Min((int)num, 81920));
				memoryStream = new MemoryStream((int)num);
			}
			else
			{
				memoryStream = new MemoryStream();
			}
			using (memoryStream)
			{
				if (async)
				{
					await stream.CopyToAsync(memoryStream, bufferSize, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				}
				else
				{
					stream.CopyTo(memoryStream, bufferSize);
				}
				return new BinaryData(memoryStream.GetBuffer().AsMemory(0, (int)memoryStream.Position), mediaType);
			}
		}

		[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.")]
		[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
		public static BinaryData FromObjectAsJson<T>(T jsonSerializable, JsonSerializerOptions? options = null)
		{
			return new BinaryData(JsonSerializer.SerializeToUtf8Bytes(jsonSerializable, options), "application/json");
		}

		public static BinaryData FromObjectAsJson<T>(T jsonSerializable, JsonTypeInfo<T> jsonTypeInfo)
		{
			return new BinaryData(JsonSerializer.SerializeToUtf8Bytes(jsonSerializable, jsonTypeInfo), "application/json");
		}

		public BinaryData WithMediaType(string? mediaType)
		{
			return new BinaryData(_bytes, mediaType);
		}

		public unsafe override string ToString()
		{
			ReadOnlySpan<byte> span = _bytes.Span;
			if (span.IsEmpty)
			{
				return string.Empty;
			}
			fixed (byte* bytes = span)
			{
				return Encoding.UTF8.GetString(bytes, span.Length);
			}
		}

		public Stream ToStream()
		{
			return new System.IO.ReadOnlyMemoryStream(_bytes);
		}

		public ReadOnlyMemory<byte> ToMemory()
		{
			return _bytes;
		}

		public byte[] ToArray()
		{
			return _bytes.ToArray();
		}

		[RequiresDynamicCode("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation.")]
		[RequiresUnreferencedCode("JSON serialization and deserialization might require types that cannot be statically analyzed.")]
		public T? ToObjectFromJson<T>(JsonSerializerOptions? options = null)
		{
			return JsonSerializer.Deserialize<T>(GetBytesWithTrimmedBom(), options);
		}

		public T? ToObjectFromJson<T>(JsonTypeInfo<T> jsonTypeInfo)
		{
			return JsonSerializer.Deserialize(GetBytesWithTrimmedBom(), jsonTypeInfo);
		}

		private ReadOnlySpan<byte> GetBytesWithTrimmedBom()
		{
			ReadOnlySpan<byte> result = _bytes.Span;
			if (result.Length > 2 && result[0] == 239 && result[1] == 187 && result[2] == 191)
			{
				result = result.Slice(3);
			}
			return result;
		}

		public static implicit operator ReadOnlyMemory<byte>(BinaryData? data)
		{
			return data?._bytes ?? default(ReadOnlyMemory<byte>);
		}

		public static implicit operator ReadOnlySpan<byte>(BinaryData? data)
		{
			return data?._bytes.Span ?? default(ReadOnlySpan<byte>);
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override bool Equals([NotNullWhen(true)] object? obj)
		{
			return this == obj;
		}

		[EditorBrowsable(EditorBrowsableState.Never)]
		public override int GetHashCode()
		{
			return base.GetHashCode();
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum");

		internal static string ArgumentOutOfRange_StreamLengthMustBeNonNegativeInt32 => GetResourceString("ArgumentOutOfRange_StreamLengthMustBeNonNegativeInt32");

		internal static string Argument_InvalidOffLen => GetResourceString("Argument_InvalidOffLen");

		internal static string IO_SeekBeforeBegin => GetResourceString("IO_SeekBeforeBegin");

		internal static string ObjectDisposed_StreamClosed => GetResourceString("ObjectDisposed_StreamClosed");

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Threading.Tasks
{
	internal static class TaskToAsyncResult
	{
		private sealed class TaskAsyncResult : IAsyncResult
		{
			internal readonly Task _task;

			private readonly AsyncCallback _callback;

			public object AsyncState { get; }

			public bool CompletedSynchronously { get; }

			public bool IsCompleted => _task.IsCompleted;

			public WaitHandle AsyncWaitHandle => ((IAsyncResult)_task).AsyncWaitHandle;

			internal TaskAsyncResult(Task task, object state, AsyncCallback callback)
			{
				_task = task;
				AsyncState = state;
				if (task.IsCompleted)
				{
					CompletedSynchronously = true;
					callback?.Invoke(this);
				}
				else if (callback != null)
				{
					_callback = callback;
					_task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter().OnCompleted(delegate
					{
						_callback(this);
					});
				}
			}
		}

		public static IAsyncResult Begin(Task task, AsyncCallback callback, object state)
		{
			if (task == null)
			{
				throw new ArgumentNullException("task");
			}
			return new TaskAsyncResult(task, state, callback);
		}

		public static void End(IAsyncResult asyncResult)
		{
			Unwrap(asyncResult).GetAwaiter().GetResult();
		}

		public static TResult End<TResult>(IAsyncResult asyncResult)
		{
			return Unwrap<TResult>(asyncResult).GetAwaiter().GetResult();
		}

		public static Task Unwrap(IAsyncResult asyncResult)
		{
			if (asyncResult == null)
			{
				throw new ArgumentNullException("asyncResult");
			}
			Task task = (asyncResult as TaskAsyncResult)?._task;
			if (task == null)
			{
				throw new ArgumentException(null, "asyncResult");
			}
			return task;
		}

		public static Task<TResult> Unwrap<TResult>(IAsyncResult asyncResult)
		{
			if (asyncResult == null)
			{
				throw new ArgumentNullException("asyncResult");
			}
			if (!((asyncResult as TaskAsyncResult)?._task is Task<TResult> result))
			{
				throw new ArgumentException(null, "asyncResult");
			}
			return result;
		}
	}
}
namespace System.Text.Json.Serialization
{
	public sealed class BinaryDataJsonConverter : JsonConverter<BinaryData>
	{
		public override BinaryData? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
		{
			return BinaryData.FromBytes(reader.GetBytesFromBase64());
		}

		public override void Write(Utf8JsonWriter writer, BinaryData value, JsonSerializerOptions options)
		{
			writer.WriteBase64StringValue(value.ToMemory().Span);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.IO
{
	internal sealed class ReadOnlyMemoryStream : Stream
	{
		private ReadOnlyMemory<byte> _content;

		private int _position;

		private bool _isOpen;

		public override bool CanRead => _isOpen;

		public override bool CanSeek => _isOpen;

		public override bool CanWrite => false;

		public override long Length
		{
			get
			{
				EnsureNotClosed();
				return _content.Length;
			}
		}

		public override long Position
		{
			get
			{
				EnsureNotClosed();
				return _position;
			}
			set
			{
				EnsureNotClosed();
				if (value < 0 || value > int.MaxValue)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_position = (int)value;
			}
		}

		public ReadOnlyMemoryStream(ReadOnlyMemory<byte> content)
		{
			_content = content;
			_isOpen = true;
		}

		private void EnsureNotClosed()
		{
			if (!_isOpen)
			{
				throw new ObjectDisposedException(null, System.SR.ObjectDisposed_StreamClosed);
			}
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			EnsureNotClosed();
			long num = origin switch
			{
				SeekOrigin.End => _content.Length + offset, 
				SeekOrigin.Current => _position + offset, 
				SeekOrigin.Begin => offset, 
				_ => throw new ArgumentOutOfRangeException("origin"), 
			};
			if (num > int.MaxValue)
			{
				throw new ArgumentOutOfRangeException("offset");
			}
			if (num < 0)
			{
				throw new IOException(System.SR.IO_SeekBeforeBegin);
			}
			_position = (int)num;
			return _position;
		}

		public override int ReadByte()
		{
			EnsureNotClosed();
			ReadOnlySpan<byte> span = _content.Span;
			if (_position >= span.Length)
			{
				return -1;
			}
			return span[_position++];
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			ValidateBufferArguments(buffer, offset, count);
			return ReadBuffer(new Span<byte>(buffer, offset, count));
		}

		private int ReadBuffer(Span<byte> buffer)
		{
			EnsureNotClosed();
			int num = _content.Length - _position;
			if (num <= 0 || buffer.Length == 0)
			{
				return 0;
			}
			ReadOnlySpan<byte> readOnlySpan;
			if (num <= buffer.Length)
			{
				readOnlySpan = _content.Span;
				readOnlySpan = readOnlySpan.Slice(_position);
				readOnlySpan.CopyTo(buffer);
				_position = _content.Length;
				return num;
			}
			readOnlySpan = _content.Span;
			readOnlySpan = readOnlySpan.Slice(_position, buffer.Length);
			readOnlySpan.CopyTo(buffer);
			_position += buffer.Length;
			return buffer.Length;
		}

		public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
		{
			ValidateBufferArguments(buffer, offset, count);
			EnsureNotClosed();
			if (!cancellationToken.IsCancellationRequested)
			{
				return Task.FromResult(ReadBuffer(new Span<byte>(buffer, offset, count)));
			}
			return Task.FromCanceled<int>(cancellationToken);
		}

		public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
		{
			return TaskToAsyncResult.Begin(ReadAsync(buffer, offset, count), callback, state);
		}

		public override int EndRead(IAsyncResult asyncResult)
		{
			EnsureNotClosed();
			return TaskToAsyncResult.End<int>(asyncResult);
		}

		public override void Flush()
		{
		}

		public override Task FlushAsync(CancellationToken cancellationToken)
		{
			return Task.CompletedTask;
		}

		public override void SetLength(long value)
		{
			throw new NotSupportedException();
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			throw new NotSupportedException();
		}

		protected override void Dispose(bool disposing)
		{
			_isOpen = false;
			_content = default(ReadOnlyMemory<byte>);
			base.Dispose(disposing);
		}

		private new static void ValidateBufferArguments(byte[] buffer, int offset, int count)
		{
			if (buffer == null)
			{
				throw new ArgumentNullException("buffer");
			}
			if (offset < 0)
			{
				throw new ArgumentOutOfRangeException("offset", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if ((uint)count > buffer.Length - offset)
			{
				throw new ArgumentOutOfRangeException("count", System.SR.Argument_InvalidOffLen);
			}
		}
	}
}

BepInEx/core/System.Memory.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Memory")]
[assembly: AssemblyDescription("System.Memory")]
[assembly: AssemblyDefaultAlias("System.Memory")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("4.0.99.0")]
[assembly: AssemblyFileVersion("4.0.99.0")]
[assembly: AssemblyVersion("4.0.99.0")]
[assembly: TypeForwardedTo(typeof(BinaryPrimitives))]
[assembly: TypeForwardedTo(typeof(BuffersExtensions))]
[assembly: TypeForwardedTo(typeof(IBufferWriter<>))]
[assembly: TypeForwardedTo(typeof(IMemoryOwner<>))]
[assembly: TypeForwardedTo(typeof(IPinnable))]
[assembly: TypeForwardedTo(typeof(MemoryHandle))]
[assembly: TypeForwardedTo(typeof(MemoryManager<>))]
[assembly: TypeForwardedTo(typeof(MemoryPool<>))]
[assembly: TypeForwardedTo(typeof(OperationStatus))]
[assembly: TypeForwardedTo(typeof(ReadOnlySequence<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySequenceSegment<>))]
[assembly: TypeForwardedTo(typeof(StandardFormat))]
[assembly: TypeForwardedTo(typeof(Base64))]
[assembly: TypeForwardedTo(typeof(Utf8Formatter))]
[assembly: TypeForwardedTo(typeof(Utf8Parser))]
[assembly: TypeForwardedTo(typeof(Memory<>))]
[assembly: TypeForwardedTo(typeof(MemoryExtensions))]
[assembly: TypeForwardedTo(typeof(ReadOnlyMemory<>))]
[assembly: TypeForwardedTo(typeof(ReadOnlySpan<>))]
[assembly: TypeForwardedTo(typeof(MemoryMarshal))]
[assembly: TypeForwardedTo(typeof(SequenceMarshal))]
[assembly: TypeForwardedTo(typeof(SequencePosition))]
[assembly: TypeForwardedTo(typeof(Span<>))]

BepInEx/core/System.Net.Http.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Cache;
using System.Net.Http.Headers;
using System.Net.Mail;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Mono.Net.Security;
using Mono.Security.Interface;
using Unity;

[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("System.Net.Http.WebRequest, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: AssemblyDelaySign(true)]
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyTitle("System.Net.Http.dll")]
[assembly: AssemblyDescription("System.Net.Http.dll")]
[assembly: AssemblyDefaultAlias("System.Net.Http.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
namespace System.Net.Http
{
	internal static class ConnectHelper
	{
		internal sealed class CertificateCallbackMapper
		{
			public readonly Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> FromHttpClientHandler;

			public readonly RemoteCertificateValidationCallback ForSocketsHttpHandler;

			public CertificateCallbackMapper(Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> fromHttpClientHandler)
			{
				FromHttpClientHandler = fromHttpClientHandler;
				ForSocketsHttpHandler = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => FromHttpClientHandler(new HttpRequestMessage(HttpMethod.Get, (string)sender), certificate as X509Certificate2, chain, sslPolicyErrors);
			}
		}

		private sealed class ConnectEventArgs : SocketAsyncEventArgs
		{
			public AsyncTaskMethodBuilder Builder { get; private set; }

			public CancellationToken CancellationToken { get; private set; }

			public void Initialize(CancellationToken cancellationToken)
			{
				CancellationToken = cancellationToken;
				AsyncTaskMethodBuilder builder = default(AsyncTaskMethodBuilder);
				_ = builder.Task;
				Builder = builder;
			}

			public void Clear()
			{
				CancellationToken = default(CancellationToken);
			}

			protected override void OnCompleted(SocketAsyncEventArgs _)
			{
				switch (base.SocketError)
				{
				case SocketError.Success:
					Builder.SetResult();
					return;
				case SocketError.OperationAborted:
				case SocketError.ConnectionAborted:
					if (CancellationToken.IsCancellationRequested)
					{
						Builder.SetException(CancellationHelper.CreateOperationCanceledException(null, CancellationToken));
						return;
					}
					break;
				}
				Builder.SetException(new SocketException((int)base.SocketError));
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <ConnectAsync>d__2 : IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncValueTaskMethodBuilder<(Socket, Stream)> <>t__builder;

			public CancellationToken cancellationToken;

			public string host;

			public int port;

			private ConnectEventArgs <saea>5__2;

			private CancellationTokenRegistration <>7__wrap2;

			private ConfiguredTaskAwaitable.ConfiguredTaskAwaiter <>u__1;

			private void MoveNext()
			{
				int num = <>1__state;
				(Socket, Stream) result;
				try
				{
					if (num != 0 && !s_connectEventArgs.TryDequeue(ref <saea>5__2))
					{
						<saea>5__2 = new ConnectEventArgs();
					}
					try
					{
						if (num != 0)
						{
							<saea>5__2.Initialize(cancellationToken);
							<saea>5__2.RemoteEndPoint = new DnsEndPoint(host, port);
							if (!Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, <saea>5__2))
							{
								if (<saea>5__2.SocketError != 0)
								{
									throw new SocketException((int)<saea>5__2.SocketError);
								}
								goto IL_015b;
							}
							<>7__wrap2 = cancellationToken.Register(delegate(object s)
							{
								Socket.CancelConnectAsync((SocketAsyncEventArgs)s);
							}, <saea>5__2);
						}
						try
						{
							ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter;
							if (num != 0)
							{
								awaiter = <saea>5__2.Builder.Task.ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
								if (!awaiter.IsCompleted)
								{
									num = (<>1__state = 0);
									<>u__1 = awaiter;
									<>t__builder.AwaitUnsafeOnCompleted<ConfiguredTaskAwaitable.ConfiguredTaskAwaiter, <ConnectAsync>d__2>(ref awaiter, ref this);
									return;
								}
							}
							else
							{
								awaiter = <>u__1;
								<>u__1 = default(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter);
								num = (<>1__state = -1);
							}
							awaiter.GetResult();
						}
						finally
						{
							if (num < 0)
							{
								((IDisposable)<>7__wrap2).Dispose();
							}
						}
						<>7__wrap2 = default(CancellationTokenRegistration);
						goto IL_015b;
						IL_015b:
						Socket connectSocket = <saea>5__2.ConnectSocket;
						connectSocket.NoDelay = true;
						result = (connectSocket, new NetworkStream(connectSocket, ownsSocket: true));
					}
					catch (Exception ex)
					{
						throw CancellationHelper.ShouldWrapInOperationCanceledException(ex, cancellationToken) ? CancellationHelper.CreateOperationCanceledException(ex, cancellationToken) : new HttpRequestException(ex.Message, ex);
					}
					finally
					{
						if (num < 0)
						{
							<saea>5__2.Clear();
							if (!s_connectEventArgs.TryEnqueue(<saea>5__2))
							{
								<saea>5__2.Dispose();
							}
						}
					}
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<saea>5__2 = null;
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<saea>5__2 = null;
				<>t__builder.SetResult(result);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		[StructLayout(LayoutKind.Auto)]
		[CompilerGenerated]
		private struct <EstablishSslConnectionAsyncCore>d__5 : IAsyncStateMachine
		{
			public int <>1__state;

			public AsyncValueTaskMethodBuilder<SslStream> <>t__builder;

			public Stream stream;

			public CancellationToken cancellationToken;

			public SslClientAuthenticationOptions sslOptions;

			private SslStream <sslStream>5__2;

			private CancellationTokenRegistration <ctr>5__3;

			private ConfiguredTaskAwaitable.ConfiguredTaskAwaiter <>u__1;

			private void MoveNext()
			{
				int num = <>1__state;
				SslStream result;
				try
				{
					if (num != 0)
					{
						<sslStream>5__2 = new SslStream(stream);
						<ctr>5__3 = cancellationToken.Register(delegate(object s)
						{
							((Stream)s).Dispose();
						}, stream);
					}
					try
					{
						ConfiguredTaskAwaitable.ConfiguredTaskAwaiter awaiter;
						if (num != 0)
						{
							awaiter = <sslStream>5__2.AuthenticateAsClientAsync(sslOptions, cancellationToken).ConfigureAwait(continueOnCapturedContext: false).GetAwaiter();
							if (!awaiter.IsCompleted)
							{
								num = (<>1__state = 0);
								<>u__1 = awaiter;
								<>t__builder.AwaitUnsafeOnCompleted<ConfiguredTaskAwaitable.ConfiguredTaskAwaiter, <EstablishSslConnectionAsyncCore>d__5>(ref awaiter, ref this);
								return;
							}
						}
						else
						{
							awaiter = <>u__1;
							<>u__1 = default(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter);
							num = (<>1__state = -1);
						}
						awaiter.GetResult();
					}
					catch (Exception ex)
					{
						<sslStream>5__2.Dispose();
						if (CancellationHelper.ShouldWrapInOperationCanceledException(ex, cancellationToken))
						{
							throw CancellationHelper.CreateOperationCanceledException(ex, cancellationToken);
						}
						throw new HttpRequestException("The SSL connection could not be established, see inner exception.", ex);
					}
					finally
					{
						if (num < 0)
						{
							<ctr>5__3.Dispose();
						}
					}
					if (cancellationToken.IsCancellationRequested)
					{
						<sslStream>5__2.Dispose();
						throw CancellationHelper.CreateOperationCanceledException(null, cancellationToken);
					}
					result = <sslStream>5__2;
				}
				catch (Exception exception)
				{
					<>1__state = -2;
					<sslStream>5__2 = null;
					<ctr>5__3 = default(CancellationTokenRegistration);
					<>t__builder.SetException(exception);
					return;
				}
				<>1__state = -2;
				<sslStream>5__2 = null;
				<ctr>5__3 = default(CancellationTokenRegistration);
				<>t__builder.SetResult(result);
			}

			void IAsyncStateMachine.MoveNext()
			{
				//ILSpy generated this explicit interface implementation from .override directive in MoveNext
				this.MoveNext();
			}

			[DebuggerHidden]
			private void SetStateMachine(IAsyncStateMachine stateMachine)
			{
				<>t__builder.SetStateMachine(stateMachine);
			}

			void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
			{
				//ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
				this.SetStateMachine(stateMachine);
			}
		}

		private static readonly Segment<ConnectEventArgs> s_connectEventArgs = new Segment<ConnectEventArgs>(Segment<ConnectEventArgs>.RoundUpToPowerOf2(Math.Max(2, Environment.ProcessorCount)));

		[AsyncStateMachine(typeof(<ConnectAsync>d__2))]
		public static ValueTask<(Socket, Stream)> ConnectAsync(string host, int port, CancellationToken cancellationToken)
		{
			//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_0041: Unknown result type (might be due to invalid IL or missing references)
			<ConnectAsync>d__2 <ConnectAsync>d__ = default(<ConnectAsync>d__2);
			<ConnectAsync>d__.host = host;
			<ConnectAsync>d__.port = port;
			<ConnectAsync>d__.cancellationToken = cancellationToken;
			<ConnectAsync>d__.<>t__builder = AsyncValueTaskMethodBuilder<(Socket, Stream)>.Create();
			<ConnectAsync>d__.<>1__state = -1;
			<ConnectAsync>d__.<>t__builder.Start<<ConnectAsync>d__2>(ref <ConnectAsync>d__);
			return <ConnectAsync>d__.<>t__builder.Task;
		}

		public static ValueTask<SslStream> EstablishSslConnectionAsync(SslClientAuthenticationOptions sslOptions, HttpRequestMessage request, Stream stream, CancellationToken cancellationToken)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			RemoteCertificateValidationCallback remoteCertificateValidationCallback = sslOptions.RemoteCertificateValidationCallback;
			if (remoteCertificateValidationCallback != null && remoteCertificateValidationCallback.Target is CertificateCallbackMapper certificateCallbackMapper)
			{
				sslOptions = SslClientAuthenticationOptionsExtensions.ShallowClone(sslOptions);
				Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> localFromHttpClientHandler = certificateCallbackMapper.FromHttpClientHandler;
				HttpRequestMessage localRequest = request;
				sslOptions.RemoteCertificateValidationCallback = (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) => localFromHttpClientHandler(localRequest, certificate as X509Certificate2, chain, sslPolicyErrors);
			}
			return EstablishSslConnectionAsyncCore(stream, sslOptions, cancellationToken);
		}

		[AsyncStateMachine(typeof(<EstablishSslConnectionAsyncCore>d__5))]
		private static ValueTask<SslStream> EstablishSslConnectionAsyncCore(Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
		{
			//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_0041: Unknown result type (might be due to invalid IL or missing references)
			<EstablishSslConnectionAsyncCore>d__5 <EstablishSslConnectionAsyncCore>d__ = default(<EstablishSslConnectionAsyncCore>d__5);
			<EstablishSslConnectionAsyncCore>d__.stream = stream;
			<EstablishSslConnectionAsyncCore>d__.sslOptions = sslOptions;
			<EstablishSslConnectionAsyncCore>d__.cancellationToken = cancellationToken;
			<EstablishSslConnectionAsyncCore>d__.<>t__builder = AsyncValueTaskMethodBuilder<SslStream>.Create();
			<EstablishSslConnectionAsyncCore>d__.<>1__state = -1;
			<EstablishSslConnectionAsyncCore>d__.<>t__builder.Start<<EstablishSslConnectionAsyncCore>d__5>(ref <EstablishSslConnectionAsyncCore>d__);
			return <EstablishSslConnectionAsyncCore>d__.<>t__builder.Task;
		}
	}
	internal static class HttpUtilities
	{
		internal static Version DefaultRequestVersion => HttpVersion.Version20;

		internal static Version DefaultResponseVersion => HttpVersion.Version11;

		internal static bool IsHttpUri(Uri uri)
		{
			return IsSupportedScheme(uri.Scheme);
		}

		internal static bool IsSupportedScheme(string scheme)
		{
			if (!IsSupportedNonSecureScheme(scheme))
			{
				return IsSupportedSecureScheme(scheme);
			}
			return true;
		}

		internal static bool IsSupportedNonSecureScheme(string scheme)
		{
			if (!string.Equals(scheme, "http", StringComparison.OrdinalIgnoreCase))
			{
				return IsNonSecureWebSocketScheme(scheme);
			}
			return true;
		}

		internal static bool IsSupportedSecureScheme(string scheme)
		{
			if (!string.Equals(scheme, "https", StringComparison.OrdinalIgnoreCase))
			{
				return IsSecureWebSocketScheme(scheme);
			}
			return true;
		}

		internal static bool IsNonSecureWebSocketScheme(string scheme)
		{
			return string.Equals(scheme, "ws", StringComparison.OrdinalIgnoreCase);
		}

		internal static bool IsSecureWebSocketScheme(string scheme)
		{
			return string.Equals(scheme, "wss", StringComparison.OrdinalIgnoreCase);
		}

		internal static Task ContinueWithStandard<T>(this Task<T> task, object state, Action<Task<T>, object> continuation)
		{
			return task.ContinueWith(continuation, state, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
		}
	}
	internal static class CancellationHelper
	{
		private static readonly string s_cancellationMessage = new OperationCanceledException().Message;

		internal static bool ShouldWrapInOperationCanceledException(Exception exception, CancellationToken cancellationToken)
		{
			if (!(exception is OperationCanceledException))
			{
				return cancellationToken.IsCancellationRequested;
			}
			return false;
		}

		internal static Exception CreateOperationCanceledException(Exception innerException, CancellationToken cancellationToken)
		{
			return new TaskCanceledException(s_cancellationMessage, innerException, cancellationToken);
		}

		private static void ThrowOperationCanceledException(Exception innerException, CancellationToken cancellationToken)
		{
			throw CreateOperationCanceledException(innerException, cancellationToken);
		}

		internal static void ThrowIfCancellationRequested(CancellationToken cancellationToken)
		{
			if (cancellationToken.IsCancellationRequested)
			{
				ThrowOperationCanceledException(null, cancellationToken);
			}
		}
	}
	public class HttpClientHandler : HttpMessageHandler
	{
		private readonly IMonoHttpClientHandler _delegatingHandler;

		private ClientCertificateOption _clientCertificateOptions;

		public static Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> DangerousAcceptAnyServerCertificateValidator
		{
			get
			{
				throw new PlatformNotSupportedException();
			}
		}

		public virtual bool SupportsAutomaticDecompression => _delegatingHandler.SupportsAutomaticDecompression;

		public virtual bool SupportsProxy => true;

		public virtual bool SupportsRedirectConfiguration => true;

		public bool UseCookies
		{
			get
			{
				return _delegatingHandler.UseCookies;
			}
			set
			{
				_delegatingHandler.UseCookies = value;
			}
		}

		public CookieContainer CookieContainer
		{
			get
			{
				return _delegatingHandler.CookieContainer;
			}
			set
			{
				_delegatingHandler.CookieContainer = value;
			}
		}

		public ClientCertificateOption ClientCertificateOptions
		{
			get
			{
				return _clientCertificateOptions;
			}
			set
			{
				switch (value)
				{
				case ClientCertificateOption.Manual:
					ThrowForModifiedManagedSslOptionsIfStarted();
					_clientCertificateOptions = value;
					_delegatingHandler.SslOptions.LocalCertificateSelectionCallback = (object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) => CertificateHelper.GetEligibleClientCertificate(ClientCertificates);
					break;
				case ClientCertificateOption.Automatic:
					ThrowForModifiedManagedSslOptionsIfStarted();
					_clientCertificateOptions = value;
					_delegatingHandler.SslOptions.LocalCertificateSelectionCallback = (object sender, string targetHost, X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) => CertificateHelper.GetEligibleClientCertificate();
					break;
				default:
					throw new ArgumentOutOfRangeException("value");
				}
			}
		}

		public X509CertificateCollection ClientCertificates
		{
			get
			{
				if (ClientCertificateOptions != 0)
				{
					throw new InvalidOperationException(SR.Format("The {0} property must be set to '{1}' to use this property.", (object)"ClientCertificateOptions", (object)"Manual"));
				}
				return _delegatingHandler.SslOptions.ClientCertificates ?? (_delegatingHandler.SslOptions.ClientCertificates = new X509CertificateCollection());
			}
		}

		public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback
		{
			get
			{
				return (_delegatingHandler.SslOptions.RemoteCertificateValidationCallback?.Target as ConnectHelper.CertificateCallbackMapper)?.FromHttpClientHandler;
			}
			set
			{
				ThrowForModifiedManagedSslOptionsIfStarted();
				_delegatingHandler.SslOptions.RemoteCertificateValidationCallback = ((value != null) ? new ConnectHelper.CertificateCallbackMapper(value).ForSocketsHttpHandler : null);
			}
		}

		public bool CheckCertificateRevocationList
		{
			get
			{
				return _delegatingHandler.SslOptions.CertificateRevocationCheckMode == X509RevocationMode.Online;
			}
			set
			{
				ThrowForModifiedManagedSslOptionsIfStarted();
				_delegatingHandler.SslOptions.CertificateRevocationCheckMode = (value ? X509RevocationMode.Online : X509RevocationMode.NoCheck);
			}
		}

		public SslProtocols SslProtocols
		{
			get
			{
				return _delegatingHandler.SslOptions.EnabledSslProtocols;
			}
			set
			{
				ThrowForModifiedManagedSslOptionsIfStarted();
				_delegatingHandler.SslOptions.EnabledSslProtocols = value;
			}
		}

		public DecompressionMethods AutomaticDecompression
		{
			get
			{
				return _delegatingHandler.AutomaticDecompression;
			}
			set
			{
				_delegatingHandler.AutomaticDecompression = value;
			}
		}

		public bool UseProxy
		{
			get
			{
				return _delegatingHandler.UseProxy;
			}
			set
			{
				_delegatingHandler.UseProxy = value;
			}
		}

		public IWebProxy Proxy
		{
			get
			{
				return _delegatingHandler.Proxy;
			}
			set
			{
				_delegatingHandler.Proxy = value;
			}
		}

		public ICredentials DefaultProxyCredentials
		{
			get
			{
				return _delegatingHandler.DefaultProxyCredentials;
			}
			set
			{
				_delegatingHandler.DefaultProxyCredentials = value;
			}
		}

		public bool PreAuthenticate
		{
			get
			{
				return _delegatingHandler.PreAuthenticate;
			}
			set
			{
				_delegatingHandler.PreAuthenticate = value;
			}
		}

		public bool UseDefaultCredentials
		{
			get
			{
				return _delegatingHandler.Credentials == CredentialCache.DefaultCredentials;
			}
			set
			{
				if (value)
				{
					_delegatingHandler.Credentials = CredentialCache.DefaultCredentials;
				}
				else if (_delegatingHandler.Credentials == CredentialCache.DefaultCredentials)
				{
					_delegatingHandler.Credentials = null;
				}
			}
		}

		public ICredentials Credentials
		{
			get
			{
				return _delegatingHandler.Credentials;
			}
			set
			{
				_delegatingHandler.Credentials = value;
			}
		}

		public bool AllowAutoRedirect
		{
			get
			{
				return _delegatingHandler.AllowAutoRedirect;
			}
			set
			{
				_delegatingHandler.AllowAutoRedirect = value;
			}
		}

		public int MaxAutomaticRedirections
		{
			get
			{
				return _delegatingHandler.MaxAutomaticRedirections;
			}
			set
			{
				_delegatingHandler.MaxAutomaticRedirections = value;
			}
		}

		public int MaxConnectionsPerServer
		{
			get
			{
				return _delegatingHandler.MaxConnectionsPerServer;
			}
			set
			{
				_delegatingHandler.MaxConnectionsPerServer = value;
			}
		}

		public int MaxResponseHeadersLength
		{
			get
			{
				return _delegatingHandler.MaxResponseHeadersLength;
			}
			set
			{
				_delegatingHandler.MaxResponseHeadersLength = value;
			}
		}

		public long MaxRequestContentBufferSize
		{
			get
			{
				return _delegatingHandler.MaxRequestContentBufferSize;
			}
			set
			{
				_delegatingHandler.MaxRequestContentBufferSize = value;
			}
		}

		public IDictionary<string, object> Properties => _delegatingHandler.Properties;

		private static IMonoHttpClientHandler CreateDefaultHandler()
		{
			return new MonoWebRequestHandler();
		}

		public HttpClientHandler()
			: this(CreateDefaultHandler())
		{
		}

		internal HttpClientHandler(IMonoHttpClientHandler handler)
		{
			_delegatingHandler = handler;
			ClientCertificateOptions = ClientCertificateOption.Manual;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				_delegatingHandler.Dispose();
			}
			base.Dispose(disposing);
		}

		private void ThrowForModifiedManagedSslOptionsIfStarted()
		{
			_delegatingHandler.SslOptions = _delegatingHandler.SslOptions;
		}

		internal void SetWebRequestTimeout(TimeSpan timeout)
		{
			_delegatingHandler.SetWebRequestTimeout(timeout);
		}

		protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			return _delegatingHandler.SendAsync(request, cancellationToken);
		}
	}
	internal interface IMonoHttpClientHandler : IDisposable
	{
		bool SupportsAutomaticDecompression { get; }

		bool UseCookies { get; set; }

		CookieContainer CookieContainer { get; set; }

		SslClientAuthenticationOptions SslOptions { get; set; }

		DecompressionMethods AutomaticDecompression { get; set; }

		bool UseProxy { get; set; }

		IWebProxy Proxy { get; set; }

		ICredentials DefaultProxyCredentials { get; set; }

		bool PreAuthenticate { get; set; }

		ICredentials Credentials { get; set; }

		bool AllowAutoRedirect { get; set; }

		int MaxAutomaticRedirections { get; set; }

		int MaxConnectionsPerServer { get; set; }

		int MaxResponseHeadersLength { get; set; }

		long MaxRequestContentBufferSize { get; set; }

		IDictionary<string, object> Properties { get; }

		Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);

		void SetWebRequestTimeout(TimeSpan timeout);
	}
	internal class MonoWebRequestHandler : IMonoHttpClientHandler, IDisposable
	{
		private static long groupCounter;

		private bool allowAutoRedirect;

		private DecompressionMethods automaticDecompression;

		private CookieContainer cookieContainer;

		private ICredentials credentials;

		private int maxAutomaticRedirections;

		private long maxRequestContentBufferSize;

		private bool preAuthenticate;

		private IWebProxy proxy;

		private bool useCookies;

		private bool useProxy;

		private SslClientAuthenticationOptions sslOptions;

		private bool allowPipelining;

		private RequestCachePolicy cachePolicy;

		private AuthenticationLevel authenticationLevel;

		private TimeSpan continueTimeout;

		private TokenImpersonationLevel impersonationLevel;

		private int maxResponseHeadersLength;

		private int readWriteTimeout;

		private RemoteCertificateValidationCallback serverCertificateValidationCallback;

		private bool unsafeAuthenticatedConnectionSharing;

		private bool sentRequest;

		private string connectionGroupName;

		private TimeSpan? timeout;

		private bool disposed;

		public bool AllowAutoRedirect
		{
			get
			{
				return allowAutoRedirect;
			}
			set
			{
				EnsureModifiability();
				allowAutoRedirect = value;
			}
		}

		public DecompressionMethods AutomaticDecompression
		{
			get
			{
				return automaticDecompression;
			}
			set
			{
				EnsureModifiability();
				automaticDecompression = value;
			}
		}

		public CookieContainer CookieContainer
		{
			get
			{
				return cookieContainer ?? (cookieContainer = new CookieContainer());
			}
			set
			{
				EnsureModifiability();
				cookieContainer = value;
			}
		}

		public ICredentials Credentials
		{
			get
			{
				return credentials;
			}
			set
			{
				EnsureModifiability();
				credentials = value;
			}
		}

		public int MaxAutomaticRedirections
		{
			get
			{
				return maxAutomaticRedirections;
			}
			set
			{
				EnsureModifiability();
				if (value <= 0)
				{
					throw new ArgumentOutOfRangeException();
				}
				maxAutomaticRedirections = value;
			}
		}

		public long MaxRequestContentBufferSize
		{
			get
			{
				return maxRequestContentBufferSize;
			}
			set
			{
				EnsureModifiability();
				if (value < 0)
				{
					throw new ArgumentOutOfRangeException();
				}
				maxRequestContentBufferSize = value;
			}
		}

		public bool PreAuthenticate
		{
			get
			{
				return preAuthenticate;
			}
			set
			{
				EnsureModifiability();
				preAuthenticate = value;
			}
		}

		public IWebProxy Proxy
		{
			get
			{
				return proxy;
			}
			set
			{
				EnsureModifiability();
				if (!UseProxy)
				{
					throw new InvalidOperationException();
				}
				proxy = value;
			}
		}

		public virtual bool SupportsAutomaticDecompression => true;

		public virtual bool SupportsProxy => true;

		public virtual bool SupportsRedirectConfiguration => true;

		public bool UseCookies
		{
			get
			{
				return useCookies;
			}
			set
			{
				EnsureModifiability();
				useCookies = value;
			}
		}

		public bool UseProxy
		{
			get
			{
				return useProxy;
			}
			set
			{
				EnsureModifiability();
				useProxy = value;
			}
		}

		public bool AllowPipelining
		{
			get
			{
				return allowPipelining;
			}
			set
			{
				EnsureModifiability();
				allowPipelining = value;
			}
		}

		public RequestCachePolicy CachePolicy
		{
			get
			{
				return cachePolicy;
			}
			set
			{
				EnsureModifiability();
				cachePolicy = value;
			}
		}

		public AuthenticationLevel AuthenticationLevel
		{
			get
			{
				return authenticationLevel;
			}
			set
			{
				EnsureModifiability();
				authenticationLevel = value;
			}
		}

		[MonoTODO]
		public TimeSpan ContinueTimeout
		{
			get
			{
				return continueTimeout;
			}
			set
			{
				EnsureModifiability();
				continueTimeout = value;
			}
		}

		public TokenImpersonationLevel ImpersonationLevel
		{
			get
			{
				return impersonationLevel;
			}
			set
			{
				EnsureModifiability();
				impersonationLevel = value;
			}
		}

		public int MaxResponseHeadersLength
		{
			get
			{
				return maxResponseHeadersLength;
			}
			set
			{
				EnsureModifiability();
				maxResponseHeadersLength = value;
			}
		}

		public int ReadWriteTimeout
		{
			get
			{
				return readWriteTimeout;
			}
			set
			{
				EnsureModifiability();
				readWriteTimeout = value;
			}
		}

		public RemoteCertificateValidationCallback ServerCertificateValidationCallback
		{
			get
			{
				return serverCertificateValidationCallback;
			}
			set
			{
				EnsureModifiability();
				serverCertificateValidationCallback = value;
			}
		}

		public bool UnsafeAuthenticatedConnectionSharing
		{
			get
			{
				return unsafeAuthenticatedConnectionSharing;
			}
			set
			{
				EnsureModifiability();
				unsafeAuthenticatedConnectionSharing = value;
			}
		}

		public SslClientAuthenticationOptions SslOptions
		{
			get
			{
				//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: Expected O, but got Unknown
				//IL_0017: Expected O, but got Unknown
				SslClientAuthenticationOptions obj = sslOptions;
				if (obj == null)
				{
					SslClientAuthenticationOptions val = new SslClientAuthenticationOptions();
					SslClientAuthenticationOptions val2 = val;
					sslOptions = val;
					obj = val2;
				}
				return obj;
			}
			set
			{
				EnsureModifiability();
				sslOptions = value;
			}
		}

		public ICredentials DefaultProxyCredentials
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		public int MaxConnectionsPerServer
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		public IDictionary<string, object> Properties
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		public MonoWebRequestHandler()
		{
			allowAutoRedirect = true;
			maxAutomaticRedirections = 50;
			maxRequestContentBufferSize = 2147483647L;
			useCookies = true;
			useProxy = true;
			allowPipelining = true;
			authenticationLevel = AuthenticationLevel.MutualAuthRequested;
			cachePolicy = WebRequest.DefaultCachePolicy;
			continueTimeout = TimeSpan.FromMilliseconds(350.0);
			impersonationLevel = TokenImpersonationLevel.Delegation;
			maxResponseHeadersLength = HttpWebRequest.DefaultMaximumResponseHeadersLength;
			readWriteTimeout = 300000;
			serverCertificateValidationCallback = null;
			unsafeAuthenticatedConnectionSharing = false;
			connectionGroupName = "HttpClientHandler" + Interlocked.Increment(ref groupCounter);
		}

		internal void EnsureModifiability()
		{
			if (sentRequest)
			{
				throw new InvalidOperationException("This instance has already started one or more requests. Properties can only be modified before sending the first request.");
			}
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && !disposed)
			{
				Volatile.Write(ref disposed, value: true);
				ServicePointManager.CloseConnectionGroup(connectionGroupName);
			}
		}

		private bool GetConnectionKeepAlive(HttpRequestHeaders headers)
		{
			return headers.Connection.Any((string l) => string.Equals(l, "Keep-Alive", StringComparison.OrdinalIgnoreCase));
		}

		internal virtual HttpWebRequest CreateWebRequest(HttpRequestMessage request)
		{
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Expected O, but got Unknown
			HttpWebRequest httpWebRequest;
			if (HttpUtilities.IsSupportedSecureScheme(request.RequestUri.Scheme))
			{
				httpWebRequest = new HttpWebRequest(request.RequestUri, MonoTlsProviderFactory.GetProviderInternal(), MonoTlsSettings.CopyDefaultSettings());
				httpWebRequest.TlsSettings.ClientCertificateSelectionCallback = (MonoLocalCertificateSelectionCallback)((string t, X509CertificateCollection lc, X509Certificate rc, string[] ai) => SslOptions.LocalCertificateSelectionCallback(this, t, lc, rc, ai));
			}
			else
			{
				httpWebRequest = new HttpWebRequest(request.RequestUri);
			}
			httpWebRequest.ThrowOnError = false;
			httpWebRequest.AllowWriteStreamBuffering = false;
			if (request.Version == HttpVersion.Version20)
			{
				httpWebRequest.ProtocolVersion = HttpVersion.Version11;
			}
			else
			{
				httpWebRequest.ProtocolVersion = request.Version;
			}
			httpWebRequest.ConnectionGroupName = connectionGroupName;
			httpWebRequest.Method = request.Method.Method;
			if (httpWebRequest.ProtocolVersion == HttpVersion.Version10)
			{
				httpWebRequest.KeepAlive = GetConnectionKeepAlive(request.Headers);
			}
			else
			{
				httpWebRequest.KeepAlive = request.Headers.ConnectionClose != true;
			}
			if (allowAutoRedirect)
			{
				httpWebRequest.AllowAutoRedirect = true;
				httpWebRequest.MaximumAutomaticRedirections = maxAutomaticRedirections;
			}
			else
			{
				httpWebRequest.AllowAutoRedirect = false;
			}
			httpWebRequest.AutomaticDecompression = automaticDecompression;
			httpWebRequest.PreAuthenticate = preAuthenticate;
			if (useCookies)
			{
				httpWebRequest.CookieContainer = CookieContainer;
			}
			httpWebRequest.Credentials = credentials;
			if (useProxy)
			{
				httpWebRequest.Proxy = proxy;
			}
			else
			{
				httpWebRequest.Proxy = null;
			}
			httpWebRequest.ServicePoint.Expect100Continue = request.Headers.ExpectContinue == true;
			if (timeout.HasValue)
			{
				httpWebRequest.Timeout = (int)timeout.Value.TotalMilliseconds;
			}
			httpWebRequest.ServerCertificateValidationCallback = SslOptions.RemoteCertificateValidationCallback;
			WebHeaderCollection headers = httpWebRequest.Headers;
			foreach (KeyValuePair<string, IEnumerable<string>> header in request.Headers)
			{
				IEnumerable<string> enumerable = header.Value;
				if (header.Key == "Host")
				{
					httpWebRequest.Host = request.Headers.Host;
					continue;
				}
				if (header.Key == "Transfer-Encoding")
				{
					enumerable = enumerable.Where((string l) => l != "chunked");
				}
				string singleHeaderString = PlatformHelper.GetSingleHeaderString(header.Key, enumerable);
				if (singleHeaderString != null)
				{
					headers.AddInternal(header.Key, singleHeaderString);
				}
			}
			return httpWebRequest;
		}

		private HttpResponseMessage CreateResponseMessage(HttpWebResponse wr, HttpRequestMessage requestMessage, CancellationToken cancellationToken)
		{
			HttpResponseMessage httpResponseMessage = new HttpResponseMessage(wr.StatusCode);
			httpResponseMessage.RequestMessage = requestMessage;
			httpResponseMessage.ReasonPhrase = wr.StatusDescription;
			httpResponseMessage.Content = PlatformHelper.CreateStreamContent(wr.GetResponseStream(), cancellationToken);
			WebHeaderCollection headers = wr.Headers;
			for (int i = 0; i < headers.Count; i++)
			{
				string key = headers.GetKey(i);
				string[] values = headers.GetValues(i);
				HttpHeaders httpHeaders = ((!PlatformHelper.IsContentHeader(key)) ? ((HttpHeaders)httpResponseMessage.Headers) : ((HttpHeaders)httpResponseMessage.Content.Headers));
				httpHeaders.TryAddWithoutValidation(key, values);
			}
			requestMessage.RequestUri = wr.ResponseUri;
			return httpResponseMessage;
		}

		private static bool MethodHasBody(HttpMethod method)
		{
			switch (method.Method)
			{
			case "HEAD":
			case "GET":
			case "MKCOL":
			case "CONNECT":
			case "TRACE":
				return false;
			default:
				return true;
			}
		}

		public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			if (disposed)
			{
				throw new ObjectDisposedException(GetType().ToString());
			}
			FieldInfo field = typeof(CancellationToken).GetField("_source", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
			CancellationTokenSource obj = (CancellationTokenSource)field.GetValue(cancellationToken);
			field = typeof(CancellationTokenSource).GetField("_timer", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
			Timer timer = (Timer)field.GetValue(obj);
			if (timer != null)
			{
				field = typeof(Timer).GetField("due_time_ms", BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				timeout = TimeSpan.FromMilliseconds((long)field.GetValue(timer));
			}
			Volatile.Write(ref sentRequest, value: true);
			HttpWebRequest wrequest = CreateWebRequest(request);
			HttpWebResponse wresponse = null;
			try
			{
				using (cancellationToken.Register(delegate(object l)
				{
					((HttpWebRequest)l).Abort();
				}, wrequest))
				{
					HttpContent content = request.Content;
					if (content != null)
					{
						WebHeaderCollection headers = wrequest.Headers;
						foreach (KeyValuePair<string, IEnumerable<string>> header in content.Headers)
						{
							foreach (string item in header.Value)
							{
								headers.AddInternal(header.Key, item);
							}
						}
						if (request.Headers.TransferEncodingChunked == true)
						{
							wrequest.SendChunked = true;
						}
						else
						{
							long? contentLength = content.Headers.ContentLength;
							if (contentLength.HasValue)
							{
								wrequest.ContentLength = contentLength.Value;
							}
							else
							{
								if (MaxRequestContentBufferSize == 0L)
								{
									throw new InvalidOperationException("The content length of the request content can't be determined. Either set TransferEncodingChunked to true, load content into buffer, or set MaxRequestContentBufferSize.");
								}
								await content.LoadIntoBufferAsync(MaxRequestContentBufferSize).ConfigureAwait(continueOnCapturedContext: false);
								wrequest.ContentLength = content.Headers.ContentLength.Value;
							}
						}
						wrequest.ResendContentFactory = content.CopyToAsync;
						using Stream stream = await wrequest.GetRequestStreamAsync().ConfigureAwait(continueOnCapturedContext: false);
						await request.Content.CopyToAsync(stream).ConfigureAwait(continueOnCapturedContext: false);
					}
					else if (MethodHasBody(request.Method))
					{
						wrequest.ContentLength = 0L;
					}
					wresponse = (HttpWebResponse)(await wrequest.GetResponseAsync().ConfigureAwait(continueOnCapturedContext: false));
				}
			}
			catch (WebException ex)
			{
				if (ex.Status != WebExceptionStatus.RequestCanceled)
				{
					throw new HttpRequestException("An error occurred while sending the request", ex);
				}
			}
			catch (IOException inner)
			{
				throw new HttpRequestException("An error occurred while sending the request", inner);
			}
			if (cancellationToken.IsCancellationRequested)
			{
				TaskCompletionSource<HttpResponseMessage> taskCompletionSource = new TaskCompletionSource<HttpResponseMessage>();
				taskCompletionSource.SetCanceled();
				return await taskCompletionSource.Task;
			}
			return CreateResponseMessage(wresponse, request, cancellationToken);
		}

		void IMonoHttpClientHandler.SetWebRequestTimeout(TimeSpan timeout)
		{
			this.timeout = timeout;
		}
	}
	internal static class PlatformHelper
	{
		internal static bool IsContentHeader(string name)
		{
			return HttpHeaders.GetKnownHeaderKind(name) == HttpHeaderKind.Content;
		}

		internal static string GetSingleHeaderString(string name, IEnumerable<string> values)
		{
			return HttpHeaders.GetSingleHeaderString(name, values);
		}

		internal static StreamContent CreateStreamContent(Stream stream, CancellationToken cancellationToken)
		{
			return new StreamContent(stream, cancellationToken);
		}
	}
	public class ByteArrayContent : HttpContent
	{
		private readonly byte[] content;

		private readonly int offset;

		private readonly int count;

		public ByteArrayContent(byte[] content)
		{
			if (content == null)
			{
				throw new ArgumentNullException("content");
			}
			this.content = content;
			count = content.Length;
		}

		public ByteArrayContent(byte[] content, int offset, int count)
			: this(content)
		{
			if (offset < 0 || offset > this.count)
			{
				throw new ArgumentOutOfRangeException("offset");
			}
			if (count < 0 || count > this.count - offset)
			{
				throw new ArgumentOutOfRangeException("count");
			}
			this.offset = offset;
			this.count = count;
		}

		protected override Task<Stream> CreateContentReadStreamAsync()
		{
			return Task.FromResult((Stream)new MemoryStream(content, offset, count));
		}

		protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
		{
			return stream.WriteAsync(content, offset, count);
		}

		protected internal override bool TryComputeLength(out long length)
		{
			length = count;
			return true;
		}
	}
	public enum ClientCertificateOption
	{
		Manual,
		Automatic
	}
	public abstract class DelegatingHandler : HttpMessageHandler
	{
		private bool disposed;

		private HttpMessageHandler handler;

		public HttpMessageHandler InnerHandler
		{
			get
			{
				return handler;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("InnerHandler");
				}
				handler = value;
			}
		}

		protected DelegatingHandler()
		{
		}

		protected DelegatingHandler(HttpMessageHandler innerHandler)
		{
			if (innerHandler == null)
			{
				throw new ArgumentNullException("innerHandler");
			}
			InnerHandler = innerHandler;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && !disposed)
			{
				disposed = true;
				if (InnerHandler != null)
				{
					InnerHandler.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			if (InnerHandler == null)
			{
				throw new InvalidOperationException("The inner handler has not been assigned.");
			}
			return InnerHandler.SendAsync(request, cancellationToken);
		}
	}
	public class FormUrlEncodedContent : ByteArrayContent
	{
		public FormUrlEncodedContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
			: base(EncodeContent(nameValueCollection))
		{
			base.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
		}

		private static byte[] EncodeContent(IEnumerable<KeyValuePair<string, string>> nameValueCollection)
		{
			if (nameValueCollection == null)
			{
				throw new ArgumentNullException("nameValueCollection");
			}
			List<byte> list = new List<byte>();
			foreach (KeyValuePair<string, string> item in nameValueCollection)
			{
				if (list.Count != 0)
				{
					list.Add(38);
				}
				byte[] array = SerializeValue(item.Key);
				if (array != null)
				{
					list.AddRange(array);
				}
				list.Add(61);
				array = SerializeValue(item.Value);
				if (array != null)
				{
					list.AddRange(array);
				}
			}
			return list.ToArray();
		}

		private static byte[] SerializeValue(string value)
		{
			if (value == null)
			{
				return null;
			}
			value = Uri.EscapeDataString(value).Replace("%20", "+");
			return Encoding.ASCII.GetBytes(value);
		}
	}
	public class HttpClient : HttpMessageInvoker
	{
		private static readonly TimeSpan TimeoutDefault = TimeSpan.FromSeconds(100.0);

		private Uri base_address;

		private CancellationTokenSource cts;

		private bool disposed;

		private HttpRequestHeaders headers;

		private long buffer_size;

		private TimeSpan timeout;

		public Uri BaseAddress
		{
			get
			{
				return base_address;
			}
			set
			{
				base_address = value;
			}
		}

		public HttpRequestHeaders DefaultRequestHeaders => headers ?? (headers = new HttpRequestHeaders());

		public long MaxResponseContentBufferSize
		{
			get
			{
				return buffer_size;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentOutOfRangeException();
				}
				buffer_size = value;
			}
		}

		public TimeSpan Timeout
		{
			get
			{
				return timeout;
			}
			set
			{
				if (value != System.Threading.Timeout.InfiniteTimeSpan && (value <= TimeSpan.Zero || value.TotalMilliseconds > 2147483647.0))
				{
					throw new ArgumentOutOfRangeException();
				}
				timeout = value;
			}
		}

		public HttpClient()
			: this(new HttpClientHandler(), disposeHandler: true)
		{
		}

		public HttpClient(HttpMessageHandler handler)
			: this(handler, disposeHandler: true)
		{
		}

		public HttpClient(HttpMessageHandler handler, bool disposeHandler)
			: base(handler, disposeHandler)
		{
			buffer_size = 2147483647L;
			timeout = TimeoutDefault;
			cts = new CancellationTokenSource();
		}

		public void CancelPendingRequests()
		{
			using CancellationTokenSource cancellationTokenSource = Interlocked.Exchange(ref cts, new CancellationTokenSource());
			cancellationTokenSource.Cancel();
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing && !disposed)
			{
				disposed = true;
				cts.Cancel();
				cts.Dispose();
			}
			base.Dispose(disposing);
		}

		public Task<HttpResponseMessage> DeleteAsync(string requestUri)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri));
		}

		public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
		}

		public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri));
		}

		public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
		}

		public Task<HttpResponseMessage> GetAsync(string requestUri)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri));
		}

		public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), cancellationToken);
		}

		public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption);
		}

		public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
		}

		public Task<HttpResponseMessage> GetAsync(Uri requestUri)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri));
		}

		public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), cancellationToken);
		}

		public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption);
		}

		public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
		}

		public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Post, requestUri)
			{
				Content = content
			});
		}

		public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Post, requestUri)
			{
				Content = content
			}, cancellationToken);
		}

		public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Post, requestUri)
			{
				Content = content
			});
		}

		public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Post, requestUri)
			{
				Content = content
			}, cancellationToken);
		}

		public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Put, requestUri)
			{
				Content = content
			});
		}

		public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Put, requestUri)
			{
				Content = content
			}, cancellationToken);
		}

		public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Put, requestUri)
			{
				Content = content
			});
		}

		public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content, CancellationToken cancellationToken)
		{
			return SendAsync(new HttpRequestMessage(HttpMethod.Put, requestUri)
			{
				Content = content
			}, cancellationToken);
		}

		public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
		{
			return SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None);
		}

		public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
		{
			return SendAsync(request, completionOption, CancellationToken.None);
		}

		public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			return SendAsync(request, HttpCompletionOption.ResponseContentRead, cancellationToken);
		}

		public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
		{
			if (request == null)
			{
				throw new ArgumentNullException("request");
			}
			if (request.SetIsUsed())
			{
				throw new InvalidOperationException("Cannot send the same request message multiple times");
			}
			Uri requestUri = request.RequestUri;
			if (requestUri == null)
			{
				if (base_address == null)
				{
					throw new InvalidOperationException("The request URI must either be an absolute URI or BaseAddress must be set");
				}
				request.RequestUri = base_address;
			}
			else if (!requestUri.IsAbsoluteUri || (requestUri.Scheme == Uri.UriSchemeFile && requestUri.OriginalString.StartsWith("/", StringComparison.Ordinal)))
			{
				if (base_address == null)
				{
					throw new InvalidOperationException("The request URI must either be an absolute URI or BaseAddress must be set");
				}
				request.RequestUri = new Uri(base_address, requestUri);
			}
			if (headers != null)
			{
				request.Headers.AddHeaders(headers);
			}
			return SendAsyncWorker(request, completionOption, cancellationToken);
		}

		private async Task<HttpResponseMessage> SendAsyncWorker(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
		{
			using CancellationTokenSource lcts = CancellationTokenSource.CreateLinkedTokenSource(cts.Token, cancellationToken);
			if (handler is HttpClientHandler httpClientHandler)
			{
				httpClientHandler.SetWebRequestTimeout(timeout);
			}
			lcts.CancelAfter(timeout);
			HttpResponseMessage response = await (base.SendAsync(request, lcts.Token) ?? throw new InvalidOperationException("Handler failed to return a value")).ConfigureAwait(continueOnCapturedContext: false);
			if (response == null)
			{
				throw new InvalidOperationException("Handler failed to return a response");
			}
			if (response.Content != null && (completionOption & HttpCompletionOption.ResponseHeadersRead) == 0)
			{
				await response.Content.LoadIntoBufferAsync(MaxResponseContentBufferSize).ConfigureAwait(continueOnCapturedContext: false);
			}
			return response;
		}

		public async Task<byte[]> GetByteArrayAsync(string requestUri)
		{
			using HttpResponseMessage resp = await GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ConfigureAwait(continueOnCapturedContext: false);
			resp.EnsureSuccessStatusCode();
			return await resp.Content.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false);
		}

		public async Task<byte[]> GetByteArrayAsync(Uri requestUri)
		{
			using HttpResponseMessage resp = await GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ConfigureAwait(continueOnCapturedContext: false);
			resp.EnsureSuccessStatusCode();
			return await resp.Content.ReadAsByteArrayAsync().ConfigureAwait(continueOnCapturedContext: false);
		}

		public async Task<Stream> GetStreamAsync(string requestUri)
		{
			HttpResponseMessage obj = await GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(continueOnCapturedContext: false);
			obj.EnsureSuccessStatusCode();
			return await obj.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false);
		}

		public async Task<Stream> GetStreamAsync(Uri requestUri)
		{
			HttpResponseMessage obj = await GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(continueOnCapturedContext: false);
			obj.EnsureSuccessStatusCode();
			return await obj.Content.ReadAsStreamAsync().ConfigureAwait(continueOnCapturedContext: false);
		}

		public async Task<string> GetStringAsync(string requestUri)
		{
			using HttpResponseMessage resp = await GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ConfigureAwait(continueOnCapturedContext: false);
			resp.EnsureSuccessStatusCode();
			return await resp.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
		}

		public async Task<string> GetStringAsync(Uri requestUri)
		{
			using HttpResponseMessage resp = await GetAsync(requestUri, HttpCompletionOption.ResponseContentRead).ConfigureAwait(continueOnCapturedContext: false);
			resp.EnsureSuccessStatusCode();
			return await resp.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false);
		}

		public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content)
		{
			throw new PlatformNotSupportedException();
		}

		public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content, CancellationToken cancellationToken)
		{
			throw new PlatformNotSupportedException();
		}

		public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content)
		{
			throw new PlatformNotSupportedException();
		}

		public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content, CancellationToken cancellationToken)
		{
			throw new PlatformNotSupportedException();
		}
	}
	public enum HttpCompletionOption
	{
		ResponseContentRead,
		ResponseHeadersRead
	}
	public abstract class HttpContent : IDisposable
	{
		private sealed class FixedMemoryStream : MemoryStream
		{
			private readonly long maxSize;

			public FixedMemoryStream(long maxSize)
			{
				this.maxSize = maxSize;
			}

			private void CheckOverflow(int count)
			{
				if (Length + count > maxSize)
				{
					throw new HttpRequestException($"Cannot write more bytes to the buffer than the configured maximum buffer size: {maxSize}");
				}
			}

			public override void WriteByte(byte value)
			{
				CheckOverflow(1);
				base.WriteByte(value);
			}

			public override void Write(byte[] buffer, int offset, int count)
			{
				CheckOverflow(count);
				base.Write(buffer, offset, count);
			}
		}

		private FixedMemoryStream buffer;

		private Stream stream;

		private bool disposed;

		private HttpContentHeaders headers;

		public HttpContentHeaders Headers => headers ?? (headers = new HttpContentHeaders(this));

		internal long? LoadedBufferLength
		{
			get
			{
				if (buffer != null)
				{
					return buffer.Length;
				}
				return null;
			}
		}

		internal void CopyTo(Stream stream)
		{
			CopyToAsync(stream).Wait();
		}

		public Task CopyToAsync(Stream stream)
		{
			return CopyToAsync(stream, null);
		}

		public Task CopyToAsync(Stream stream, TransportContext context)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			if (buffer != null)
			{
				return buffer.CopyToAsync(stream);
			}
			return SerializeToStreamAsync(stream, context);
		}

		protected virtual async Task<Stream> CreateContentReadStreamAsync()
		{
			await LoadIntoBufferAsync().ConfigureAwait(continueOnCapturedContext: false);
			return buffer;
		}

		private static FixedMemoryStream CreateFixedMemoryStream(long maxBufferSize)
		{
			return new FixedMemoryStream(maxBufferSize);
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && !disposed)
			{
				disposed = true;
				if (buffer != null)
				{
					buffer.Dispose();
				}
			}
		}

		public Task LoadIntoBufferAsync()
		{
			return LoadIntoBufferAsync(2147483647L);
		}

		public async Task LoadIntoBufferAsync(long maxBufferSize)
		{
			if (disposed)
			{
				throw new ObjectDisposedException(GetType().ToString());
			}
			if (buffer == null)
			{
				buffer = CreateFixedMemoryStream(maxBufferSize);
				await SerializeToStreamAsync(buffer, null).ConfigureAwait(continueOnCapturedContext: false);
				buffer.Seek(0L, SeekOrigin.Begin);
			}
		}

		public async Task<Stream> ReadAsStreamAsync()
		{
			if (disposed)
			{
				throw new ObjectDisposedException(GetType().ToString());
			}
			if (buffer != null)
			{
				return new MemoryStream(buffer.GetBuffer(), 0, (int)buffer.Length, writable: false);
			}
			if (stream == null)
			{
				stream = await CreateContentReadStreamAsync().ConfigureAwait(continueOnCapturedContext: false);
			}
			return stream;
		}

		public async Task<byte[]> ReadAsByteArrayAsync()
		{
			await LoadIntoBufferAsync().ConfigureAwait(continueOnCapturedContext: false);
			return buffer.ToArray();
		}

		public async Task<string> ReadAsStringAsync()
		{
			await LoadIntoBufferAsync().ConfigureAwait(continueOnCapturedContext: false);
			if (buffer.Length == 0L)
			{
				return string.Empty;
			}
			byte[] array = buffer.GetBuffer();
			int num = (int)buffer.Length;
			int preambleLength = 0;
			Encoding encoding;
			if (headers != null && headers.ContentType != null && headers.ContentType.CharSet != null)
			{
				encoding = Encoding.GetEncoding(headers.ContentType.CharSet);
				preambleLength = StartsWith(array, num, encoding.GetPreamble());
			}
			else
			{
				encoding = GetEncodingFromBuffer(array, num, ref preambleLength) ?? Encoding.UTF8;
			}
			return encoding.GetString(array, preambleLength, num - preambleLength);
		}

		private static Encoding GetEncodingFromBuffer(byte[] buffer, int length, ref int preambleLength)
		{
			Encoding[] array = new Encoding[3]
			{
				Encoding.UTF8,
				Encoding.UTF32,
				Encoding.Unicode
			};
			foreach (Encoding encoding in array)
			{
				if ((preambleLength = StartsWith(buffer, length, encoding.GetPreamble())) != 0)
				{
					return encoding;
				}
			}
			return null;
		}

		private static int StartsWith(byte[] array, int length, byte[] value)
		{
			if (length < value.Length)
			{
				return 0;
			}
			for (int i = 0; i < value.Length; i++)
			{
				if (array[i] != value[i])
				{
					return 0;
				}
			}
			return value.Length;
		}

		internal Task SerializeToStreamAsync_internal(Stream stream, TransportContext context)
		{
			return SerializeToStreamAsync(stream, context);
		}

		protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context);

		protected internal abstract bool TryComputeLength(out long length);
	}
	public abstract class HttpMessageHandler : IDisposable
	{
		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
		}

		protected internal abstract Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
	}
	public class HttpMessageInvoker : IDisposable
	{
		private protected HttpMessageHandler handler;

		private readonly bool disposeHandler;

		public HttpMessageInvoker(HttpMessageHandler handler)
			: this(handler, disposeHandler: true)
		{
		}

		public HttpMessageInvoker(HttpMessageHandler handler, bool disposeHandler)
		{
			if (handler == null)
			{
				throw new ArgumentNullException("handler");
			}
			this.handler = handler;
			this.disposeHandler = disposeHandler;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && disposeHandler && handler != null)
			{
				handler.Dispose();
				handler = null;
			}
		}

		public virtual Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			return handler.SendAsync(request, cancellationToken);
		}
	}
	public class HttpMethod : IEquatable<HttpMethod>
	{
		private static readonly HttpMethod delete_method = new HttpMethod("DELETE");

		private static readonly HttpMethod get_method = new HttpMethod("GET");

		private static readonly HttpMethod head_method = new HttpMethod("HEAD");

		private static readonly HttpMethod options_method = new HttpMethod("OPTIONS");

		private static readonly HttpMethod post_method = new HttpMethod("POST");

		private static readonly HttpMethod put_method = new HttpMethod("PUT");

		private static readonly HttpMethod trace_method = new HttpMethod("TRACE");

		private readonly string method;

		public static HttpMethod Delete => delete_method;

		public static HttpMethod Get => get_method;

		public static HttpMethod Head => head_method;

		public string Method => method;

		public static HttpMethod Options => options_method;

		public static HttpMethod Post => post_method;

		public static HttpMethod Put => put_method;

		public static HttpMethod Trace => trace_method;

		public static HttpMethod Patch
		{
			get
			{
				throw new PlatformNotSupportedException();
			}
		}

		public HttpMethod(string method)
		{
			if (string.IsNullOrEmpty(method))
			{
				throw new ArgumentException("method");
			}
			Parser.Token.Check(method);
			this.method = method;
		}

		public static bool operator ==(HttpMethod left, HttpMethod right)
		{
			if ((object)left == null || (object)right == null)
			{
				return (object)left == right;
			}
			return left.Equals(right);
		}

		public static bool operator !=(HttpMethod left, HttpMethod right)
		{
			return !(left == right);
		}

		public bool Equals(HttpMethod other)
		{
			return string.Equals(method, other.method, StringComparison.OrdinalIgnoreCase);
		}

		public override bool Equals(object obj)
		{
			if (obj is HttpMethod other)
			{
				return Equals(other);
			}
			return false;
		}

		public override int GetHashCode()
		{
			return method.GetHashCode();
		}

		public override string ToString()
		{
			return method;
		}
	}
	[Serializable]
	public class HttpRequestException : Exception
	{
		public HttpRequestException()
		{
		}

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

		public HttpRequestException(string message, Exception inner)
			: base(message, inner)
		{
		}
	}
	public class HttpRequestMessage : IDisposable
	{
		private HttpRequestHeaders headers;

		private HttpMethod method;

		private Version version;

		private Dictionary<string, object> properties;

		private Uri uri;

		private bool is_used;

		private bool disposed;

		public HttpContent Content { get; set; }

		public HttpRequestHeaders Headers => headers ?? (headers = new HttpRequestHeaders());

		public HttpMethod Method
		{
			get
			{
				return method;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("method");
				}
				method = value;
			}
		}

		public IDictionary<string, object> Properties => properties ?? (properties = new Dictionary<string, object>());

		public Uri RequestUri
		{
			get
			{
				return uri;
			}
			set
			{
				if (value != null && value.IsAbsoluteUri && !IsAllowedAbsoluteUri(value))
				{
					throw new ArgumentException("Only http or https scheme is allowed");
				}
				uri = value;
			}
		}

		public Version Version
		{
			get
			{
				return version ?? HttpVersion.Version11;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("Version");
				}
				version = value;
			}
		}

		public HttpRequestMessage()
		{
			method = HttpMethod.Get;
		}

		public HttpRequestMessage(HttpMethod method, string requestUri)
			: this(method, string.IsNullOrEmpty(requestUri) ? null : new Uri(requestUri, UriKind.RelativeOrAbsolute))
		{
		}

		public HttpRequestMessage(HttpMethod method, Uri requestUri)
		{
			Method = method;
			RequestUri = requestUri;
		}

		private static bool IsAllowedAbsoluteUri(Uri uri)
		{
			if (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps)
			{
				return true;
			}
			if (uri.Scheme == Uri.UriSchemeFile && uri.OriginalString.StartsWith("/", StringComparison.Ordinal))
			{
				return true;
			}
			return false;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && !disposed)
			{
				disposed = true;
				if (Content != null)
				{
					Content.Dispose();
				}
			}
		}

		internal bool SetIsUsed()
		{
			if (is_used)
			{
				return true;
			}
			is_used = true;
			return false;
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("Method: ").Append(method);
			stringBuilder.Append(", RequestUri: '").Append((RequestUri != null) ? RequestUri.ToString() : "<null>");
			stringBuilder.Append("', Version: ").Append(Version);
			stringBuilder.Append(", Content: ").Append((Content != null) ? Content.ToString() : "<null>");
			stringBuilder.Append(", Headers:\r\n{\r\n").Append(Headers);
			if (Content != null)
			{
				stringBuilder.Append(Content.Headers);
			}
			stringBuilder.Append("}");
			return stringBuilder.ToString();
		}
	}
	public class HttpResponseMessage : IDisposable
	{
		private HttpResponseHeaders headers;

		private HttpResponseHeaders trailingHeaders;

		private string reasonPhrase;

		private HttpStatusCode statusCode;

		private Version version;

		private bool disposed;

		public HttpContent Content { get; set; }

		public HttpResponseHeaders Headers => headers ?? (headers = new HttpResponseHeaders());

		public bool IsSuccessStatusCode
		{
			get
			{
				if (statusCode >= HttpStatusCode.OK)
				{
					return statusCode < HttpStatusCode.MultipleChoices;
				}
				return false;
			}
		}

		public string ReasonPhrase
		{
			get
			{
				return reasonPhrase ?? HttpStatusDescription.Get(statusCode);
			}
			set
			{
				reasonPhrase = value;
			}
		}

		public HttpRequestMessage RequestMessage { get; set; }

		public HttpStatusCode StatusCode
		{
			get
			{
				return statusCode;
			}
			set
			{
				if (value < (HttpStatusCode)0)
				{
					throw new ArgumentOutOfRangeException();
				}
				statusCode = value;
			}
		}

		public Version Version
		{
			get
			{
				return version ?? HttpVersion.Version11;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("Version");
				}
				version = value;
			}
		}

		public HttpResponseHeaders TrailingHeaders
		{
			get
			{
				if (trailingHeaders == null)
				{
					trailingHeaders = new HttpResponseHeaders();
				}
				return trailingHeaders;
			}
		}

		public HttpResponseMessage()
			: this(HttpStatusCode.OK)
		{
		}

		public HttpResponseMessage(HttpStatusCode statusCode)
		{
			StatusCode = statusCode;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing && !disposed)
			{
				disposed = true;
				if (Content != null)
				{
					Content.Dispose();
				}
			}
		}

		public HttpResponseMessage EnsureSuccessStatusCode()
		{
			if (IsSuccessStatusCode)
			{
				return this;
			}
			throw new HttpRequestException($"{(int)statusCode} ({ReasonPhrase})");
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("StatusCode: ").Append((int)StatusCode);
			stringBuilder.Append(", ReasonPhrase: '").Append(ReasonPhrase ?? "<null>");
			stringBuilder.Append("', Version: ").Append(Version);
			stringBuilder.Append(", Content: ").Append((Content != null) ? Content.ToString() : "<null>");
			stringBuilder.Append(", Headers:\r\n{\r\n").Append(Headers);
			if (Content != null)
			{
				stringBuilder.Append(Content.Headers);
			}
			stringBuilder.Append("}");
			return stringBuilder.ToString();
		}
	}
	public abstract class MessageProcessingHandler : DelegatingHandler
	{
		protected MessageProcessingHandler()
		{
		}

		protected MessageProcessingHandler(HttpMessageHandler innerHandler)
			: base(innerHandler)
		{
		}

		protected abstract HttpRequestMessage ProcessRequest(HttpRequestMessage request, CancellationToken cancellationToken);

		protected abstract HttpResponseMessage ProcessResponse(HttpResponseMessage response, CancellationToken cancellationToken);

		protected internal sealed override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
		{
			request = ProcessRequest(request, cancellationToken);
			return ProcessResponse(await base.SendAsync(request, cancellationToken).ConfigureAwait(continueOnCapturedContext: false), cancellationToken);
		}
	}
	public class MultipartContent : HttpContent, IEnumerable<HttpContent>, IEnumerable
	{
		private List<HttpContent> nested_content;

		private readonly string boundary;

		public MultipartContent()
			: this("mixed")
		{
		}

		public MultipartContent(string subtype)
			: this(subtype, Guid.NewGuid().ToString("D", CultureInfo.InvariantCulture))
		{
		}

		public MultipartContent(string subtype, string boundary)
		{
			if (string.IsNullOrWhiteSpace(subtype))
			{
				throw new ArgumentException("boundary");
			}
			if (string.IsNullOrWhiteSpace(boundary))
			{
				throw new ArgumentException("boundary");
			}
			if (boundary.Length > 70)
			{
				throw new ArgumentOutOfRangeException("boundary");
			}
			if (boundary.Last() == ' ' || !IsValidRFC2049(boundary))
			{
				throw new ArgumentException("boundary");
			}
			this.boundary = boundary;
			nested_content = new List<HttpContent>(2);
			base.Headers.ContentType = new MediaTypeHeaderValue("multipart/" + subtype)
			{
				Parameters = 
				{
					new NameValueHeaderValue("boundary", "\"" + boundary + "\"")
				}
			};
		}

		private static bool IsValidRFC2049(string s)
		{
			foreach (char c in s)
			{
				if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9'))
				{
					switch (c)
					{
					case '\'':
					case '(':
					case ')':
					case '+':
					case ',':
					case '-':
					case '.':
					case '/':
					case ':':
					case '=':
					case '?':
						continue;
					}
					return false;
				}
			}
			return true;
		}

		public virtual void Add(HttpContent content)
		{
			if (content == null)
			{
				throw new ArgumentNullException("content");
			}
			if (nested_content == null)
			{
				nested_content = new List<HttpContent>();
			}
			nested_content.Add(content);
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				foreach (HttpContent item in nested_content)
				{
					item.Dispose();
				}
				nested_content = null;
			}
			base.Dispose(disposing);
		}

		protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append('-').Append('-');
			sb.Append(boundary);
			sb.Append('\r').Append('\n');
			byte[] bytes;
			for (int i = 0; i < nested_content.Count; i++)
			{
				HttpContent c = nested_content[i];
				foreach (KeyValuePair<string, IEnumerable<string>> header in c.Headers)
				{
					sb.Append(header.Key);
					sb.Append(':').Append(' ');
					foreach (string item in header.Value)
					{
						sb.Append(item);
					}
					sb.Append('\r').Append('\n');
				}
				sb.Append('\r').Append('\n');
				bytes = Encoding.ASCII.GetBytes(sb.ToString());
				sb.Clear();
				await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(continueOnCapturedContext: false);
				await c.SerializeToStreamAsync_internal(stream, context).ConfigureAwait(continueOnCapturedContext: false);
				if (i != nested_content.Count - 1)
				{
					sb.Append('\r').Append('\n');
					sb.Append('-').Append('-');
					sb.Append(boundary);
					sb.Append('\r').Append('\n');
				}
			}
			sb.Append('\r').Append('\n');
			sb.Append('-').Append('-');
			sb.Append(boundary);
			sb.Append('-').Append('-');
			sb.Append('\r').Append('\n');
			bytes = Encoding.ASCII.GetBytes(sb.ToString());
			await stream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(continueOnCapturedContext: false);
		}

		protected internal override bool TryComputeLength(out long length)
		{
			length = 12 + 2 * boundary.Length;
			for (int i = 0; i < nested_content.Count; i++)
			{
				HttpContent httpContent = nested_content[i];
				foreach (KeyValuePair<string, IEnumerable<string>> header in httpContent.Headers)
				{
					length += header.Key.Length;
					length += 4L;
					foreach (string item in header.Value)
					{
						length += item.Length;
					}
				}
				if (!httpContent.TryComputeLength(out var length2))
				{
					return false;
				}
				length += 2L;
				length += length2;
				if (i != nested_content.Count - 1)
				{
					length += 6L;
					length += boundary.Length;
				}
			}
			return true;
		}

		public IEnumerator<HttpContent> GetEnumerator()
		{
			return nested_content.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return nested_content.GetEnumerator();
		}
	}
	public class MultipartFormDataContent : MultipartContent
	{
		public MultipartFormDataContent()
			: base("form-data")
		{
		}

		public MultipartFormDataContent(string boundary)
			: base("form-data", boundary)
		{
		}

		public override void Add(HttpContent content)
		{
			base.Add(content);
			AddContentDisposition(content, null, null);
		}

		public void Add(HttpContent content, string name)
		{
			base.Add(content);
			if (string.IsNullOrWhiteSpace(name))
			{
				throw new ArgumentException("name");
			}
			AddContentDisposition(content, name, null);
		}

		public void Add(HttpContent content, string name, string fileName)
		{
			base.Add(content);
			if (string.IsNullOrWhiteSpace(name))
			{
				throw new ArgumentException("name");
			}
			if (string.IsNullOrWhiteSpace(fileName))
			{
				throw new ArgumentException("fileName");
			}
			AddContentDisposition(content, name, fileName);
		}

		private void AddContentDisposition(HttpContent content, string name, string fileName)
		{
			HttpContentHeaders httpContentHeaders = content.Headers;
			if (httpContentHeaders.ContentDisposition == null)
			{
				httpContentHeaders.ContentDisposition = new ContentDispositionHeaderValue("form-data")
				{
					Name = name,
					FileName = fileName,
					FileNameStar = fileName
				};
			}
		}
	}
	public class StreamContent : HttpContent
	{
		private readonly Stream content;

		private readonly int bufferSize;

		private readonly CancellationToken cancellationToken;

		private readonly long startPosition;

		private bool contentCopied;

		public StreamContent(Stream content)
			: this(content, 16384)
		{
		}

		public StreamContent(Stream content, int bufferSize)
		{
			if (content == null)
			{
				throw new ArgumentNullException("content");
			}
			if (bufferSize <= 0)
			{
				throw new ArgumentOutOfRangeException("bufferSize");
			}
			this.content = content;
			this.bufferSize = bufferSize;
			if (content.CanSeek)
			{
				startPosition = content.Position;
			}
		}

		internal StreamContent(Stream content, CancellationToken cancellationToken)
			: this(content)
		{
			this.cancellationToken = cancellationToken;
		}

		protected override Task<Stream> CreateContentReadStreamAsync()
		{
			return Task.FromResult(content);
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				content.Dispose();
			}
			base.Dispose(disposing);
		}

		protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
		{
			if (contentCopied)
			{
				if (!content.CanSeek)
				{
					throw new InvalidOperationException("The stream was already consumed. It cannot be read again.");
				}
				content.Seek(startPosition, SeekOrigin.Begin);
			}
			else
			{
				contentCopied = true;
			}
			return content.CopyToAsync(stream, bufferSize, cancellationToken);
		}

		protected internal override bool TryComputeLength(out long length)
		{
			if (!content.CanSeek)
			{
				length = 0L;
				return false;
			}
			length = content.Length - startPosition;
			return true;
		}
	}
	public class StringContent : ByteArrayContent
	{
		public StringContent(string content)
			: this(content, null, null)
		{
		}

		public StringContent(string content, Encoding encoding)
			: this(content, encoding, null)
		{
		}

		public StringContent(string content, Encoding encoding, string mediaType)
			: base(GetByteArray(content, encoding))
		{
			base.Headers.ContentType = new MediaTypeHeaderValue(mediaType ?? "text/plain")
			{
				CharSet = (encoding ?? Encoding.UTF8).WebName
			};
		}

		private static byte[] GetByteArray(string content, Encoding encoding)
		{
			return (encoding ?? Encoding.UTF8).GetBytes(content);
		}
	}
	public sealed class ReadOnlyMemoryContent : HttpContent
	{
		public ReadOnlyMemoryContent(ReadOnlyMemory<byte> content)
		{
			throw new PlatformNotSupportedException();
		}

		protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
		{
			throw new PlatformNotSupportedException();
		}

		protected internal override bool TryComputeLength(out long length)
		{
			throw new PlatformNotSupportedException();
		}
	}
}
namespace System.Net.Http.Headers
{
	public class AuthenticationHeaderValue : ICloneable
	{
		public string Parameter { get; private set; }

		public string Scheme { get; private set; }

		public AuthenticationHeaderValue(string scheme)
			: this(scheme, null)
		{
		}

		public AuthenticationHeaderValue(string scheme, string parameter)
		{
			Parser.Token.Check(scheme);
			Scheme = scheme;
			Parameter = parameter;
		}

		private AuthenticationHeaderValue()
		{
		}

		object ICloneable.Clone()
		{
			return MemberwiseClone();
		}

		public override bool Equals(object obj)
		{
			if (obj is AuthenticationHeaderValue authenticationHeaderValue && string.Equals(authenticationHeaderValue.Scheme, Scheme, StringComparison.OrdinalIgnoreCase))
			{
				return authenticationHeaderValue.Parameter == Parameter;
			}
			return false;
		}

		public override int GetHashCode()
		{
			int num = Scheme.ToLowerInvariant().GetHashCode();
			if (!string.IsNullOrEmpty(Parameter))
			{
				num ^= Parameter.ToLowerInvariant().GetHashCode();
			}
			return num;
		}

		public static AuthenticationHeaderValue Parse(string input)
		{
			if (TryParse(input, out var parsedValue))
			{
				return parsedValue;
			}
			throw new FormatException(input);
		}

		public static bool TryParse(string input, out AuthenticationHeaderValue parsedValue)
		{
			if (TryParseElement(new Lexer(input), out parsedValue, out var t) && (Token.Type)t == Token.Type.End)
			{
				return true;
			}
			parsedValue = null;
			return false;
		}

		internal static bool TryParse(string input, int minimalCount, out List<AuthenticationHeaderValue> result)
		{
			return CollectionParser.TryParse(input, minimalCount, (ElementTryParser<AuthenticationHeaderValue>)TryParseElement, out result);
		}

		private static bool TryParseElement(Lexer lexer, out AuthenticationHeaderValue parsedValue, out Token t)
		{
			t = lexer.Scan();
			if ((Token.Type)t != Token.Type.Token)
			{
				parsedValue = null;
				return false;
			}
			parsedValue = new AuthenticationHeaderValue();
			parsedValue.Scheme = lexer.GetStringValue(t);
			t = lexer.Scan();
			if ((Token.Type)t == Token.Type.Token)
			{
				parsedValue.Parameter = lexer.GetRemainingStringValue(t.StartPosition);
				t = new Token(Token.Type.End, 0, 0);
			}
			return true;
		}

		public override string ToString()
		{
			if (Parameter == null)
			{
				return Scheme;
			}
			return Scheme + " " + Parameter;
		}
	}
	public class CacheControlHeaderValue : ICloneable
	{
		private List<NameValueHeaderValue> extensions;

		private List<string> no_cache_headers;

		private List<string> private_headers;

		public ICollection<NameValueHeaderValue> Extensions => extensions ?? (extensions = new List<NameValueHeaderValue>());

		public TimeSpan? MaxAge { get; set; }

		public bool MaxStale { get; set; }

		public TimeSpan? MaxStaleLimit { get; set; }

		public TimeSpan? MinFresh { get; set; }

		public bool MustRevalidate { get; set; }

		public bool NoCache { get; set; }

		public ICollection<string> NoCacheHeaders => no_cache_headers ?? (no_cache_headers = new List<string>());

		public bool NoStore { get; set; }

		public bool NoTransform { get; set; }

		public bool OnlyIfCached { get; set; }

		public bool Private { get; set; }

		public ICollection<string> PrivateHeaders => private_headers ?? (private_headers = new List<string>());

		public bool ProxyRevalidate { get; set; }

		public bool Public { get; set; }

		public TimeSpan? SharedMaxAge { get; set; }

		object ICloneable.Clone()
		{
			CacheControlHeaderValue cacheControlHeaderValue = (CacheControlHeaderValue)MemberwiseClone();
			if (extensions != null)
			{
				cacheControlHeaderValue.extensions = new List<NameValueHeaderValue>();
				foreach (NameValueHeaderValue extension in extensions)
				{
					cacheControlHeaderValue.extensions.Add(extension);
				}
			}
			if (no_cache_headers != null)
			{
				cacheControlHeaderValue.no_cache_headers = new List<string>();
				foreach (string no_cache_header in no_cache_headers)
				{
					cacheControlHeaderValue.no_cache_headers.Add(no_cache_header);
				}
			}
			if (private_headers != null)
			{
				cacheControlHeaderValue.private_headers = new List<string>();
				foreach (string private_header in private_headers)
				{
					cacheControlHeaderValue.private_headers.Add(private_header);
				}
			}
			return cacheControlHeaderValue;
		}

		public override bool Equals(object obj)
		{
			if (!(obj is CacheControlHeaderValue cacheControlHeaderValue))
			{
				return false;
			}
			TimeSpan? maxAge = MaxAge;
			TimeSpan? maxAge2 = cacheControlHeaderValue.MaxAge;
			if (maxAge.HasValue == maxAge2.HasValue && (!maxAge.HasValue || !(maxAge.GetValueOrDefault() != maxAge2.GetValueOrDefault())) && MaxStale == cacheControlHeaderValue.MaxStale && !(MaxStaleLimit != cacheControlHeaderValue.MaxStaleLimit))
			{
				maxAge = MinFresh;
				maxAge2 = cacheControlHeaderValue.MinFresh;
				if (maxAge.HasValue == maxAge2.HasValue && (!maxAge.HasValue || !(maxAge.GetValueOrDefault() != maxAge2.GetValueOrDefault())) && MustRevalidate == cacheControlHeaderValue.MustRevalidate && NoCache == cacheControlHeaderValue.NoCache && NoStore == cacheControlHeaderValue.NoStore && NoTransform == cacheControlHeaderValue.NoTransform && OnlyIfCached == cacheControlHeaderValue.OnlyIfCached && Private == cacheControlHeaderValue.Private && ProxyRevalidate == cacheControlHeaderValue.ProxyRevalidate && Public == cacheControlHeaderValue.Public && !(SharedMaxAge != cacheControlHeaderValue.SharedMaxAge))
				{
					if (extensions.SequenceEqual(cacheControlHeaderValue.extensions) && no_cache_headers.SequenceEqual(cacheControlHeaderValue.no_cache_headers))
					{
						return private_headers.SequenceEqual(cacheControlHeaderValue.private_headers);
					}
					return false;
				}
			}
			return false;
		}

		public override int GetHashCode()
		{
			return (((((((((((((((29 * 29 + HashCodeCalculator.Calculate(extensions)) * 29 + MaxAge.GetHashCode()) * 29 + MaxStale.GetHashCode()) * 29 + MaxStaleLimit.GetHashCode()) * 29 + MinFresh.GetHashCode()) * 29 + MustRevalidate.GetHashCode()) * 29 + HashCodeCalculator.Calculate(no_cache_headers)) * 29 + NoCache.GetHashCode()) * 29 + NoStore.GetHashCode()) * 29 + NoTransform.GetHashCode()) * 29 + OnlyIfCached.GetHashCode()) * 29 + Private.GetHashCode()) * 29 + HashCodeCalculator.Calculate(private_headers)) * 29 + ProxyRevalidate.GetHashCode()) * 29 + Public.GetHashCode()) * 29 + SharedMaxAge.GetHashCode();
		}

		public static CacheControlHeaderValue Parse(string input)
		{
			if (TryParse(input, out var parsedValue))
			{
				return parsedValue;
			}
			throw new FormatException(input);
		}

		public static bool TryParse(string input, out CacheControlHeaderValue parsedValue)
		{
			parsedValue = null;
			if (input == null)
			{
				return true;
			}
			CacheControlHeaderValue cacheControlHeaderValue = new CacheControlHeaderValue();
			Lexer lexer = new Lexer(input);
			Token token;
			do
			{
				token = lexer.Scan();
				if ((Token.Type)token != Token.Type.Token)
				{
					return false;
				}
				string stringValue = lexer.GetStringValue(token);
				bool flag = false;
				switch (stringValue)
				{
				case "no-store":
					cacheControlHeaderValue.NoStore = true;
					break;
				case "no-transform":
					cacheControlHeaderValue.NoTransform = true;
					break;
				case "only-if-cached":
					cacheControlHeaderValue.OnlyIfCached = true;
					break;
				case "public":
					cacheControlHeaderValue.Public = true;
					break;
				case "must-revalidate":
					cacheControlHeaderValue.MustRevalidate = true;
					break;
				case "proxy-revalidate":
					cacheControlHeaderValue.ProxyRevalidate = true;
					break;
				case "max-stale":
				{
					cacheControlHeaderValue.MaxStale = true;
					token = lexer.Scan();
					if ((Token.Type)token != Token.Type.SeparatorEqual)
					{
						flag = true;
						break;
					}
					token = lexer.Scan();
					if ((Token.Type)token != Token.Type.Token)
					{
						return false;
					}
					TimeSpan? maxStaleLimit = lexer.TryGetTimeSpanValue(token);
					if (!maxStaleLimit.HasValue)
					{
						return false;
					}
					cacheControlHeaderValue.MaxStaleLimit = maxStaleLimit;
					break;
				}
				case "max-age":
				case "s-maxage":
				case "min-fresh":
				{
					token = lexer.Scan();
					if ((Token.Type)token != Token.Type.SeparatorEqual)
					{
						return false;
					}
					token = lexer.Scan();
					if ((Token.Type)token != Token.Type.Token)
					{
						return false;
					}
					TimeSpan? maxStaleLimit = lexer.TryGetTimeSpanValue(token);
					if (!maxStaleLimit.HasValue)
					{
						return false;
					}
					switch (stringValue.Length)
					{
					case 7:
						cacheControlHeaderValue.MaxAge = maxStaleLimit;
						break;
					case 8:
						cacheControlHeaderValue.SharedMaxAge = maxStaleLimit;
						break;
					default:
						cacheControlHeaderValue.MinFresh = maxStaleLimit;
						break;
					}
					break;
				}
				case "private":
				case "no-cache":
				{
					if (stringValue.Length == 7)
					{
						cacheControlHeaderValue.Private = true;
					}
					else
					{
						cacheControlHeaderValue.NoCache = true;
					}
					token = lexer.Scan();
					if ((Token.Type)token != Token.Type.SeparatorEqual)
					{
						flag = true;
						break;
					}
					token = lexer.Scan();
					if ((Token.Type)token != Token.Type.QuotedString)
					{
						return false;
					}
					string[] array = lexer.GetQuotedStringValue(token).Split(',');
					for (int i = 0; i < array.Length; i++)
					{
						string item = array[i].Trim('\t', ' ');
						if (stringValue.Length == 7)
						{
							cacheControlHeaderValue.PrivateHeaders.Add(item);
							continue;
						}
						cacheControlHeaderValue.NoCache = true;
						cacheControlHeaderValue.NoCacheHeaders.Add(item);
					}
					break;
				}
				default:
				{
					string stringValue2 = lexer.GetStringValue(token);
					string value = null;
					token = lexer.Scan();
					if ((Token.Type)token == Token.Type.SeparatorEqual)
					{
						token = lexer.Scan();
						Token.Type kind = token.Kind;
						if ((uint)(kind - 2) > 1u)
						{
							return false;
						}
						value = lexer.GetStringValue(token);
					}
					else
					{
						flag = true;
					}
					cacheControlHeaderValue.Extensions.Add(NameValueHeaderValue.Create(stringValue2, value));
					break;
				}
				}
				if (!flag)
				{
					token = lexer.Scan();
				}
			}
			while ((Token.Type)token == Token.Type.SeparatorComma);
			if ((Token.Type)token != Token.Type.End)
			{
				return false;
			}
			parsedValue = cacheControlHeaderValue;
			return true;
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (NoStore)
			{
				stringBuilder.Append("no-store");
				stringBuilder.Append(", ");
			}
			if (NoTransform)
			{
				stringBuilder.Append("no-transform");
				stringBuilder.Append(", ");
			}
			if (OnlyIfCached)
			{
				stringBuilder.Append("only-if-cached");
				stringBuilder.Append(", ");
			}
			if (Public)
			{
				stringBuilder.Append("public");
				stringBuilder.Append(", ");
			}
			if (MustRevalidate)
			{
				stringBuilder.Append("must-revalidate");
				stringBuilder.Append(", ");
			}
			if (ProxyRevalidate)
			{
				stringBuilder.Append("proxy-revalidate");
				stringBuilder.Append(", ");
			}
			if (NoCache)
			{
				stringBuilder.Append("no-cache");
				if (no_cache_headers != null)
				{
					stringBuilder.Append("=\"");
					no_cache_headers.ToStringBuilder(stringBuilder);
					stringBuilder.Append("\"");
				}
				stringBuilder.Append(", ");
			}
			if (MaxAge.HasValue)
			{
				stringBuilder.Append("max-age=");
				stringBuilder.Append(MaxAge.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture));
				stringBuilder.Append(", ");
			}
			if (SharedMaxAge.HasValue)
			{
				stringBuilder.Append("s-maxage=");
				stringBuilder.Append(SharedMaxAge.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture));
				stringBuilder.Append(", ");
			}
			if (MaxStale)
			{
				stringBuilder.Append("max-stale");
				if (MaxStaleLimit.HasValue)
				{
					stringBuilder.Append("=");
					stringBuilder.Append(MaxStaleLimit.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture));
				}
				stringBuilder.Append(", ");
			}
			if (MinFresh.HasValue)
			{
				stringBuilder.Append("min-fresh=");
				stringBuilder.Append(MinFresh.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture));
				stringBuilder.Append(", ");
			}
			if (Private)
			{
				stringBuilder.Append("private");
				if (private_headers != null)
				{
					stringBuilder.Append("=\"");
					private_headers.ToStringBuilder(stringBuilder);
					stringBuilder.Append("\"");
				}
				stringBuilder.Append(", ");
			}
			extensions.ToStringBuilder(stringBuilder);
			if (stringBuilder.Length > 2 && stringBuilder[stringBuilder.Length - 2] == ',' && stringBuilder[stringBuilder.Length - 1] == ' ')
			{
				stringBuilder.Remove(stringBuilder.Length - 2, 2);
			}
			return stringBuilder.ToString();
		}
	}
	internal static class CollectionExtensions
	{
		public static bool SequenceEqual<TSource>(this List<TSource> first, List<TSource> second)
		{
			if (first == null)
			{
				if (second != null)
				{
					return second.Count == 0;
				}
				return true;
			}
			if (second == null)
			{
				if (first != null)
				{
					return first.Count == 0;
				}
				return true;
			}
			return Enumerable.SequenceEqual(first, second);
		}

		public static void SetValue(this List<NameValueHeaderValue> parameters, string key, string value)
		{
			for (int i = 0; i < parameters.Count; i++)
			{
				if (string.Equals(parameters[i].Name, key, StringComparison.OrdinalIgnoreCase))
				{
					if (value == null)
					{
						parameters.RemoveAt(i);
					}
					else
					{
						parameters[i].Value = value;
					}
					return;
				}
			}
			if (!string.IsNullOrEmpty(value))
			{
				parameters.Add(new NameValueHeaderValue(key, value));
			}
		}

		public static string ToString<T>(this List<T> list)
		{
			if (list == null || list.Count == 0)
			{
				return null;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < list.Count; i++)
			{
				stringBuilder.Append("; ");
				stringBuilder.Append(list[i]);
			}
			return stringBuilder.ToString();
		}

		public static void ToStringBuilder<T>(this List<T> list, StringBuilder sb)
		{
			if (list == null || list.Count == 0)
			{
				return;
			}
			for (int i = 0; i < list.Count; i++)
			{
				if (i > 0)
				{
					sb.Append(", ");
				}
				sb.Append(list[i]);
			}
		}
	}
	internal delegate bool ElementTryParser<T>(Lexer lexer, out T parsedValue, out Token token);
	internal static class CollectionParser
	{
		public static bool TryParse<T>(string input, int minimalCount, ElementTryParser<T> parser, out List<T> result) where T : class
		{
			Lexer lexer = new Lexer(input);
			result = new List<T>();
			Token token;
			do
			{
				if (!parser(lexer, out var parsedValue, out token))
				{
					return false;
				}
				if (parsedValue != null)
				{
					result.Add(parsedValue);
				}
			}
			while ((Token.Type)token == Token.Type.SeparatorComma);
			if ((Token.Type)token == Token.Type.End)
			{
				if (minimalCount > result.Count)
				{
					result = null;
					return false;
				}
				return true;
			}
			result = null;
			return false;
		}

		public static bool TryParse(string input, int minimalCount, out List<string> result)
		{
			return TryParse(input, minimalCount, (ElementTryParser<string>)TryParseStringElement, out result);
		}

		public static bool TryParseRepetition(string input, int minimalCount, out List<string> result)
		{
			return TryParseRepetition(input, minimalCount, (ElementTryParser<string>)TryParseStringElement, out result);
		}

		private static bool TryParseStringElement(Lexer lexer, out string parsedValue, out Token t)
		{
			t = lexer.Scan();
			if ((Token.Type)t == Token.Type.Token)
			{
				parsedValue = lexer.GetStringValue(t);
				if (parsedValue.Length == 0)
				{
					parsedValue = null;
				}
				t = lexer.Scan();
			}
			else
			{
				parsedValue = null;
			}
			return true;
		}

		public static bool TryParseRepetition<T>(string input, int minimalCount, ElementTryParser<T> parser, out List<T> result) where T : class
		{
			Lexer lexer = new Lexer(input);
			result = new List<T>();
			Token token;
			do
			{
				if (!parser(lexer, out var parsedValue, out token))
				{
					return false;
				}
				if (parsedValue != null)
				{
					result.Add(parsedValue);
				}
			}
			while ((Token.Type)token != Token.Type.End);
			if (minimalCount > result.Count)
			{
				return false;
			}
			return true;
		}
	}
	public class ContentDispositionHeaderValue : ICloneable
	{
		private string dispositionType;

		private List<NameValueHeaderValue> parameters;

		public DateTimeOffset? CreationDate
		{
			get
			{
				return GetDateValue("creation-date");
			}
			set
			{
				SetDateValue("creation-date", value);
			}
		}

		public string DispositionType
		{
			get
			{
				return dispositionType;
			}
			set
			{
				Parser.Token.Check(value);
				dispositionType = value;
			}
		}

		public string FileName
		{
			get
			{
				string text = FindParameter("filename");
				if (text == null)
				{
					return null;
				}
				return DecodeValue(text, extendedNotation: false);
			}
			set
			{
				if (value != null)
				{
					value = EncodeBase64Value(value);
				}
				SetValue("filename", value);
			}
		}

		public string FileNameStar
		{
			get
			{
				string text = FindParameter("filename*");
				if (text == null)
				{
					return null;
				}
				return DecodeValue(text, extendedNotation: true);
			}
			set
			{
				if (value != null)
				{
					value = EncodeRFC5987(value);
				}
				SetValue("filename*", value);
			}
		}

		public DateTimeOffset? ModificationDate
		{
			get
			{
				return GetDateValue("modification-date");
			}
			set
			{
				SetDateValue("modification-date", value);
			}
		}

		public string Name
		{
			get
			{
				string text = FindParameter("name");
				if (text == null)
				{
					return null;
				}
				return DecodeValue(text, extendedNotation: false);
			}
			set
			{
				if (value != null)
				{
					value = EncodeBase64Value(value);
				}
				SetValue("name", value);
			}
		}

		public ICollection<NameValueHeaderValue> Parameters => parameters ?? (parameters = new List<NameValueHeaderValue>());

		public DateTimeOffset? ReadDate
		{
			get
			{
				return GetDateValue("read-date");
			}
			set
			{
				SetDateValue("read-date", value);
			}
		}

		public long? Size
		{
			get
			{
				if (Parser.Long.TryParse(FindParameter("size"), out var result))
				{
					return result;
				}
				return null;
			}
			set
			{
				if (!value.HasValue)
				{
					SetValue("size", null);
					return;
				}
				if (value < 0)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				SetValue("size", value.Value.ToString(CultureInfo.InvariantCulture));
			}
		}

		private ContentDispositionHeaderValue()
		{
		}

		public ContentDispositionHeaderValue(string dispositionType)
		{
			DispositionType = dispositionType;
		}

		protected ContentDispositionHeaderValue(ContentDispositionHeaderValue source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			dispositionType = source.dispositionType;
			if (source.parameters == null)
			{
				return;
			}
			foreach (NameValueHeaderValue parameter in source.parameters)
			{
				Parameters.Add(new NameValueHeaderValue(parameter));
			}
		}

		object ICloneable.Clone()
		{
			return new ContentDispositionHeaderValue(this);
		}

		public override bool Equals(object obj)
		{
			if (obj is ContentDispositionHeaderValue contentDispositionHeaderValue && string.Equals(contentDispositionHeaderValue.dispositionType, dispositionType, StringComparison.OrdinalIgnoreCase))
			{
				return contentDispositionHeaderValue.parameters.SequenceEqual(parameters);
			}
			return false;
		}

		private string FindParameter(string name)
		{
			if (parameters == null)
			{
				return null;
			}
			foreach (NameValueHeaderValue parameter in parameters)
			{
				if (string.Equals(parameter.Name, name, StringComparison.OrdinalIgnoreCase))
				{
					return parameter.Value;
				}
			}
			return null;
		}

		private DateTimeOffset? GetDateValue(string name)
		{
			string text = FindParameter(name);
			if (text == null || text == null)
			{
				return null;
			}
			if (text.Length < 3)
			{
				return null;
			}
			if (text[0] == '"')
			{
				text = text.Substring(1, text.Length - 2);
			}
			if (Lexer.TryGetDateValue(text, out var value))
			{
				return value;
			}
			return null;
		}

		private static string EncodeBase64Value(string value)
		{
			bool flag = value.Length > 1 && value[0] == '"' && value[value.Length - 1] == '"';
			if (flag)
			{
				value = value.Substring(1, value.Length - 2);
			}
			for (int i = 0; i < value.Length; i++)
			{
				if (value[i] > '\u007f')
				{
					Encoding uTF = Encoding.UTF8;
					return $"\"=?{uTF.WebName}?B?{Convert.ToBase64String(uTF.GetBytes(value))}?=\"";
				}
			}
			if (flag || !Lexer.IsValidToken(value))
			{
				return "\"" + value + "\"";
			}
			return value;
		}

		private static string EncodeRFC5987(string value)
		{
			Encoding uTF = Encoding.UTF8;
			StringBuilder stringBuilder = new StringBuilder(value.Length + 11);
			stringBuilder.Append(uTF.WebName);
			stringBuilder.Append('\'');
			stringBuilder.Append('\'');
			foreach (char c in value)
			{
				if (c > '\u007f')
				{
					byte[] bytes = uTF.GetBytes(new char[1] { c });
					foreach (byte b in bytes)
					{
						stringBuilder.Append('%');
						stringBuilder.Append(b.ToString("X2"));
					}
				}
				else if (!Lexer.IsValidCharacter(c) || c == '*' || c == '?' || c == '%')
				{
					stringBuilder.Append(Uri.HexEscape(c));
				}
				else
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		private static string DecodeValue(string value, bool extendedNotation)
		{
			if (value.Length < 2)
			{
				return value;
			}
			string[] array;
			Encoding encoding;
			if (value[0] == '"')
			{
				array = value.Split('?');
				if (array.Length != 5 || array[0] != "\"=" || array[4] != "=\"" || (array[2] != "B" && array[2] != "b"))
				{
					return value;
				}
				try
				{
					encoding = Encoding.GetEncoding(array[1]);
					return encoding.GetString(Convert.FromBase64String(array[3]));
				}
				catch
				{
					return value;
				}
			}
			if (!extendedNotation)
			{
				return value;
			}
			array = value.Split('\'');
			if (array.Length != 3)
			{
				return null;
			}
			try
			{
				encoding = Encoding.GetEncoding(array[0]);
			}
			catch
			{
				return null;
			}
			value = array[2];
			if (value.IndexOf('%') < 0)
			{
				return value;
			}
			StringBuilder stringBuilder = new StringBuilder();
			byte[] array2 = null;
			int num = 0;
			int index = 0;
			while (index < value.Length)
			{
				char c = value[index];
				if (c == '%')
				{
					char c2 = c;
					c = Uri.HexUnescape(value, ref index);
					if (c != c2)
					{
						if (array2 == null)
						{
							array2 = new byte[value.Length - index + 1];
						}
						array2[num++] = (byte)c;
						continue;
					}
				}
				else
				{
					index++;
				}
				if (num != 0)
				{
					stringBuilder.Append(encoding.GetChars(array2, 0, num));
					num = 0;
				}
				stringBuilder.Append(c);
			}
			if (num != 0)
			{
				stringBuilder.Append(encoding.GetChars(array2, 0, num));
			}
			return stringBuilder.ToString();
		}

		public override int GetHashCode()
		{
			return dispositionType.ToLowerInvariant().GetHashCode() ^ HashCodeCalculator.Calculate(parameters);
		}

		public static ContentDispositionHeaderValue Parse(string input)
		{
			if (TryParse(input, out var parsedVa

BepInEx/core/System.Net.ServerSentEvents.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using FxResources.System.Net.ServerSentEvents;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Net.ServerSentEvents")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides a simple parser for server-sent events (SSE).\r\n\r\nCommonly Used Types:\r\nSystem.Net.ServerSentEvents.SseParser")]
[assembly: AssemblyFileVersion("9.0.925.41916")]
[assembly: AssemblyInformationalVersion("9.0.9+893c2ebbd49952ca49e93298148af2d95a61a0a4")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Net.ServerSentEvents")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.9")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.System.Net.ServerSentEvents
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string InvalidOperation_EnumerateOnlyOnce => GetResourceString("InvalidOperation_EnumerateOnlyOnce");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Net.ServerSentEvents
{
	public sealed class SseParser<T>
	{
		private const byte CR = 13;

		private const byte LF = 10;

		private const int DefaultArrayPoolRentSize = 1024;

		private readonly Stream _stream;

		private readonly SseItemParser<T> _itemParser;

		private int _used;

		private byte[] _lineBuffer = Array.Empty<byte>();

		private int _lineOffset;

		private int _lineLength;

		private int _newlineIndex;

		private int _lastSearchedForNewline;

		private bool _eof;

		private byte[] _dataBuffer;

		private int _dataLength;

		private bool _dataAppended;

		private string _eventType = "message";

		private static ReadOnlySpan<byte> CRLF => "\r\n"u8;

		public string LastEventId { get; private set; } = string.Empty;


		public TimeSpan ReconnectionInterval { get; private set; } = Timeout.InfiniteTimeSpan;


		private static ReadOnlySpan<byte> Utf8Bom => "\ufeff"u8;

		internal SseParser(Stream stream, SseItemParser<T> itemParser)
		{
			_stream = stream;
			_itemParser = itemParser;
		}

		public IEnumerable<SseItem<T>> Enumerate()
		{
			ThrowIfNotFirstEnumeration();
			_lineBuffer = ArrayPool<byte>.Shared.Rent(1024);
			try
			{
				while (FillLineBuffer() != 0 && _lineLength < Utf8Bom.Length)
				{
				}
				SkipBomIfPresent();
				while (true)
				{
					GetNextSearchOffsetAndLength(out var searchOffset, out var searchLength);
					_newlineIndex = _lineBuffer.AsSpan(searchOffset, searchLength).IndexOfAny<byte>(13, 10);
					if (_newlineIndex >= 0)
					{
						_lastSearchedForNewline = -1;
						_newlineIndex += searchOffset;
						if (_lineBuffer[_newlineIndex] == 10 || _newlineIndex - _lineOffset + 1 < _lineLength || _eof)
						{
							if (ProcessLine(out var sseItem, out var advance))
							{
								yield return sseItem;
							}
							_lineOffset += advance;
							_lineLength -= advance;
							continue;
						}
					}
					else
					{
						_lastSearchedForNewline = _lineOffset + _lineLength;
					}
					if (!_eof)
					{
						FillLineBuffer();
						continue;
					}
					break;
				}
			}
			finally
			{
				SseParser<T> sseParser = this;
				ArrayPool<byte>.Shared.Return(sseParser._lineBuffer);
				if (sseParser._dataBuffer != null)
				{
					ArrayPool<byte>.Shared.Return(sseParser._dataBuffer);
				}
			}
		}

		public async IAsyncEnumerable<SseItem<T>> EnumerateAsync([EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			ThrowIfNotFirstEnumeration();
			_lineBuffer = ArrayPool<byte>.Shared.Rent(1024);
			try
			{
				while (await FillLineBufferAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) != 0 && _lineLength < Utf8Bom.Length)
				{
				}
				SkipBomIfPresent();
				while (true)
				{
					GetNextSearchOffsetAndLength(out var searchOffset, out var searchLength);
					_newlineIndex = _lineBuffer.AsSpan(searchOffset, searchLength).IndexOfAny<byte>(13, 10);
					if (_newlineIndex >= 0)
					{
						_lastSearchedForNewline = -1;
						_newlineIndex += searchOffset;
						if (_lineBuffer[_newlineIndex] == 10 || _newlineIndex - _lineOffset + 1 < _lineLength || _eof)
						{
							if (ProcessLine(out var sseItem, out var advance))
							{
								yield return sseItem;
							}
							_lineOffset += advance;
							_lineLength -= advance;
							continue;
						}
					}
					else
					{
						_lastSearchedForNewline = searchOffset + searchLength;
					}
					if (_eof)
					{
						break;
					}
					await FillLineBufferAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				}
			}
			finally
			{
				ArrayPool<byte>.Shared.Return(_lineBuffer);
				if (_dataBuffer != null)
				{
					ArrayPool<byte>.Shared.Return(_dataBuffer);
				}
			}
		}

		private void GetNextSearchOffsetAndLength(out int searchOffset, out int searchLength)
		{
			if (_lastSearchedForNewline > _lineOffset)
			{
				searchOffset = _lastSearchedForNewline;
				searchLength = _lineLength - (_lastSearchedForNewline - _lineOffset);
			}
			else
			{
				searchOffset = _lineOffset;
				searchLength = _lineLength;
			}
		}

		private int GetNewLineLength()
		{
			if (!_lineBuffer.AsSpan(_newlineIndex, _lineLength - (_newlineIndex - _lineOffset)).StartsWith(CRLF))
			{
				return 1;
			}
			return 2;
		}

		private void ShiftOrGrowLineBufferIfNecessary()
		{
			if (_lineOffset + _lineLength != _lineBuffer.Length)
			{
				return;
			}
			if (_lineOffset != 0)
			{
				_lineBuffer.AsSpan(_lineOffset, _lineLength).CopyTo(_lineBuffer);
				if (_lastSearchedForNewline >= 0)
				{
					_lastSearchedForNewline -= _lineOffset;
				}
				_lineOffset = 0;
			}
			else if (_lineLength == _lineBuffer.Length)
			{
				GrowBuffer(ref _lineBuffer, _lineBuffer.Length * 2);
			}
		}

		private bool ProcessLine(out SseItem<T> sseItem, out int advance)
		{
			ReadOnlySpan<byte> readOnlySpan = _lineBuffer.AsSpan(_lineOffset, _newlineIndex - _lineOffset);
			if (readOnlySpan.IsEmpty)
			{
				advance = GetNewLineLength();
				if (_dataAppended)
				{
					sseItem = new SseItem<T>(_itemParser(_eventType, _dataBuffer.AsSpan(0, _dataLength)), _eventType);
					_eventType = "message";
					_dataLength = 0;
					_dataAppended = false;
					return true;
				}
				sseItem = default(SseItem<T>);
				return false;
			}
			int num = readOnlySpan.IndexOf<byte>(58);
			ReadOnlySpan<byte> span;
			ReadOnlySpan<byte> readOnlySpan2;
			if (num >= 0)
			{
				span = readOnlySpan.Slice(0, num);
				readOnlySpan2 = readOnlySpan.Slice(num + 1);
				if (!readOnlySpan2.IsEmpty && readOnlySpan2[0] == 32)
				{
					readOnlySpan2 = readOnlySpan2.Slice(1);
				}
			}
			else
			{
				span = readOnlySpan;
				readOnlySpan2 = default(ReadOnlySpan<byte>);
			}
			long result;
			if (span.SequenceEqual("data"u8))
			{
				if (!_dataAppended)
				{
					int newLineLength = GetNewLineLength();
					ReadOnlySpan<byte> span2 = _lineBuffer.AsSpan(_newlineIndex + newLineLength, _lineLength - readOnlySpan.Length - newLineLength);
					if (!span2.IsEmpty && (span2[0] == 10 || (span2[0] == 13 && span2.Length > 1)))
					{
						advance = readOnlySpan.Length + newLineLength + ((!span2.StartsWith(CRLF)) ? 1 : 2);
						sseItem = new SseItem<T>(_itemParser(_eventType, readOnlySpan2), _eventType);
						_eventType = "message";
						return true;
					}
				}
				if (_dataBuffer == null || _dataLength + _lineLength + 1 > _dataBuffer.Length)
				{
					GrowBuffer(ref _dataBuffer, _dataLength + _lineLength + 1);
				}
				if (_dataAppended)
				{
					_dataBuffer[_dataLength++] = 10;
				}
				readOnlySpan2.CopyTo(_dataBuffer.AsSpan(_dataLength));
				_dataLength += readOnlySpan2.Length;
				_dataAppended = true;
			}
			else if (span.SequenceEqual("event"u8))
			{
				_eventType = SseParser.Utf8GetString(readOnlySpan2);
			}
			else if (span.SequenceEqual("id"u8))
			{
				if (readOnlySpan2.IndexOf<byte>(0) < 0)
				{
					LastEventId = SseParser.Utf8GetString(readOnlySpan2);
				}
			}
			else if (span.SequenceEqual("retry"u8) && long.TryParse(SseParser.Utf8GetString(readOnlySpan2), NumberStyles.None, CultureInfo.InvariantCulture, out result))
			{
				ReconnectionInterval = TimeSpan.FromMilliseconds(result);
			}
			advance = readOnlySpan.Length + GetNewLineLength();
			sseItem = default(SseItem<T>);
			return false;
		}

		private void ThrowIfNotFirstEnumeration()
		{
			if (Interlocked.Exchange(ref _used, 1) != 0)
			{
				throw new InvalidOperationException(System.SR.InvalidOperation_EnumerateOnlyOnce);
			}
		}

		private int FillLineBuffer()
		{
			ShiftOrGrowLineBufferIfNecessary();
			int num = _lineOffset + _lineLength;
			int num2 = _stream.Read(_lineBuffer, num, _lineBuffer.Length - num);
			if (num2 > 0)
			{
				_lineLength += num2;
			}
			else
			{
				_eof = true;
				num2 = 0;
			}
			return num2;
		}

		private async ValueTask<int> FillLineBufferAsync(CancellationToken cancellationToken)
		{
			ShiftOrGrowLineBufferIfNecessary();
			int num = _lineOffset + _lineLength;
			int num2 = await new ValueTask<int>(_stream.ReadAsync(_lineBuffer, num, _lineBuffer.Length - num, cancellationToken)).ConfigureAwait(continueOnCapturedContext: false);
			if (num2 > 0)
			{
				_lineLength += num2;
			}
			else
			{
				_eof = true;
				num2 = 0;
			}
			return num2;
		}

		private void SkipBomIfPresent()
		{
			if (_lineBuffer.AsSpan(0, _lineLength).StartsWith(Utf8Bom))
			{
				_lineOffset += 3;
				_lineLength -= 3;
			}
		}

		private static void GrowBuffer([NotNull] ref byte[] buffer, int minimumLength)
		{
			byte[] array = buffer;
			buffer = ArrayPool<byte>.Shared.Rent(Math.Max(minimumLength, 1024));
			if (array != null)
			{
				Array.Copy(array, buffer, array.Length);
				ArrayPool<byte>.Shared.Return(array);
			}
		}
	}
	public readonly struct SseItem<T>
	{
		public T Data { get; }

		public string EventType { get; }

		public SseItem(T data, string eventType)
		{
			Data = data;
			EventType = eventType;
		}
	}
	public delegate T SseItemParser<out T>(string eventType, ReadOnlySpan<byte> data);
	public static class SseParser
	{
		public const string EventTypeDefault = "message";

		public static SseParser<string> Create(Stream sseStream)
		{
			return Create(sseStream, (string _, ReadOnlySpan<byte> bytes) => Utf8GetString(bytes));
		}

		public static SseParser<T> Create<T>(Stream sseStream, SseItemParser<T> itemParser)
		{
			return new SseParser<T>(sseStream ?? throw new ArgumentNullException("sseStream"), itemParser ?? throw new ArgumentNullException("itemParser"));
		}

		internal unsafe static string Utf8GetString(ReadOnlySpan<byte> bytes)
		{
			fixed (byte* ptr = bytes)
			{
				if (ptr != null)
				{
					return Encoding.UTF8.GetString(ptr, bytes.Length);
				}
				return string.Empty;
			}
		}
	}
}

BepInEx/core/System.Numerics.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
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;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Numerics.dll")]
[assembly: AssemblyDescription("System.Numerics.dll")]
[assembly: AssemblyDefaultAlias("System.Numerics.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: SecurityCritical]
[assembly: CompilationRelaxations(8)]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class SR
{
	public const string Argument_BadFormatSpecifier = "Format specifier was invalid.";

	public const string Argument_InvalidNumberStyles = "An undefined NumberStyles value is being used.";

	public const string Argument_InvalidHexStyle = "With the AllowHexSpecifier bit set in the enum bit field, the only other valid bits that can be combined into the enum value must be a subset of those in HexNumber.";

	public const string Argument_MustBeBigInt = "The parameter must be a BigInteger.";

	public const string Format_TooLarge = "The value is too large to be represented by this format specifier.";

	public const string ArgumentOutOfRange_MustBeNonNeg = "The number must be greater than or equal to zero.";

	public const string Overflow_BigIntInfinity = "BigInteger cannot represent infinity.";

	public const string Overflow_NotANumber = "The value is not a number.";

	public const string Overflow_ParseBigInteger = "The value could not be parsed.";

	public const string Overflow_Int32 = "Value was either too large or too small for an Int32.";

	public const string Overflow_Int64 = "Value was either too large or too small for an Int64.";

	public const string Overflow_UInt32 = "Value was either too large or too small for a UInt32.";

	public const string Overflow_UInt64 = "Value was either too large or too small for a UInt64.";

	public const string Overflow_Decimal = "Value was either too large or too small for a Decimal.";

	public const string Arg_ArgumentOutOfRangeException = "Index was out of bounds:";

	public const string Arg_ElementsInSourceIsGreaterThanDestination = "Number of elements in source vector is greater than the destination array";

	public const string Arg_NullArgumentNullRef = "The method was called with a null array argument.";

	public const string Arg_TypeNotSupported = "Specified type is not supported";

	public const string ArgumentException_BufferNotFromPool = "The buffer is not associated with this pool and may not be returned to it.";

	public const string Overflow_Negative_Unsigned = "Negative values do not have an unsigned representation.";

	internal static string GetString(string name, params object[] args)
	{
		return GetString(CultureInfo.InvariantCulture, name, args);
	}

	internal static string GetString(CultureInfo culture, string name, params object[] args)
	{
		return string.Format(culture, name, args);
	}

	internal static string GetString(string name)
	{
		return name;
	}

	internal static string GetString(CultureInfo culture, string name)
	{
		return name;
	}

	internal static string Format(string resourceFormat, params object[] args)
	{
		if (args != null)
		{
			return string.Format(CultureInfo.InvariantCulture, resourceFormat, args);
		}
		return resourceFormat;
	}

	internal static string Format(string resourceFormat, object p1)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1);
	}

	internal static string Format(string resourceFormat, object p1, object p2)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2);
	}

	internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2)
	{
		return string.Format(ci, resourceFormat, p1, p2);
	}

	internal static string Format(string resourceFormat, object p1, object p2, object p3)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3);
	}

	internal static string GetResourceString(string str)
	{
		return str;
	}
}
namespace System.Numerics
{
	public struct Matrix3x2 : IEquatable<Matrix3x2>
	{
		public float M11;

		public float M12;

		public float M21;

		public float M22;

		public float M31;

		public float M32;

		private static readonly Matrix3x2 _identity = new Matrix3x2(1f, 0f, 0f, 1f, 0f, 0f);

		public static Matrix3x2 Identity => _identity;

		public bool IsIdentity
		{
			get
			{
				if (M11 == 1f && M22 == 1f && M12 == 0f && M21 == 0f && M31 == 0f)
				{
					return M32 == 0f;
				}
				return false;
			}
		}

		public Vector2 Translation
		{
			get
			{
				return new Vector2(M31, M32);
			}
			set
			{
				M31 = value.X;
				M32 = value.Y;
			}
		}

		public Matrix3x2(float m11, float m12, float m21, float m22, float m31, float m32)
		{
			M11 = m11;
			M12 = m12;
			M21 = m21;
			M22 = m22;
			M31 = m31;
			M32 = m32;
		}

		public static Matrix3x2 CreateTranslation(Vector2 position)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = 1f;
			result.M12 = 0f;
			result.M21 = 0f;
			result.M22 = 1f;
			result.M31 = position.X;
			result.M32 = position.Y;
			return result;
		}

		public static Matrix3x2 CreateTranslation(float xPosition, float yPosition)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = 1f;
			result.M12 = 0f;
			result.M21 = 0f;
			result.M22 = 1f;
			result.M31 = xPosition;
			result.M32 = yPosition;
			return result;
		}

		public static Matrix3x2 CreateScale(float xScale, float yScale)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = xScale;
			result.M12 = 0f;
			result.M21 = 0f;
			result.M22 = yScale;
			result.M31 = 0f;
			result.M32 = 0f;
			return result;
		}

		public static Matrix3x2 CreateScale(float xScale, float yScale, Vector2 centerPoint)
		{
			float m = centerPoint.X * (1f - xScale);
			float m2 = centerPoint.Y * (1f - yScale);
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = xScale;
			result.M12 = 0f;
			result.M21 = 0f;
			result.M22 = yScale;
			result.M31 = m;
			result.M32 = m2;
			return result;
		}

		public static Matrix3x2 CreateScale(Vector2 scales)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = scales.X;
			result.M12 = 0f;
			result.M21 = 0f;
			result.M22 = scales.Y;
			result.M31 = 0f;
			result.M32 = 0f;
			return result;
		}

		public static Matrix3x2 CreateScale(Vector2 scales, Vector2 centerPoint)
		{
			float m = centerPoint.X * (1f - scales.X);
			float m2 = centerPoint.Y * (1f - scales.Y);
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = scales.X;
			result.M12 = 0f;
			result.M21 = 0f;
			result.M22 = scales.Y;
			result.M31 = m;
			result.M32 = m2;
			return result;
		}

		public static Matrix3x2 CreateScale(float scale)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = scale;
			result.M12 = 0f;
			result.M21 = 0f;
			result.M22 = scale;
			result.M31 = 0f;
			result.M32 = 0f;
			return result;
		}

		public static Matrix3x2 CreateScale(float scale, Vector2 centerPoint)
		{
			float m = centerPoint.X * (1f - scale);
			float m2 = centerPoint.Y * (1f - scale);
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = scale;
			result.M12 = 0f;
			result.M21 = 0f;
			result.M22 = scale;
			result.M31 = m;
			result.M32 = m2;
			return result;
		}

		public static Matrix3x2 CreateSkew(float radiansX, float radiansY)
		{
			float m = MathF.Tan(radiansX);
			float m2 = MathF.Tan(radiansY);
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = 1f;
			result.M12 = m2;
			result.M21 = m;
			result.M22 = 1f;
			result.M31 = 0f;
			result.M32 = 0f;
			return result;
		}

		public static Matrix3x2 CreateSkew(float radiansX, float radiansY, Vector2 centerPoint)
		{
			float num = MathF.Tan(radiansX);
			float num2 = MathF.Tan(radiansY);
			float m = (0f - centerPoint.Y) * num;
			float m2 = (0f - centerPoint.X) * num2;
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = 1f;
			result.M12 = num2;
			result.M21 = num;
			result.M22 = 1f;
			result.M31 = m;
			result.M32 = m2;
			return result;
		}

		public static Matrix3x2 CreateRotation(float radians)
		{
			radians = MathF.IEEERemainder(radians, (float)Math.PI * 2f);
			float num;
			float num2;
			if (radians > -1.7453294E-05f && radians < 1.7453294E-05f)
			{
				num = 1f;
				num2 = 0f;
			}
			else if (radians > 1.570779f && radians < 1.5708138f)
			{
				num = 0f;
				num2 = 1f;
			}
			else if (radians < -3.1415753f || radians > 3.1415753f)
			{
				num = -1f;
				num2 = 0f;
			}
			else if (radians > -1.5708138f && radians < -1.570779f)
			{
				num = 0f;
				num2 = -1f;
			}
			else
			{
				num = MathF.Cos(radians);
				num2 = MathF.Sin(radians);
			}
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = num;
			result.M12 = num2;
			result.M21 = 0f - num2;
			result.M22 = num;
			result.M31 = 0f;
			result.M32 = 0f;
			return result;
		}

		public static Matrix3x2 CreateRotation(float radians, Vector2 centerPoint)
		{
			radians = MathF.IEEERemainder(radians, (float)Math.PI * 2f);
			float num;
			float num2;
			if (radians > -1.7453294E-05f && radians < 1.7453294E-05f)
			{
				num = 1f;
				num2 = 0f;
			}
			else if (radians > 1.570779f && radians < 1.5708138f)
			{
				num = 0f;
				num2 = 1f;
			}
			else if (radians < -3.1415753f || radians > 3.1415753f)
			{
				num = -1f;
				num2 = 0f;
			}
			else if (radians > -1.5708138f && radians < -1.570779f)
			{
				num = 0f;
				num2 = -1f;
			}
			else
			{
				num = MathF.Cos(radians);
				num2 = MathF.Sin(radians);
			}
			float m = centerPoint.X * (1f - num) + centerPoint.Y * num2;
			float m2 = centerPoint.Y * (1f - num) - centerPoint.X * num2;
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = num;
			result.M12 = num2;
			result.M21 = 0f - num2;
			result.M22 = num;
			result.M31 = m;
			result.M32 = m2;
			return result;
		}

		public float GetDeterminant()
		{
			return M11 * M22 - M21 * M12;
		}

		public static bool Invert(Matrix3x2 matrix, out Matrix3x2 result)
		{
			float num = matrix.M11 * matrix.M22 - matrix.M21 * matrix.M12;
			if (MathF.Abs(num) < float.Epsilon)
			{
				result = new Matrix3x2(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN);
				return false;
			}
			float num2 = 1f / num;
			result.M11 = matrix.M22 * num2;
			result.M12 = (0f - matrix.M12) * num2;
			result.M21 = (0f - matrix.M21) * num2;
			result.M22 = matrix.M11 * num2;
			result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * num2;
			result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * num2;
			return true;
		}

		public static Matrix3x2 Lerp(Matrix3x2 matrix1, Matrix3x2 matrix2, float amount)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount;
			result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount;
			result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount;
			result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount;
			result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount;
			result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount;
			return result;
		}

		public static Matrix3x2 Negate(Matrix3x2 value)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = 0f - value.M11;
			result.M12 = 0f - value.M12;
			result.M21 = 0f - value.M21;
			result.M22 = 0f - value.M22;
			result.M31 = 0f - value.M31;
			result.M32 = 0f - value.M32;
			return result;
		}

		public static Matrix3x2 Add(Matrix3x2 value1, Matrix3x2 value2)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = value1.M11 + value2.M11;
			result.M12 = value1.M12 + value2.M12;
			result.M21 = value1.M21 + value2.M21;
			result.M22 = value1.M22 + value2.M22;
			result.M31 = value1.M31 + value2.M31;
			result.M32 = value1.M32 + value2.M32;
			return result;
		}

		public static Matrix3x2 Subtract(Matrix3x2 value1, Matrix3x2 value2)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = value1.M11 - value2.M11;
			result.M12 = value1.M12 - value2.M12;
			result.M21 = value1.M21 - value2.M21;
			result.M22 = value1.M22 - value2.M22;
			result.M31 = value1.M31 - value2.M31;
			result.M32 = value1.M32 - value2.M32;
			return result;
		}

		public static Matrix3x2 Multiply(Matrix3x2 value1, Matrix3x2 value2)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21;
			result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22;
			result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21;
			result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22;
			result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31;
			result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32;
			return result;
		}

		public static Matrix3x2 Multiply(Matrix3x2 value1, float value2)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = value1.M11 * value2;
			result.M12 = value1.M12 * value2;
			result.M21 = value1.M21 * value2;
			result.M22 = value1.M22 * value2;
			result.M31 = value1.M31 * value2;
			result.M32 = value1.M32 * value2;
			return result;
		}

		public static Matrix3x2 operator -(Matrix3x2 value)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = 0f - value.M11;
			result.M12 = 0f - value.M12;
			result.M21 = 0f - value.M21;
			result.M22 = 0f - value.M22;
			result.M31 = 0f - value.M31;
			result.M32 = 0f - value.M32;
			return result;
		}

		public static Matrix3x2 operator +(Matrix3x2 value1, Matrix3x2 value2)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = value1.M11 + value2.M11;
			result.M12 = value1.M12 + value2.M12;
			result.M21 = value1.M21 + value2.M21;
			result.M22 = value1.M22 + value2.M22;
			result.M31 = value1.M31 + value2.M31;
			result.M32 = value1.M32 + value2.M32;
			return result;
		}

		public static Matrix3x2 operator -(Matrix3x2 value1, Matrix3x2 value2)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = value1.M11 - value2.M11;
			result.M12 = value1.M12 - value2.M12;
			result.M21 = value1.M21 - value2.M21;
			result.M22 = value1.M22 - value2.M22;
			result.M31 = value1.M31 - value2.M31;
			result.M32 = value1.M32 - value2.M32;
			return result;
		}

		public static Matrix3x2 operator *(Matrix3x2 value1, Matrix3x2 value2)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21;
			result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22;
			result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21;
			result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22;
			result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31;
			result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32;
			return result;
		}

		public static Matrix3x2 operator *(Matrix3x2 value1, float value2)
		{
			Matrix3x2 result = default(Matrix3x2);
			result.M11 = value1.M11 * value2;
			result.M12 = value1.M12 * value2;
			result.M21 = value1.M21 * value2;
			result.M22 = value1.M22 * value2;
			result.M31 = value1.M31 * value2;
			result.M32 = value1.M32 * value2;
			return result;
		}

		public static bool operator ==(Matrix3x2 value1, Matrix3x2 value2)
		{
			if (value1.M11 == value2.M11 && value1.M22 == value2.M22 && value1.M12 == value2.M12 && value1.M21 == value2.M21 && value1.M31 == value2.M31)
			{
				return value1.M32 == value2.M32;
			}
			return false;
		}

		public static bool operator !=(Matrix3x2 value1, Matrix3x2 value2)
		{
			if (value1.M11 == value2.M11 && value1.M12 == value2.M12 && value1.M21 == value2.M21 && value1.M22 == value2.M22 && value1.M31 == value2.M31)
			{
				return value1.M32 != value2.M32;
			}
			return true;
		}

		public bool Equals(Matrix3x2 other)
		{
			if (M11 == other.M11 && M22 == other.M22 && M12 == other.M12 && M21 == other.M21 && M31 == other.M31)
			{
				return M32 == other.M32;
			}
			return false;
		}

		public override bool Equals(object obj)
		{
			if (obj is Matrix3x2)
			{
				return Equals((Matrix3x2)obj);
			}
			return false;
		}

		public override string ToString()
		{
			CultureInfo currentCulture = CultureInfo.CurrentCulture;
			return string.Format(currentCulture, "{{ {{M11:{0} M12:{1}}} {{M21:{2} M22:{3}}} {{M31:{4} M32:{5}}} }}", M11.ToString(currentCulture), M12.ToString(currentCulture), M21.ToString(currentCulture), M22.ToString(currentCulture), M31.ToString(currentCulture), M32.ToString(currentCulture));
		}

		public override int GetHashCode()
		{
			return M11.GetHashCode() + M12.GetHashCode() + M21.GetHashCode() + M22.GetHashCode() + M31.GetHashCode() + M32.GetHashCode();
		}
	}
	public struct Matrix4x4 : IEquatable<Matrix4x4>
	{
		private struct CanonicalBasis
		{
			public Vector3 Row0;

			public Vector3 Row1;

			public Vector3 Row2;
		}

		private struct VectorBasis
		{
			public unsafe Vector3* Element0;

			public unsafe Vector3* Element1;

			public unsafe Vector3* Element2;
		}

		public float M11;

		public float M12;

		public float M13;

		public float M14;

		public float M21;

		public float M22;

		public float M23;

		public float M24;

		public float M31;

		public float M32;

		public float M33;

		public float M34;

		public float M41;

		public float M42;

		public float M43;

		public float M44;

		private static readonly Matrix4x4 _identity = new Matrix4x4(1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f, 0f, 0f, 0f, 0f, 1f);

		public static Matrix4x4 Identity => _identity;

		public bool IsIdentity
		{
			get
			{
				if (M11 == 1f && M22 == 1f && M33 == 1f && M44 == 1f && M12 == 0f && M13 == 0f && M14 == 0f && M21 == 0f && M23 == 0f && M24 == 0f && M31 == 0f && M32 == 0f && M34 == 0f && M41 == 0f && M42 == 0f)
				{
					return M43 == 0f;
				}
				return false;
			}
		}

		public Vector3 Translation
		{
			get
			{
				return new Vector3(M41, M42, M43);
			}
			set
			{
				M41 = value.X;
				M42 = value.Y;
				M43 = value.Z;
			}
		}

		public Matrix4x4(float m11, float m12, float m13, float m14, float m21, float m22, float m23, float m24, float m31, float m32, float m33, float m34, float m41, float m42, float m43, float m44)
		{
			M11 = m11;
			M12 = m12;
			M13 = m13;
			M14 = m14;
			M21 = m21;
			M22 = m22;
			M23 = m23;
			M24 = m24;
			M31 = m31;
			M32 = m32;
			M33 = m33;
			M34 = m34;
			M41 = m41;
			M42 = m42;
			M43 = m43;
			M44 = m44;
		}

		public Matrix4x4(Matrix3x2 value)
		{
			M11 = value.M11;
			M12 = value.M12;
			M13 = 0f;
			M14 = 0f;
			M21 = value.M21;
			M22 = value.M22;
			M23 = 0f;
			M24 = 0f;
			M31 = 0f;
			M32 = 0f;
			M33 = 1f;
			M34 = 0f;
			M41 = value.M31;
			M42 = value.M32;
			M43 = 0f;
			M44 = 1f;
		}

		public static Matrix4x4 CreateBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 cameraUpVector, Vector3 cameraForwardVector)
		{
			Vector3 left = new Vector3(objectPosition.X - cameraPosition.X, objectPosition.Y - cameraPosition.Y, objectPosition.Z - cameraPosition.Z);
			float num = left.LengthSquared();
			left = ((!(num < 0.0001f)) ? Vector3.Multiply(left, 1f / MathF.Sqrt(num)) : (-cameraForwardVector));
			Vector3 vector = Vector3.Normalize(Vector3.Cross(cameraUpVector, left));
			Vector3 vector2 = Vector3.Cross(left, vector);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = vector.X;
			result.M12 = vector.Y;
			result.M13 = vector.Z;
			result.M14 = 0f;
			result.M21 = vector2.X;
			result.M22 = vector2.Y;
			result.M23 = vector2.Z;
			result.M24 = 0f;
			result.M31 = left.X;
			result.M32 = left.Y;
			result.M33 = left.Z;
			result.M34 = 0f;
			result.M41 = objectPosition.X;
			result.M42 = objectPosition.Y;
			result.M43 = objectPosition.Z;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateConstrainedBillboard(Vector3 objectPosition, Vector3 cameraPosition, Vector3 rotateAxis, Vector3 cameraForwardVector, Vector3 objectForwardVector)
		{
			Vector3 left = new Vector3(objectPosition.X - cameraPosition.X, objectPosition.Y - cameraPosition.Y, objectPosition.Z - cameraPosition.Z);
			float num = left.LengthSquared();
			left = ((!(num < 0.0001f)) ? Vector3.Multiply(left, 1f / MathF.Sqrt(num)) : (-cameraForwardVector));
			Vector3 vector = rotateAxis;
			Vector3 vector3;
			Vector3 vector2;
			if (MathF.Abs(Vector3.Dot(rotateAxis, left)) > 0.99825466f)
			{
				vector2 = objectForwardVector;
				if (MathF.Abs(Vector3.Dot(rotateAxis, vector2)) > 0.99825466f)
				{
					vector2 = ((MathF.Abs(rotateAxis.Z) > 0.99825466f) ? new Vector3(1f, 0f, 0f) : new Vector3(0f, 0f, -1f));
				}
				vector3 = Vector3.Normalize(Vector3.Cross(rotateAxis, vector2));
				vector2 = Vector3.Normalize(Vector3.Cross(vector3, rotateAxis));
			}
			else
			{
				vector3 = Vector3.Normalize(Vector3.Cross(rotateAxis, left));
				vector2 = Vector3.Normalize(Vector3.Cross(vector3, vector));
			}
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = vector3.X;
			result.M12 = vector3.Y;
			result.M13 = vector3.Z;
			result.M14 = 0f;
			result.M21 = vector.X;
			result.M22 = vector.Y;
			result.M23 = vector.Z;
			result.M24 = 0f;
			result.M31 = vector2.X;
			result.M32 = vector2.Y;
			result.M33 = vector2.Z;
			result.M34 = 0f;
			result.M41 = objectPosition.X;
			result.M42 = objectPosition.Y;
			result.M43 = objectPosition.Z;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateTranslation(Vector3 position)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 1f;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = 1f;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = 1f;
			result.M34 = 0f;
			result.M41 = position.X;
			result.M42 = position.Y;
			result.M43 = position.Z;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateTranslation(float xPosition, float yPosition, float zPosition)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 1f;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = 1f;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = 1f;
			result.M34 = 0f;
			result.M41 = xPosition;
			result.M42 = yPosition;
			result.M43 = zPosition;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateScale(float xScale, float yScale, float zScale)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = xScale;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = yScale;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = zScale;
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = 0f;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateScale(float xScale, float yScale, float zScale, Vector3 centerPoint)
		{
			float m = centerPoint.X * (1f - xScale);
			float m2 = centerPoint.Y * (1f - yScale);
			float m3 = centerPoint.Z * (1f - zScale);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = xScale;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = yScale;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = zScale;
			result.M34 = 0f;
			result.M41 = m;
			result.M42 = m2;
			result.M43 = m3;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateScale(Vector3 scales)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = scales.X;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = scales.Y;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = scales.Z;
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = 0f;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateScale(Vector3 scales, Vector3 centerPoint)
		{
			float m = centerPoint.X * (1f - scales.X);
			float m2 = centerPoint.Y * (1f - scales.Y);
			float m3 = centerPoint.Z * (1f - scales.Z);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = scales.X;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = scales.Y;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = scales.Z;
			result.M34 = 0f;
			result.M41 = m;
			result.M42 = m2;
			result.M43 = m3;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateScale(float scale)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = scale;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = scale;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = scale;
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = 0f;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateScale(float scale, Vector3 centerPoint)
		{
			float m = centerPoint.X * (1f - scale);
			float m2 = centerPoint.Y * (1f - scale);
			float m3 = centerPoint.Z * (1f - scale);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = scale;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = scale;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = scale;
			result.M34 = 0f;
			result.M41 = m;
			result.M42 = m2;
			result.M43 = m3;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateRotationX(float radians)
		{
			float num = MathF.Cos(radians);
			float num2 = MathF.Sin(radians);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 1f;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = num;
			result.M23 = num2;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f - num2;
			result.M33 = num;
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = 0f;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateRotationX(float radians, Vector3 centerPoint)
		{
			float num = MathF.Cos(radians);
			float num2 = MathF.Sin(radians);
			float m = centerPoint.Y * (1f - num) + centerPoint.Z * num2;
			float m2 = centerPoint.Z * (1f - num) - centerPoint.Y * num2;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 1f;
			result.M12 = 0f;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = num;
			result.M23 = num2;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f - num2;
			result.M33 = num;
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = m;
			result.M43 = m2;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateRotationY(float radians)
		{
			float num = MathF.Cos(radians);
			float num2 = MathF.Sin(radians);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = num;
			result.M12 = 0f;
			result.M13 = 0f - num2;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = 1f;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = num2;
			result.M32 = 0f;
			result.M33 = num;
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = 0f;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateRotationY(float radians, Vector3 centerPoint)
		{
			float num = MathF.Cos(radians);
			float num2 = MathF.Sin(radians);
			float m = centerPoint.X * (1f - num) - centerPoint.Z * num2;
			float m2 = centerPoint.Z * (1f - num) + centerPoint.X * num2;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = num;
			result.M12 = 0f;
			result.M13 = 0f - num2;
			result.M14 = 0f;
			result.M21 = 0f;
			result.M22 = 1f;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = num2;
			result.M32 = 0f;
			result.M33 = num;
			result.M34 = 0f;
			result.M41 = m;
			result.M42 = 0f;
			result.M43 = m2;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateRotationZ(float radians)
		{
			float num = MathF.Cos(radians);
			float num2 = MathF.Sin(radians);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = num;
			result.M12 = num2;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f - num2;
			result.M22 = num;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = 1f;
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = 0f;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateRotationZ(float radians, Vector3 centerPoint)
		{
			float num = MathF.Cos(radians);
			float num2 = MathF.Sin(radians);
			float m = centerPoint.X * (1f - num) + centerPoint.Y * num2;
			float m2 = centerPoint.Y * (1f - num) - centerPoint.X * num2;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = num;
			result.M12 = num2;
			result.M13 = 0f;
			result.M14 = 0f;
			result.M21 = 0f - num2;
			result.M22 = num;
			result.M23 = 0f;
			result.M24 = 0f;
			result.M31 = 0f;
			result.M32 = 0f;
			result.M33 = 1f;
			result.M34 = 0f;
			result.M41 = m;
			result.M42 = m2;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateFromAxisAngle(Vector3 axis, float angle)
		{
			float x = axis.X;
			float y = axis.Y;
			float z = axis.Z;
			float num = MathF.Sin(angle);
			float num2 = MathF.Cos(angle);
			float num3 = x * x;
			float num4 = y * y;
			float num5 = z * z;
			float num6 = x * y;
			float num7 = x * z;
			float num8 = y * z;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = num3 + num2 * (1f - num3);
			result.M12 = num6 - num2 * num6 + num * z;
			result.M13 = num7 - num2 * num7 - num * y;
			result.M14 = 0f;
			result.M21 = num6 - num2 * num6 - num * z;
			result.M22 = num4 + num2 * (1f - num4);
			result.M23 = num8 - num2 * num8 + num * x;
			result.M24 = 0f;
			result.M31 = num7 - num2 * num7 + num * y;
			result.M32 = num8 - num2 * num8 - num * x;
			result.M33 = num5 + num2 * (1f - num5);
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = 0f;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreatePerspectiveFieldOfView(float fieldOfView, float aspectRatio, float nearPlaneDistance, float farPlaneDistance)
		{
			if (fieldOfView <= 0f || fieldOfView >= (float)Math.PI)
			{
				throw new ArgumentOutOfRangeException("fieldOfView");
			}
			if (nearPlaneDistance <= 0f)
			{
				throw new ArgumentOutOfRangeException("nearPlaneDistance");
			}
			if (farPlaneDistance <= 0f)
			{
				throw new ArgumentOutOfRangeException("farPlaneDistance");
			}
			if (nearPlaneDistance >= farPlaneDistance)
			{
				throw new ArgumentOutOfRangeException("nearPlaneDistance");
			}
			float num = 1f / MathF.Tan(fieldOfView * 0.5f);
			float m = num / aspectRatio;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = m;
			result.M12 = (result.M13 = (result.M14 = 0f));
			result.M22 = num;
			result.M21 = (result.M23 = (result.M24 = 0f));
			result.M31 = (result.M32 = 0f);
			float num2 = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance))));
			result.M34 = -1f;
			result.M41 = (result.M42 = (result.M44 = 0f));
			result.M43 = nearPlaneDistance * num2;
			return result;
		}

		public static Matrix4x4 CreatePerspective(float width, float height, float nearPlaneDistance, float farPlaneDistance)
		{
			if (nearPlaneDistance <= 0f)
			{
				throw new ArgumentOutOfRangeException("nearPlaneDistance");
			}
			if (farPlaneDistance <= 0f)
			{
				throw new ArgumentOutOfRangeException("farPlaneDistance");
			}
			if (nearPlaneDistance >= farPlaneDistance)
			{
				throw new ArgumentOutOfRangeException("nearPlaneDistance");
			}
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 2f * nearPlaneDistance / width;
			result.M12 = (result.M13 = (result.M14 = 0f));
			result.M22 = 2f * nearPlaneDistance / height;
			result.M21 = (result.M23 = (result.M24 = 0f));
			float num = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance))));
			result.M31 = (result.M32 = 0f);
			result.M34 = -1f;
			result.M41 = (result.M42 = (result.M44 = 0f));
			result.M43 = nearPlaneDistance * num;
			return result;
		}

		public static Matrix4x4 CreatePerspectiveOffCenter(float left, float right, float bottom, float top, float nearPlaneDistance, float farPlaneDistance)
		{
			if (nearPlaneDistance <= 0f)
			{
				throw new ArgumentOutOfRangeException("nearPlaneDistance");
			}
			if (farPlaneDistance <= 0f)
			{
				throw new ArgumentOutOfRangeException("farPlaneDistance");
			}
			if (nearPlaneDistance >= farPlaneDistance)
			{
				throw new ArgumentOutOfRangeException("nearPlaneDistance");
			}
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 2f * nearPlaneDistance / (right - left);
			result.M12 = (result.M13 = (result.M14 = 0f));
			result.M22 = 2f * nearPlaneDistance / (top - bottom);
			result.M21 = (result.M23 = (result.M24 = 0f));
			result.M31 = (left + right) / (right - left);
			result.M32 = (top + bottom) / (top - bottom);
			float num = (result.M33 = (float.IsPositiveInfinity(farPlaneDistance) ? (-1f) : (farPlaneDistance / (nearPlaneDistance - farPlaneDistance))));
			result.M34 = -1f;
			result.M43 = nearPlaneDistance * num;
			result.M41 = (result.M42 = (result.M44 = 0f));
			return result;
		}

		public static Matrix4x4 CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 2f / width;
			result.M12 = (result.M13 = (result.M14 = 0f));
			result.M22 = 2f / height;
			result.M21 = (result.M23 = (result.M24 = 0f));
			result.M33 = 1f / (zNearPlane - zFarPlane);
			result.M31 = (result.M32 = (result.M34 = 0f));
			result.M41 = (result.M42 = 0f);
			result.M43 = zNearPlane / (zNearPlane - zFarPlane);
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateOrthographicOffCenter(float left, float right, float bottom, float top, float zNearPlane, float zFarPlane)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 2f / (right - left);
			result.M12 = (result.M13 = (result.M14 = 0f));
			result.M22 = 2f / (top - bottom);
			result.M21 = (result.M23 = (result.M24 = 0f));
			result.M33 = 1f / (zNearPlane - zFarPlane);
			result.M31 = (result.M32 = (result.M34 = 0f));
			result.M41 = (left + right) / (left - right);
			result.M42 = (top + bottom) / (bottom - top);
			result.M43 = zNearPlane / (zNearPlane - zFarPlane);
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateLookAt(Vector3 cameraPosition, Vector3 cameraTarget, Vector3 cameraUpVector)
		{
			Vector3 vector = Vector3.Normalize(cameraPosition - cameraTarget);
			Vector3 vector2 = Vector3.Normalize(Vector3.Cross(cameraUpVector, vector));
			Vector3 vector3 = Vector3.Cross(vector, vector2);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = vector2.X;
			result.M12 = vector3.X;
			result.M13 = vector.X;
			result.M14 = 0f;
			result.M21 = vector2.Y;
			result.M22 = vector3.Y;
			result.M23 = vector.Y;
			result.M24 = 0f;
			result.M31 = vector2.Z;
			result.M32 = vector3.Z;
			result.M33 = vector.Z;
			result.M34 = 0f;
			result.M41 = 0f - Vector3.Dot(vector2, cameraPosition);
			result.M42 = 0f - Vector3.Dot(vector3, cameraPosition);
			result.M43 = 0f - Vector3.Dot(vector, cameraPosition);
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateWorld(Vector3 position, Vector3 forward, Vector3 up)
		{
			Vector3 vector = Vector3.Normalize(-forward);
			Vector3 vector2 = Vector3.Normalize(Vector3.Cross(up, vector));
			Vector3 vector3 = Vector3.Cross(vector, vector2);
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = vector2.X;
			result.M12 = vector2.Y;
			result.M13 = vector2.Z;
			result.M14 = 0f;
			result.M21 = vector3.X;
			result.M22 = vector3.Y;
			result.M23 = vector3.Z;
			result.M24 = 0f;
			result.M31 = vector.X;
			result.M32 = vector.Y;
			result.M33 = vector.Z;
			result.M34 = 0f;
			result.M41 = position.X;
			result.M42 = position.Y;
			result.M43 = position.Z;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateFromQuaternion(Quaternion quaternion)
		{
			float num = quaternion.X * quaternion.X;
			float num2 = quaternion.Y * quaternion.Y;
			float num3 = quaternion.Z * quaternion.Z;
			float num4 = quaternion.X * quaternion.Y;
			float num5 = quaternion.Z * quaternion.W;
			float num6 = quaternion.Z * quaternion.X;
			float num7 = quaternion.Y * quaternion.W;
			float num8 = quaternion.Y * quaternion.Z;
			float num9 = quaternion.X * quaternion.W;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 1f - 2f * (num2 + num3);
			result.M12 = 2f * (num4 + num5);
			result.M13 = 2f * (num6 - num7);
			result.M14 = 0f;
			result.M21 = 2f * (num4 - num5);
			result.M22 = 1f - 2f * (num3 + num);
			result.M23 = 2f * (num8 + num9);
			result.M24 = 0f;
			result.M31 = 2f * (num6 + num7);
			result.M32 = 2f * (num8 - num9);
			result.M33 = 1f - 2f * (num2 + num);
			result.M34 = 0f;
			result.M41 = 0f;
			result.M42 = 0f;
			result.M43 = 0f;
			result.M44 = 1f;
			return result;
		}

		public static Matrix4x4 CreateFromYawPitchRoll(float yaw, float pitch, float roll)
		{
			return CreateFromQuaternion(Quaternion.CreateFromYawPitchRoll(yaw, pitch, roll));
		}

		public static Matrix4x4 CreateShadow(Vector3 lightDirection, Plane plane)
		{
			Plane plane2 = Plane.Normalize(plane);
			float num = plane2.Normal.X * lightDirection.X + plane2.Normal.Y * lightDirection.Y + plane2.Normal.Z * lightDirection.Z;
			float num2 = 0f - plane2.Normal.X;
			float num3 = 0f - plane2.Normal.Y;
			float num4 = 0f - plane2.Normal.Z;
			float num5 = 0f - plane2.D;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = num2 * lightDirection.X + num;
			result.M21 = num3 * lightDirection.X;
			result.M31 = num4 * lightDirection.X;
			result.M41 = num5 * lightDirection.X;
			result.M12 = num2 * lightDirection.Y;
			result.M22 = num3 * lightDirection.Y + num;
			result.M32 = num4 * lightDirection.Y;
			result.M42 = num5 * lightDirection.Y;
			result.M13 = num2 * lightDirection.Z;
			result.M23 = num3 * lightDirection.Z;
			result.M33 = num4 * lightDirection.Z + num;
			result.M43 = num5 * lightDirection.Z;
			result.M14 = 0f;
			result.M24 = 0f;
			result.M34 = 0f;
			result.M44 = num;
			return result;
		}

		public static Matrix4x4 CreateReflection(Plane value)
		{
			value = Plane.Normalize(value);
			float x = value.Normal.X;
			float y = value.Normal.Y;
			float z = value.Normal.Z;
			float num = -2f * x;
			float num2 = -2f * y;
			float num3 = -2f * z;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = num * x + 1f;
			result.M12 = num2 * x;
			result.M13 = num3 * x;
			result.M14 = 0f;
			result.M21 = num * y;
			result.M22 = num2 * y + 1f;
			result.M23 = num3 * y;
			result.M24 = 0f;
			result.M31 = num * z;
			result.M32 = num2 * z;
			result.M33 = num3 * z + 1f;
			result.M34 = 0f;
			result.M41 = num * value.D;
			result.M42 = num2 * value.D;
			result.M43 = num3 * value.D;
			result.M44 = 1f;
			return result;
		}

		public float GetDeterminant()
		{
			float m = M11;
			float m2 = M12;
			float m3 = M13;
			float m4 = M14;
			float m5 = M21;
			float m6 = M22;
			float m7 = M23;
			float m8 = M24;
			float m9 = M31;
			float m10 = M32;
			float m11 = M33;
			float m12 = M34;
			float m13 = M41;
			float m14 = M42;
			float m15 = M43;
			float m16 = M44;
			float num = m11 * m16 - m12 * m15;
			float num2 = m10 * m16 - m12 * m14;
			float num3 = m10 * m15 - m11 * m14;
			float num4 = m9 * m16 - m12 * m13;
			float num5 = m9 * m15 - m11 * m13;
			float num6 = m9 * m14 - m10 * m13;
			return m * (m6 * num - m7 * num2 + m8 * num3) - m2 * (m5 * num - m7 * num4 + m8 * num5) + m3 * (m5 * num2 - m6 * num4 + m8 * num6) - m4 * (m5 * num3 - m6 * num5 + m7 * num6);
		}

		public static bool Invert(Matrix4x4 matrix, out Matrix4x4 result)
		{
			float m = matrix.M11;
			float m2 = matrix.M12;
			float m3 = matrix.M13;
			float m4 = matrix.M14;
			float m5 = matrix.M21;
			float m6 = matrix.M22;
			float m7 = matrix.M23;
			float m8 = matrix.M24;
			float m9 = matrix.M31;
			float m10 = matrix.M32;
			float m11 = matrix.M33;
			float m12 = matrix.M34;
			float m13 = matrix.M41;
			float m14 = matrix.M42;
			float m15 = matrix.M43;
			float m16 = matrix.M44;
			float num = m11 * m16 - m12 * m15;
			float num2 = m10 * m16 - m12 * m14;
			float num3 = m10 * m15 - m11 * m14;
			float num4 = m9 * m16 - m12 * m13;
			float num5 = m9 * m15 - m11 * m13;
			float num6 = m9 * m14 - m10 * m13;
			float num7 = m6 * num - m7 * num2 + m8 * num3;
			float num8 = 0f - (m5 * num - m7 * num4 + m8 * num5);
			float num9 = m5 * num2 - m6 * num4 + m8 * num6;
			float num10 = 0f - (m5 * num3 - m6 * num5 + m7 * num6);
			float num11 = m * num7 + m2 * num8 + m3 * num9 + m4 * num10;
			if (MathF.Abs(num11) < float.Epsilon)
			{
				result = new Matrix4x4(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN, float.NaN);
				return false;
			}
			float num12 = 1f / num11;
			result.M11 = num7 * num12;
			result.M21 = num8 * num12;
			result.M31 = num9 * num12;
			result.M41 = num10 * num12;
			result.M12 = (0f - (m2 * num - m3 * num2 + m4 * num3)) * num12;
			result.M22 = (m * num - m3 * num4 + m4 * num5) * num12;
			result.M32 = (0f - (m * num2 - m2 * num4 + m4 * num6)) * num12;
			result.M42 = (m * num3 - m2 * num5 + m3 * num6) * num12;
			float num13 = m7 * m16 - m8 * m15;
			float num14 = m6 * m16 - m8 * m14;
			float num15 = m6 * m15 - m7 * m14;
			float num16 = m5 * m16 - m8 * m13;
			float num17 = m5 * m15 - m7 * m13;
			float num18 = m5 * m14 - m6 * m13;
			result.M13 = (m2 * num13 - m3 * num14 + m4 * num15) * num12;
			result.M23 = (0f - (m * num13 - m3 * num16 + m4 * num17)) * num12;
			result.M33 = (m * num14 - m2 * num16 + m4 * num18) * num12;
			result.M43 = (0f - (m * num15 - m2 * num17 + m3 * num18)) * num12;
			float num19 = m7 * m12 - m8 * m11;
			float num20 = m6 * m12 - m8 * m10;
			float num21 = m6 * m11 - m7 * m10;
			float num22 = m5 * m12 - m8 * m9;
			float num23 = m5 * m11 - m7 * m9;
			float num24 = m5 * m10 - m6 * m9;
			result.M14 = (0f - (m2 * num19 - m3 * num20 + m4 * num21)) * num12;
			result.M24 = (m * num19 - m3 * num22 + m4 * num23) * num12;
			result.M34 = (0f - (m * num20 - m2 * num22 + m4 * num24)) * num12;
			result.M44 = (m * num21 - m2 * num23 + m3 * num24) * num12;
			return true;
		}

		public unsafe static bool Decompose(Matrix4x4 matrix, out Vector3 scale, out Quaternion rotation, out Vector3 translation)
		{
			bool result = true;
			fixed (Vector3* ptr = &scale)
			{
				float* ptr2 = (float*)ptr;
				VectorBasis vectorBasis = default(VectorBasis);
				Vector3** ptr3 = (Vector3**)(&vectorBasis);
				Matrix4x4 identity = Identity;
				CanonicalBasis canonicalBasis = default(CanonicalBasis);
				Vector3* ptr4 = &canonicalBasis.Row0;
				canonicalBasis.Row0 = new Vector3(1f, 0f, 0f);
				canonicalBasis.Row1 = new Vector3(0f, 1f, 0f);
				canonicalBasis.Row2 = new Vector3(0f, 0f, 1f);
				translation = new Vector3(matrix.M41, matrix.M42, matrix.M43);
				*ptr3 = (Vector3*)(&identity.M11);
				ptr3[1] = (Vector3*)(&identity.M21);
				ptr3[2] = (Vector3*)(&identity.M31);
				*(*ptr3) = new Vector3(matrix.M11, matrix.M12, matrix.M13);
				*ptr3[1] = new Vector3(matrix.M21, matrix.M22, matrix.M23);
				*ptr3[2] = new Vector3(matrix.M31, matrix.M32, matrix.M33);
				scale.X = (*ptr3)->Length();
				scale.Y = ptr3[1]->Length();
				scale.Z = ptr3[2]->Length();
				float num = *ptr2;
				float num2 = ptr2[1];
				float num3 = ptr2[2];
				uint num4;
				uint num5;
				uint num6;
				if (num < num2)
				{
					if (num2 < num3)
					{
						num4 = 2u;
						num5 = 1u;
						num6 = 0u;
					}
					else
					{
						num4 = 1u;
						if (num < num3)
						{
							num5 = 2u;
							num6 = 0u;
						}
						else
						{
							num5 = 0u;
							num6 = 2u;
						}
					}
				}
				else if (num < num3)
				{
					num4 = 2u;
					num5 = 0u;
					num6 = 1u;
				}
				else
				{
					num4 = 0u;
					if (num2 < num3)
					{
						num5 = 2u;
						num6 = 1u;
					}
					else
					{
						num5 = 1u;
						num6 = 2u;
					}
				}
				if (ptr2[num4] < 0.0001f)
				{
					*ptr3[num4] = ptr4[num4];
				}
				*ptr3[num4] = Vector3.Normalize(*ptr3[num4]);
				if (ptr2[num5] < 0.0001f)
				{
					float num7 = MathF.Abs(ptr3[num4]->X);
					float num8 = MathF.Abs(ptr3[num4]->Y);
					float num9 = MathF.Abs(ptr3[num4]->Z);
					uint num10 = ((num7 < num8) ? ((!(num8 < num9)) ? ((!(num7 < num9)) ? 2u : 0u) : 0u) : ((num7 < num9) ? 1u : ((num8 < num9) ? 1u : 2u)));
					*ptr3[num5] = Vector3.Cross(*ptr3[num4], ptr4[num10]);
				}
				*ptr3[num5] = Vector3.Normalize(*ptr3[num5]);
				if (ptr2[num6] < 0.0001f)
				{
					*ptr3[num6] = Vector3.Cross(*ptr3[num4], *ptr3[num5]);
				}
				*ptr3[num6] = Vector3.Normalize(*ptr3[num6]);
				float num11 = identity.GetDeterminant();
				if (num11 < 0f)
				{
					ptr2[num4] = 0f - ptr2[num4];
					*ptr3[num4] = -(*ptr3[num4]);
					num11 = 0f - num11;
				}
				num11 -= 1f;
				num11 *= num11;
				if (0.0001f < num11)
				{
					rotation = Quaternion.Identity;
					result = false;
				}
				else
				{
					rotation = Quaternion.CreateFromRotationMatrix(identity);
				}
			}
			return result;
		}

		public static Matrix4x4 Transform(Matrix4x4 value, Quaternion rotation)
		{
			float num = rotation.X + rotation.X;
			float num2 = rotation.Y + rotation.Y;
			float num3 = rotation.Z + rotation.Z;
			float num4 = rotation.W * num;
			float num5 = rotation.W * num2;
			float num6 = rotation.W * num3;
			float num7 = rotation.X * num;
			float num8 = rotation.X * num2;
			float num9 = rotation.X * num3;
			float num10 = rotation.Y * num2;
			float num11 = rotation.Y * num3;
			float num12 = rotation.Z * num3;
			float num13 = 1f - num10 - num12;
			float num14 = num8 - num6;
			float num15 = num9 + num5;
			float num16 = num8 + num6;
			float num17 = 1f - num7 - num12;
			float num18 = num11 - num4;
			float num19 = num9 - num5;
			float num20 = num11 + num4;
			float num21 = 1f - num7 - num10;
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value.M11 * num13 + value.M12 * num14 + value.M13 * num15;
			result.M12 = value.M11 * num16 + value.M12 * num17 + value.M13 * num18;
			result.M13 = value.M11 * num19 + value.M12 * num20 + value.M13 * num21;
			result.M14 = value.M14;
			result.M21 = value.M21 * num13 + value.M22 * num14 + value.M23 * num15;
			result.M22 = value.M21 * num16 + value.M22 * num17 + value.M23 * num18;
			result.M23 = value.M21 * num19 + value.M22 * num20 + value.M23 * num21;
			result.M24 = value.M24;
			result.M31 = value.M31 * num13 + value.M32 * num14 + value.M33 * num15;
			result.M32 = value.M31 * num16 + value.M32 * num17 + value.M33 * num18;
			result.M33 = value.M31 * num19 + value.M32 * num20 + value.M33 * num21;
			result.M34 = value.M34;
			result.M41 = value.M41 * num13 + value.M42 * num14 + value.M43 * num15;
			result.M42 = value.M41 * num16 + value.M42 * num17 + value.M43 * num18;
			result.M43 = value.M41 * num19 + value.M42 * num20 + value.M43 * num21;
			result.M44 = value.M44;
			return result;
		}

		public static Matrix4x4 Transpose(Matrix4x4 matrix)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = matrix.M11;
			result.M12 = matrix.M21;
			result.M13 = matrix.M31;
			result.M14 = matrix.M41;
			result.M21 = matrix.M12;
			result.M22 = matrix.M22;
			result.M23 = matrix.M32;
			result.M24 = matrix.M42;
			result.M31 = matrix.M13;
			result.M32 = matrix.M23;
			result.M33 = matrix.M33;
			result.M34 = matrix.M43;
			result.M41 = matrix.M14;
			result.M42 = matrix.M24;
			result.M43 = matrix.M34;
			result.M44 = matrix.M44;
			return result;
		}

		public static Matrix4x4 Lerp(Matrix4x4 matrix1, Matrix4x4 matrix2, float amount)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount;
			result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount;
			result.M13 = matrix1.M13 + (matrix2.M13 - matrix1.M13) * amount;
			result.M14 = matrix1.M14 + (matrix2.M14 - matrix1.M14) * amount;
			result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount;
			result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount;
			result.M23 = matrix1.M23 + (matrix2.M23 - matrix1.M23) * amount;
			result.M24 = matrix1.M24 + (matrix2.M24 - matrix1.M24) * amount;
			result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount;
			result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount;
			result.M33 = matrix1.M33 + (matrix2.M33 - matrix1.M33) * amount;
			result.M34 = matrix1.M34 + (matrix2.M34 - matrix1.M34) * amount;
			result.M41 = matrix1.M41 + (matrix2.M41 - matrix1.M41) * amount;
			result.M42 = matrix1.M42 + (matrix2.M42 - matrix1.M42) * amount;
			result.M43 = matrix1.M43 + (matrix2.M43 - matrix1.M43) * amount;
			result.M44 = matrix1.M44 + (matrix2.M44 - matrix1.M44) * amount;
			return result;
		}

		public static Matrix4x4 Negate(Matrix4x4 value)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 0f - value.M11;
			result.M12 = 0f - value.M12;
			result.M13 = 0f - value.M13;
			result.M14 = 0f - value.M14;
			result.M21 = 0f - value.M21;
			result.M22 = 0f - value.M22;
			result.M23 = 0f - value.M23;
			result.M24 = 0f - value.M24;
			result.M31 = 0f - value.M31;
			result.M32 = 0f - value.M32;
			result.M33 = 0f - value.M33;
			result.M34 = 0f - value.M34;
			result.M41 = 0f - value.M41;
			result.M42 = 0f - value.M42;
			result.M43 = 0f - value.M43;
			result.M44 = 0f - value.M44;
			return result;
		}

		public static Matrix4x4 Add(Matrix4x4 value1, Matrix4x4 value2)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value1.M11 + value2.M11;
			result.M12 = value1.M12 + value2.M12;
			result.M13 = value1.M13 + value2.M13;
			result.M14 = value1.M14 + value2.M14;
			result.M21 = value1.M21 + value2.M21;
			result.M22 = value1.M22 + value2.M22;
			result.M23 = value1.M23 + value2.M23;
			result.M24 = value1.M24 + value2.M24;
			result.M31 = value1.M31 + value2.M31;
			result.M32 = value1.M32 + value2.M32;
			result.M33 = value1.M33 + value2.M33;
			result.M34 = value1.M34 + value2.M34;
			result.M41 = value1.M41 + value2.M41;
			result.M42 = value1.M42 + value2.M42;
			result.M43 = value1.M43 + value2.M43;
			result.M44 = value1.M44 + value2.M44;
			return result;
		}

		public static Matrix4x4 Subtract(Matrix4x4 value1, Matrix4x4 value2)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value1.M11 - value2.M11;
			result.M12 = value1.M12 - value2.M12;
			result.M13 = value1.M13 - value2.M13;
			result.M14 = value1.M14 - value2.M14;
			result.M21 = value1.M21 - value2.M21;
			result.M22 = value1.M22 - value2.M22;
			result.M23 = value1.M23 - value2.M23;
			result.M24 = value1.M24 - value2.M24;
			result.M31 = value1.M31 - value2.M31;
			result.M32 = value1.M32 - value2.M32;
			result.M33 = value1.M33 - value2.M33;
			result.M34 = value1.M34 - value2.M34;
			result.M41 = value1.M41 - value2.M41;
			result.M42 = value1.M42 - value2.M42;
			result.M43 = value1.M43 - value2.M43;
			result.M44 = value1.M44 - value2.M44;
			return result;
		}

		public static Matrix4x4 Multiply(Matrix4x4 value1, Matrix4x4 value2)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21 + value1.M13 * value2.M31 + value1.M14 * value2.M41;
			result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22 + value1.M13 * value2.M32 + value1.M14 * value2.M42;
			result.M13 = value1.M11 * value2.M13 + value1.M12 * value2.M23 + value1.M13 * value2.M33 + value1.M14 * value2.M43;
			result.M14 = value1.M11 * value2.M14 + value1.M12 * value2.M24 + value1.M13 * value2.M34 + value1.M14 * value2.M44;
			result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21 + value1.M23 * value2.M31 + value1.M24 * value2.M41;
			result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22 + value1.M23 * value2.M32 + value1.M24 * value2.M42;
			result.M23 = value1.M21 * value2.M13 + value1.M22 * value2.M23 + value1.M23 * value2.M33 + value1.M24 * value2.M43;
			result.M24 = value1.M21 * value2.M14 + value1.M22 * value2.M24 + value1.M23 * value2.M34 + value1.M24 * value2.M44;
			result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value1.M33 * value2.M31 + value1.M34 * value2.M41;
			result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value1.M33 * value2.M32 + value1.M34 * value2.M42;
			result.M33 = value1.M31 * value2.M13 + value1.M32 * value2.M23 + value1.M33 * value2.M33 + value1.M34 * value2.M43;
			result.M34 = value1.M31 * value2.M14 + value1.M32 * value2.M24 + value1.M33 * value2.M34 + value1.M34 * value2.M44;
			result.M41 = value1.M41 * value2.M11 + value1.M42 * value2.M21 + value1.M43 * value2.M31 + value1.M44 * value2.M41;
			result.M42 = value1.M41 * value2.M12 + value1.M42 * value2.M22 + value1.M43 * value2.M32 + value1.M44 * value2.M42;
			result.M43 = value1.M41 * value2.M13 + value1.M42 * value2.M23 + value1.M43 * value2.M33 + value1.M44 * value2.M43;
			result.M44 = value1.M41 * value2.M14 + value1.M42 * value2.M24 + value1.M43 * value2.M34 + value1.M44 * value2.M44;
			return result;
		}

		public static Matrix4x4 Multiply(Matrix4x4 value1, float value2)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value1.M11 * value2;
			result.M12 = value1.M12 * value2;
			result.M13 = value1.M13 * value2;
			result.M14 = value1.M14 * value2;
			result.M21 = value1.M21 * value2;
			result.M22 = value1.M22 * value2;
			result.M23 = value1.M23 * value2;
			result.M24 = value1.M24 * value2;
			result.M31 = value1.M31 * value2;
			result.M32 = value1.M32 * value2;
			result.M33 = value1.M33 * value2;
			result.M34 = value1.M34 * value2;
			result.M41 = value1.M41 * value2;
			result.M42 = value1.M42 * value2;
			result.M43 = value1.M43 * value2;
			result.M44 = value1.M44 * value2;
			return result;
		}

		public static Matrix4x4 operator -(Matrix4x4 value)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = 0f - value.M11;
			result.M12 = 0f - value.M12;
			result.M13 = 0f - value.M13;
			result.M14 = 0f - value.M14;
			result.M21 = 0f - value.M21;
			result.M22 = 0f - value.M22;
			result.M23 = 0f - value.M23;
			result.M24 = 0f - value.M24;
			result.M31 = 0f - value.M31;
			result.M32 = 0f - value.M32;
			result.M33 = 0f - value.M33;
			result.M34 = 0f - value.M34;
			result.M41 = 0f - value.M41;
			result.M42 = 0f - value.M42;
			result.M43 = 0f - value.M43;
			result.M44 = 0f - value.M44;
			return result;
		}

		public static Matrix4x4 operator +(Matrix4x4 value1, Matrix4x4 value2)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value1.M11 + value2.M11;
			result.M12 = value1.M12 + value2.M12;
			result.M13 = value1.M13 + value2.M13;
			result.M14 = value1.M14 + value2.M14;
			result.M21 = value1.M21 + value2.M21;
			result.M22 = value1.M22 + value2.M22;
			result.M23 = value1.M23 + value2.M23;
			result.M24 = value1.M24 + value2.M24;
			result.M31 = value1.M31 + value2.M31;
			result.M32 = value1.M32 + value2.M32;
			result.M33 = value1.M33 + value2.M33;
			result.M34 = value1.M34 + value2.M34;
			result.M41 = value1.M41 + value2.M41;
			result.M42 = value1.M42 + value2.M42;
			result.M43 = value1.M43 + value2.M43;
			result.M44 = value1.M44 + value2.M44;
			return result;
		}

		public static Matrix4x4 operator -(Matrix4x4 value1, Matrix4x4 value2)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value1.M11 - value2.M11;
			result.M12 = value1.M12 - value2.M12;
			result.M13 = value1.M13 - value2.M13;
			result.M14 = value1.M14 - value2.M14;
			result.M21 = value1.M21 - value2.M21;
			result.M22 = value1.M22 - value2.M22;
			result.M23 = value1.M23 - value2.M23;
			result.M24 = value1.M24 - value2.M24;
			result.M31 = value1.M31 - value2.M31;
			result.M32 = value1.M32 - value2.M32;
			result.M33 = value1.M33 - value2.M33;
			result.M34 = value1.M34 - value2.M34;
			result.M41 = value1.M41 - value2.M41;
			result.M42 = value1.M42 - value2.M42;
			result.M43 = value1.M43 - value2.M43;
			result.M44 = value1.M44 - value2.M44;
			return result;
		}

		public static Matrix4x4 operator *(Matrix4x4 value1, Matrix4x4 value2)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21 + value1.M13 * value2.M31 + value1.M14 * value2.M41;
			result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22 + value1.M13 * value2.M32 + value1.M14 * value2.M42;
			result.M13 = value1.M11 * value2.M13 + value1.M12 * value2.M23 + value1.M13 * value2.M33 + value1.M14 * value2.M43;
			result.M14 = value1.M11 * value2.M14 + value1.M12 * value2.M24 + value1.M13 * value2.M34 + value1.M14 * value2.M44;
			result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21 + value1.M23 * value2.M31 + value1.M24 * value2.M41;
			result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22 + value1.M23 * value2.M32 + value1.M24 * value2.M42;
			result.M23 = value1.M21 * value2.M13 + value1.M22 * value2.M23 + value1.M23 * value2.M33 + value1.M24 * value2.M43;
			result.M24 = value1.M21 * value2.M14 + value1.M22 * value2.M24 + value1.M23 * value2.M34 + value1.M24 * value2.M44;
			result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value1.M33 * value2.M31 + value1.M34 * value2.M41;
			result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value1.M33 * value2.M32 + value1.M34 * value2.M42;
			result.M33 = value1.M31 * value2.M13 + value1.M32 * value2.M23 + value1.M33 * value2.M33 + value1.M34 * value2.M43;
			result.M34 = value1.M31 * value2.M14 + value1.M32 * value2.M24 + value1.M33 * value2.M34 + value1.M34 * value2.M44;
			result.M41 = value1.M41 * value2.M11 + value1.M42 * value2.M21 + value1.M43 * value2.M31 + value1.M44 * value2.M41;
			result.M42 = value1.M41 * value2.M12 + value1.M42 * value2.M22 + value1.M43 * value2.M32 + value1.M44 * value2.M42;
			result.M43 = value1.M41 * value2.M13 + value1.M42 * value2.M23 + value1.M43 * value2.M33 + value1.M44 * value2.M43;
			result.M44 = value1.M41 * value2.M14 + value1.M42 * value2.M24 + value1.M43 * value2.M34 + value1.M44 * value2.M44;
			return result;
		}

		public static Matrix4x4 operator *(Matrix4x4 value1, float value2)
		{
			Matrix4x4 result = default(Matrix4x4);
			result.M11 = value1.M11 * value2;
			result.M12 = value1.M12 * value2;
			result.M13 = value1.M13 * value2;
			result.M14 = value1.M14 * value2;
			result.M21 = value1.M21 * value2;
			result.M22 = value1.M22 * value2;
			result.M23 = value1.M23 * value2;
			result.M24 = value1.M24 * value2;
			result.M31 = value1.M31 * value2;
			result.M32 = value1.M32 * value2;
			result.M33 = value1.M33 * value2;
			result.M34 = value1.M34 * value2;
			result.M41 = value1.M41 * value2;
			result.M42 = value1.M42 * value2;
			result.M43 = value1.M43 * value2;
			result.M44 = value1.M44 * value2;
			return result;
		}

		public static bool operator ==(Matrix4x4 value1, Matrix4x4 value2)
		{
			if (value1.M11 == value2.M11 && value1.M22 == value2.M22 && value1.M33 == value2.M33 && value1.M44 == value2.M44 && value1.M12 == value2.M12 && value1.M13 == value2.M13 && value1.M14 == value2.M14 && value1.M21 == value2.M21 && value1.M23 == value2.M23 && value1.M24 == value2.M24 && value1.M31 == value2.M31 && value1.M32 == value2.M32 && value1.M34 == value2.M34 && value1.M41 == value2.M41 && value1.M42 == value2.M42)
			{
				return value1.M43 == value2.M43;
			}
			return false;
		}

		public static bool operator !=(Matrix4x4 value1, Matrix4x4 value2)
		{
			if (value1.M11 == value2.M11 && value1.M12 == value2.M12 && value1.M13 == value2.M13 && value1.M14 == value2.M14 && value1.M21 == value2.M21 && value1.M22 == value2.M22 && value1.M23 == value2.M23 && value1.M24 == value2.M24 && value1.M31 == value2.M31 && value1.M32 == value2.M32 && value1.M33 == value2.M33 && value1.M34 == value2.M34 && value1.M41 == value2.M41 && value1.M42 == value2.M42 && value1.M43 == value2.M43)
			{
				return value1.M44 != value2.M44;
			}
			return true;
		}

		public bool Equals(Matrix4x4 other)
		{
			if (M11 == other.M11 && M22 == other.M22 && M33 == other.M33 && M44 == other.M44 && M12 == other.M12 && M13 == other.M13 && M14 == other.M14 && M21 == other.M21 && M23 == other.M23 && M24 == other.M24 && M31 == other.M31 && M32 == other.M32 && M34 == other.M34 && M41 == other.M41 && M42 == other.M42)
			{
				return M43 == other.M43;
			}
			return false;
		}

		public override bool Equals(object obj)
		{
			if (obj is Matrix4x4)
			{
				return Equals((Matrix4x4)obj);
			}
			return false;
		}

		public override string ToString()
		{
			CultureInfo currentCulture = CultureInfo.CurrentCulture;
			return string.Format(currentCulture, "{{ {{M11:{0} M12:{1} M13:{2} M14:{3}}} {{M21:{4} M22:{5} M23:{6} M24:{7}}} {{M31:{8} M32:{9} M33:{10} M34:{11}}} {{M41:{12} M42:{13} M43:{14} M44:{15}}} }}", M11.ToString(currentCulture), M12.ToString(currentCulture), M13.ToString(currentCulture), M14.ToString(currentCulture), M21.ToString(currentCulture), M22.ToString(currentCulture), M23.ToString(currentCulture), M24.ToString(currentCulture), M31.ToString(currentCulture), M32.ToString(currentCulture), M33.ToString(currentCulture), M34.ToString(currentCulture), M41.ToString(currentCulture), M42.ToString(currentCulture), M43.ToString(currentCulture), M44.ToString(currentCulture));
		}

		public override int GetHashCode()
		{
			return M11.GetHashCode() + M12.GetHashCode() + M13.GetHashCode() + M14.GetHashCode() + M21.GetHashCode() + M22.GetHashCode() + M23.GetHashCode() + M24.GetHashCode() + M31.GetHashCode() + M32.GetHashCode() + M33.GetHashCode() + M34.GetHashCode() + M41.GetHashCode() + M42.GetHashCode() + M43.GetHashCode() + M44.GetHashCode();
		}
	}
	public struct Plane : IEquatable<Plane>
	{
		public Vector3 Normal;

		public float D;

		public Plane(float x, float y, float z, float d)
		{
			Normal = new Vector3(x, y, z);
			D = d;
		}

		public Plane(Vector3 normal, float d)
		{
			Normal = normal;
			D = d;
		}

		public Plane(Vector4 value)
		{
			Normal = new Vector3(value.X, value.Y, value.Z);
			D = value.W;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Plane CreateFromVertices(Vector3 point1, Vector3 point2, Vector3 point3)
		{
			if (Vector.IsHardwareAccelerated)
			{
				Vector3 vector = point2 - point1;
				Vector3 vector2 = point3 - point1;
				Vector3 vector3 = Vector3.Normalize(Vector3.Cross(vector, vector2));
				float d = 0f - Vector3.Dot(vector3, point1);
				return new Plane(vector3, d);
			}
			float num = point2.X - point1.X;
			float num2 = point2.Y - point1.Y;
			float num3 = point2.Z - point1.Z;
			float num4 = point3.X - point1.X;
			float num5 = point3.Y - point1.Y;
			float num6 = point3.Z - point1.Z;
			float num7 = num2 * num6 - num3 * num5;
			float num8 = num3 * num4 - num * num6;
			float num9 = num * num5 - num2 * num4;
			float num10 = num7 * num7 + num8 * num8 + num9 * num9;
			float num11 = 1f / MathF.Sqrt(num10);
			Vector3 normal = new Vector3(num7 * num11, num8 * num11, num9 * num11);
			return new Plane(normal, 0f - (normal.X * point1.X + normal.Y * point1.Y + normal.Z * point1.Z));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Plane Normalize(Plane value)
		{
			if (Vector.IsHardwareAccelerated)
			{
				float num = value.Normal.LengthSquared();
				if (MathF.Abs(num - 1f) < 1.1920929E-07f)
				{
					return value;
				}
				float num2 = MathF.Sqrt(num);
				return new Plane(value.Normal / num2, value.D / num2);
			}
			float num3 = value.Normal.X * value.Normal.X + value.Normal.Y * value.Normal.Y + value.Normal.Z * value.Normal.Z;
			if (MathF.Abs(num3 - 1f) < 1.1920929E-07f)
			{
				return value;
			}
			float num4 = 1f / MathF.Sqrt(num3);
			return new Plane(value.Normal.X * num4, value.Normal.Y * num4, value.Normal.Z * num4, value.D * num4);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Plane Transform(Plane plane, Matrix4x4 matrix)
		{
			Matrix4x4.Invert(matrix, out var result);
			float x = plane.Normal.X;
			float y = plane.Normal.Y;
			float z = plane.Normal.Z;
			float d = plane.D;
			return new Plane(x * result.M11 + y * result.M12 + z * result.M13 + d * result.M14, x * result.M21 + y * result.M22 + z * result.M23 + d * result.M24, x * result.M31 + y * result.M32 + z * result.M33 + d * result.M34, x * result.M41 + y * result.M42 + z * result.M43 + d * result.M44);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Plane Transform(Plane plane, Quaternion rotation)
		{
			float num = rotation.X + rotation.X;
			float num2 = rotation.Y + rotation.Y;
			float num3 = rotation.Z + rotation.Z;
			float num4 = rotation.W * num;
			float num5 = rotation.W * num2;
			float num6 = rotation.W * num3;
			float num7 = rotation.X * num;
			float num8 = rotation.X * num2;
			float num9 = rotation.X * num3;
			float num10 = rotation.Y * num2;
			float num11 = rotation.Y * num3;
			float num12 = rotation.Z * num3;
			float num13 = 1f - num10 - num12;
			float num14 = num8 - num6;
			float num15 = num9 + num5;
			float num16 = num8 + num6;
			float num17 = 1f - num7 - num12;
			float num18 = num11 - num4;
			float num19 = num9 - num5;
			float num20 = num11 + num4;
			float num21 = 1f - num7 - num10;
			float x = plane.Normal.X;
			float y = plane.Normal.Y;
			float z = plane.Normal.Z;
			return new Plane(x * num13 + y * num14 + z * num15, x * num16 + y * num17 + z * num18, x * num19 + y * num20 + z * num21, plane.D);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Dot(Plane plane, Vector4 value)
		{
			return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D * value.W;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float DotCoordinate(Plane plane, Vector3 value)
		{
			if (Vector.IsHardwareAccelerated)
			{
				return Vector3.Dot(plane.Normal, value) + plane.D;
			}
			return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z + plane.D;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float DotNormal(Plane plane, Vector3 value)
		{
			if (Vector.IsHardwareAccelerated)
			{
				return Vector3.Dot(plane.Normal, value);
			}
			return plane.Normal.X * value.X + plane.Normal.Y * value.Y + plane.Normal.Z * value.Z;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool operator ==(Plane value1, Plane value2)
		{
			if (value1.Normal.X == value2.Normal.X && value1.Normal.Y == value2.Normal.Y && value1.Normal.Z == value2.Normal.Z)
			{
				return value1.D == value2.D;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool operator !=(Plane value1, Plane value2)
		{
			if (value1.Normal.X == value2.Normal.X && value1.Normal.Y == value2.Normal.Y && value1.Normal.Z == value2.Normal.Z)
			{
				return value1.D != value2.D;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool Equals(Plane other)
		{
			if (Vector.IsHardwareAccelerated)
			{
				if (Normal.Equals(other.Normal))
				{
					return D == other.D;
				}
				return false;
			}
			if (Normal.X == other.Normal.X && Normal.Y == other.Normal.Y && Normal.Z == other.Normal.Z)
			{
				return D == other.D;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override bool Equals(object obj)
		{
			if (obj is Plane)
			{
				return Equals((Plane)obj);
			}
			return false;
		}

		public override string ToString()
		{
			CultureInfo currentCulture = CultureInfo.CurrentCulture;
			return string.Format(currentCulture, "{{Normal:{0} D:{1}}}", Normal.ToString(), D.ToString(currentCulture));
		}

		public override int GetHashCode()
		{
			return Normal.GetHashCode() + D.GetHashCode();
		}
	}
	public struct Quaternion : IEquatable<Quaternion>
	{
		public float X;

		public float Y;

		public float Z;

		public float W;

		public static Quaternion Identity => new Quaternion(0f, 0f, 0f, 1f);

		public bool IsIdentity
		{
			get
			{
				if (X == 0f && Y == 0f && Z == 0f)
				{
					return W == 1f;
				}
				return false;
			}
		}

		public Quaternion(float x, float y, float z, float w)
		{
			X = x;
			Y = y;
			Z = z;
			W = w;
		}

		public Quaternion(Vector3 vectorPart, float scalarPart)
		{
			X = vectorPart.X;
			Y = vectorPart.Y;
			Z = vectorPart.Z;
			W = scalarPart;
		}

		public float Length()
		{
			return MathF.Sqrt(X * X + Y * Y + Z * Z + W * W);
		}

		public float LengthSquared()
		{
			return X * X + Y * Y + Z * Z + W * W;
		}

		public static Quaternion Normalize(Quaternion value)
		{
			float num = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W;
			float num2 = 1f / MathF.Sqrt(num);
			Quaternion result = default(Quaternion);
			result.X = value.X * num2;
			result.Y = value.Y * num2;
			result.Z = value.Z * num2;
			result.W = value.W * num2;
			return result;
		}

		public static Quaternion Conjugate(Quaternion value)
		{
			Quaternion result = default(Quaternion);
			result.X = 0f - value.X;
			result.Y = 0f - value.Y;
			result.Z = 0f - value.Z;
			result.W = value.W;
			return result;
		}

		public static Quaternion Inverse(Quaternion value)
		{
			float num = value.X * value.X + value.Y * value.Y + value.Z * value.Z + value.W * value.W;
			float num2 = 1f / num;
			Quaternion result = default(Quaternion);
			result.X = (0f - value.X) * num2;
			result.Y = (0f - value.Y) * num2;
			result.Z = (0f - value.Z) * num2;
			result.W = value.W * num2;
			return result;
		}

		public static Quaternion CreateFromAxisAngle(Vector3 axis, float angle)
		{
			float num = angle * 0.5f;
			float num2 = MathF.Sin(num);
			float w = MathF.Cos(num);
			Quaternion result = default(Quaternion);
			result.X = axis.X * num2;
			result.Y = axis.Y * num2;
			result.Z = axis.Z * num2;
			result.W = w;
			return result;
		}

		public static Quaternion CreateFromYawPitchRoll(float yaw, float pitch, float roll)
		{
			float num = roll * 0.5f;
			float num2 = MathF.Sin(num);
			float num3 = MathF.Cos(num);
			float num4 = pitch * 0.5f;
			float num5 = MathF.Sin(num4);
			float num6 = MathF.Cos(num4);
			float num7 = yaw * 0.5f;
			float num8 = MathF.Sin(num7);
			float num9 = MathF.Cos(num7);
			Quaternion result = default(Quaternion);
			result.X = num9 * num5 * num3 + num8 * num6 * num2;
			result.Y = num8 * num6 * num3 - num9 * num5 * num2;
			result.Z = num9 * num6 * num2 - num8 * num5 * num3;
			result.W = num9 * num6 * num3 + num8 * num5 * num2;
			return result;
		}

		public static Quaternion CreateFromRotationMatrix(Matrix4x4 matrix)
		{
			float num = matrix.M11 + matrix.M22 + matrix.M33;
			Quaternion result = default(Quaternion);
			if (num > 0f)
			{
				float num2 = MathF.Sqrt(num + 1f);
				result.W = num2 * 0.5f;
				num2 = 0.5f / num2;
				result.X = (matrix.M23 - matrix.M32) * num2;
				result.Y = (matrix.M31 - matrix.M13) * num2;
				result.Z = (matrix.M12 - matrix.M21) * num2;
			}
			else if (matrix.M11 >= matrix.M22 && matrix.M11 >= matrix.M33)
			{
				float num3 = MathF.Sqrt(1f + matrix.M11 - matrix.M22 - matrix.M33);
				float num4 = 0.5f / num3;
				result.X = 0.5f * num3;
				result.Y = (matrix.M12 + matrix.M21) * num4;
				result.Z = (matrix.M13 + matrix.M31) * num4;
				result.W = (matrix.M23 - matrix.M32) * num4;
			}
			else if (matrix.M22 > matrix.M33)
			{
				float num5 = MathF.Sqrt(1f + matrix.M22 - matrix.M11 - matrix.M33);
				float num6 = 0.5f / num5;
				result.X = (matrix.M21 + matrix.M12) * num6;
				result.Y = 0.5f * num5;
				result.Z = (matrix.M32 + matrix.M23) * num6;
				result.W = (matrix.M31 - matrix.M13) * num6;
			}
			else
			{
				float num7 = MathF.Sqrt(1f + matrix.M33 - matrix.M11 - matrix.M22);
				float num8 = 0.5f / num7;
				result.X = (matrix.M31 + matrix.M13) * num8;
				result.Y = (matrix.M32 + matrix.M23) * num8;
				result.Z = 0.5f * num7;
				result.W = (matrix.M12 - matrix.M21) * num8;
			}
			return result;
		}

		public static float Dot(Quaternion quaternion1, Quaternion quaternion2)
		{
			return quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W;
		}

		public static Quaternion Slerp(Quaternion quaternion1, Quaternion quaternion2, float amount)
		{
			float num = quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W;
			bool flag = false;
			if (num < 0f)
			{
				flag = true;
				num = 0f - num;
			}
			float num2;
			float num3;
			if (num > 0.999999f)
			{
				num2 = 1f - amount;
				num3 = (flag ? (0f - amount) : amount);
			}
			else
			{
				float num4 = MathF.Acos(num);
				float num5 = 1f / MathF.Sin(num4);
				num2 = MathF.Sin((1f - amount) * num4) * num5;
				num3 = (flag ? ((0f - MathF.Sin(amount * num4)) * num5) : (MathF.Sin(amount * num4) * num5));
			}
			Quaternion result = default(Quaternion);
			result.X = num2 * quaternion1.X + num3 * quaternion2.X;
			result.Y = num2 * quaternion1.Y + num3 * quaternion2.Y;
			result.Z = num2 * quaternion1.Z + num3 * quaternion2.Z;
			result.W = num2 * quaternion1.W + num3 * quaternion2.W;
			return result;
		}

		public static Quaternion Lerp(Quaternion quaternion1, Quaternion quaternion2, float amount)
		{
			float num = 1f - amount;
			Quaternion result = default(Quaternion);
			if (quaternion1.X * quaternion2.X + quaternion1.Y * quaternion2.Y + quaternion1.Z * quaternion2.Z + quaternion1.W * quaternion2.W >= 0f)
			{
				result.X = num * quaternion1.X + amount * quaternion2.X;
				result.Y = num * quaternion1.Y + amount * quaternion2.Y;
				result.Z = num * quaternion1.Z + amount * quaternion2.Z;
				result.W = num * quaternion1.W + amount * quaternion2.W;
			}
			else
			{
				result.X = num * quaternion1.X - amount * quaternion2.X;
				result.Y = num * quaternion1.Y - amount * quaternion2.Y;
				result.Z = num * quaternion1.Z - amount * quaternion2.Z;
				result.W = num * quaternion1.W - amount * quaternion2.W;
			}
			float num2 = result.X * result.X + result.Y * result.Y + result.Z * result.Z + result.W * result.W;
			float num3 = 1f / MathF.Sqrt(num2);
			result.X *= num3;
			result.Y *= num3;
			result.Z *= num3;
			result.W *= num3;
			return result;
		}

		public static Quaternion Concatenate(Quaternion value1, Quaternion value2)
		{
			float x = value2.X;
			float y = value2.Y;
			float z = value2.Z;
			float w = value2.W;
			float x2 = value1.X;
			float y2 = value1.Y;
			float z2 = value1.Z;
			float w2 = value1.W;
			float num = y * z2 - z * y2;
			float num2 = z * x2 - x * z2;
			float num3 = x * y2 - y * x2;
			float num4 = x * x2 + y * y2 + z * z2;
			Quaternion result = default(Quaternion);
			result.X = x * w2 + x2 * w + num;
			result.Y = y * w2 + y2 * w + num2;
			result.Z = z * w2 + z2 * w + num3;
			result.W = w * w2 - num4;
			return result;
		}

		public static Quaternion Negate(Quaternion value)
		{
			Quaternion result = default(Quaternion);
			result.X = 0f - value.X;
			result.Y = 0f - value.Y;
			result.Z = 0f - value.Z;
			result.W = 0f - value.W;
			return result;
		}

		public static Quaternion Add(Quaternion value1, Quaternion value2)
		{
			Quaternion result = default(Quaternion);
			result.X = value1.X + value2.X;
			result.Y = value1.Y + value2.Y;
			result.Z = value1.Z + value2.Z;
			result.W = value1.W + value2.W;
			return result;
		}

		public static Quaternion Subtract(Quaternion value1, Quaternion value2)
		{
			Quaternion result = default(Quaternion);
			result.X = value1.X - value2.X;
			result.Y = value1.Y - value2.Y;
			result.Z = value1.Z - value2.Z;
			result.W = value1.W - value2.W;
			return result;
		}

		public static Quaternion Multiply(Quaternion value1, Quaternion value2)
		{
			float x = value1.X;
			float y = value1.Y;
			float z = value1.Z;
			float w = value1.W;
			float x2 = value2.X;
			float y2 = value2.Y;
			float z2 = value2.Z;
			float w2 = value2.W;
			float num = y * z2 - z * y2;
			float num2 = z * x2 - x * z2;
			float num3 = x * y2 - y * x2;
			float num4 = x * x2 + y * y2 + z * z2;
			Quaternion result = default(Quaternion);
			result.X = x * w2 + x2 * w + num;
			result.Y = y * w2 + y2 * w + num2;
			result.Z = z * w2 + z2 * w + num3;
			result.W = w * w2 - num4;
			return result;
		}

		public static Quaternion Multiply(Quaternion value1, float value2)
		{
			Quaternion result = default(Quaternion);
			result.X = value1.X * value2;
			result.Y = value1.Y * value2;
			result.Z = value1.Z * value2;
			result.W = value1.W * value2;
			return result;
		}

		public static Quaternion Divide(Quaternion value1, Quaternion value2)
		{
			float x = value1.X;
			float y = value1.Y;
			float z = value1.Z;
			float w = value1.W;
			float num = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W;
			float num2 = 1f / num;
			float num3 = (0f - value2.X) * num2;
			float num4 = (0f - value2.Y) * num2;
			float num5 = (0f - value2.Z) * num2;
			float num6 = value2.W * num2;
			float num7 = y * num5 - z * num4;
			float num8 = z * num3 - x * num5;
			float num9 = x * num4 - y * num3;
			float num10 = x * num3 + y * num4 + z * num5;
			Quaternion result = default(Quaternion);
			result.X = x * num6 + num3 * w + num7;
			result.Y = y * num6 + num4 * w + num8;
			result.Z = z * num6 + num5 * w + num9;
			result.W = w * num6 - num10;
			return result;
		}

		public static Quaternion operator -(Quaternion value)
		{
			Quaternion result = default(Quaternion);
			result.X = 0f - value.X;
			result.Y = 0f - value.Y;
			result.Z = 0f - value.Z;
			result.W = 0f - value.W;
			return result;
		}

		public static Quaternion operator +(Quaternion value1, Quaternion value2)
		{
			Quaternion result = default(Quaternion);
			result.X = value1.X + value2.X;
			result.Y = value1.Y + value2.Y;
			result.Z = value1.Z + value2.Z;
			result.W = value1.W + value2.W;
			return result;
		}

		public static Quaternion operator -(Quaternion value1, Quaternion value2)
		{
			Quaternion result = default(Quaternion);
			result.X = value1.X - value2.X;
			result.Y = value1.Y - value2.Y;
			result.Z = value1.Z - value2.Z;
			result.W = value1.W - value2.W;
			return result;
		}

		public static Quaternion operator *(Quaternion value1, Quaternion value2)
		{
			float x = value1.X;
			float y = value1.Y;
			float z = value1.Z;
			float w = value1.W;
			float x2 = value2.X;
			float y2 = value2.Y;
			float z2 = value2.Z;
			float w2 = value2.W;
			float num = y * z2 - z * y2;
			float num2 = z * x2 - x * z2;
			float num3 = x * y2 - y * x2;
			float num4 = x * x2 + y * y2 + z * z2;
			Quaternion result = default(Quaternion);
			result.X = x * w2 + x2 * w + num;
			result.Y = y * w2 + y2 * w + num2;
			result.Z = z * w2 + z2 * w + num3;
			result.W = w * w2 - num4;
			return result;
		}

		public static Quaternion operator *(Quaternion value1, float value2)
		{
			Quaternion result = default(Quaternion);
			result.X = value1.X * value2;
			result.Y = value1.Y * value2;
			result.Z = value1.Z * value2;
			result.W = value1.W * value2;
			return result;
		}

		public static Quaternion operator /(Quaternion value1, Quaternion value2)
		{
			float x = value1.X;
			float y = value1.Y;
			float z = value1.Z;
			float w = value1.W;
			float num = value2.X * value2.X + value2.Y * value2.Y + value2.Z * value2.Z + value2.W * value2.W;
			float num2 = 1f / num;
			float num3 = (0f - value2.X) * num2;
			float num4 = (0f - value2.Y) * num2;
			float num5 = (0f - value2.Z) * num2;
			float num6 = value2.W * num2;
			float num7 = y * num5 - z * num4;
			float num8 = z * num3 - x * num5;
			float num9 = x * num4 - y * num3;
			float num10 = x * num3 + y * num4 + z * num5;
			Quaternion result = default(Quaternion);
			result.X = x * num6 + num3 * w + num7;
			result.Y = y * num6 + num4 * w + num8;
			result.Z = z * num6 + num5 * w + num9;
			result.W = w * num6 - num10;
			return result;
		}

		public static bool operator ==(Quaternion value1, Quaternion value2)
		{
			if (value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z)
			{
				return value1.W == value2.W;
			}
			return false;
		}

		public static bool operator !=(Quaternion value1, Quaternion value2)
		{
			if (value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z)
			{
				return value1.W != value2.W;
			}
			return true;
		}

		public bool Equals(Quaternion other)
		{
			if (X == other.X && Y == other.Y && Z == other.Z)
			{
				return W == other.W;
			}
			return false;
		}

		public override bool Equals(object obj)
		{
			if (obj is Quaternion)
			{
				return Equals((Quaternion)obj);
			}
			return false;
		}

		public override string ToString()
		{
			CultureInfo currentCulture = CultureInfo.CurrentCulture;
			return string.Format(currentCulture, "{{X:{0} Y:{1} Z:{2} W:{3}}}", X.ToString(currentCulture), Y.ToString(currentCulture), Z.ToString(currentCulture), W.ToString(currentCulture));
		}

		public override int GetHashCode()
		{
			return X.GetHashCode() + Y.GetHashCode() + Z.GetHashCode() + W.GetHashCode();
		}
	}
	public struct Vector2 : IEquatable<Vector2>, IFormattable
	{
		public float X;

		public float Y;

		public static Vector2 Zero => default(Vector2);

		public static Vector2 One => new Vector2(1f, 1f);

		public static Vector2 UnitX => new Vector2(1f, 0f);

		public static Vector2 UnitY => new Vector2(0f, 1f);

		public override int GetHashCode()
		{
			return HashHelpers.Combine(X.GetHashCode(), Y.GetHashCode());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override bool Equals(object obj)
		{
			if (!(obj is Vector2))
			{
				return false;
			}
			return Equals((Vector2)obj);
		}

		public override string ToString()
		{
			return ToString("G", CultureInfo.CurrentCulture);
		}

		public string ToString(string format)
		{
			return ToString(format, CultureInfo.CurrentCulture);
		}

		public string ToString(string format, IFormatProvider formatProvider)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
			stringBuilder.Append('<');
			stringBuilder.Append(X.ToString(format, formatProvider));
			stringBuilder.Append(numberGroupSeparator);
			stringBuilder.Append(' ');
			stringBuilder.Append(Y.ToString(format, formatProvider));
			stringBuilder.Append('>');
			return stringBuilder.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public float Length()
		{
			if (Vector.IsHardwareAccelerated)
			{
				return MathF.Sqrt(Dot(this, this));
			}
			return MathF.Sqrt(X * X + Y * Y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public float LengthSquared()
		{
			if (Vector.IsHardwareAccelerated)
			{
				return Dot(this, this);
			}
			return X * X + Y * Y;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Distance(Vector2 value1, Vector2 value2)
		{
			if (Vector.IsHardwareAccelerated)
			{
				Vector2 vector = value1 - value2;
				return MathF.Sqrt(Dot(vector, vector));
			}
			float num = value1.X - value2.X;
			float num2 = value1.Y - value2.Y;
			return MathF.Sqrt(num * num + num2 * num2);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float DistanceSquared(Vector2 value1, Vector2 value2)
		{
			if (Vector.IsHardwareAccelerated)
			{
				Vector2 vector = value1 - value2;
				return Dot(vector, vector);
			}
			float num = value1.X - value2.X;
			float num2 = value1.Y - value2.Y;
			return num * num + num2 * num2;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Normalize(Vector2 value)
		{
			if (Vector.IsHardwareAccelerated)
			{
				float num = value.Length();
				return value / num;
			}
			float num2 = value.X * value.X + value.Y * value.Y;
			float num3 = 1f / MathF.Sqrt(num2);
			return new Vector2(value.X * num3, value.Y * num3);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Reflect(Vector2 vector, Vector2 normal)
		{
			if (Vector.IsHardwareAccelerated)
			{
				float num = Dot(vector, normal);
				return vector - 2f * num * normal;
			}
			float num2 = vector.X * normal.X + vector.Y * normal.Y;
			return new Vector2(vector.X - 2f * num2 * normal.X, vector.Y - 2f * num2 * normal.Y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max)
		{
			float x = value1.X;
			x = ((x > max.X) ? max.X : x);
			x = ((x < min.X) ? min.X : x);
			float y = value1.Y;
			y = ((y > max.Y) ? max.Y : y);
			y = ((y < min.Y) ? min.Y : y);
			return new Vector2(x, y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount)
		{
			return new Vector2(value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Transform(Vector2 position, Matrix3x2 matrix)
		{
			return new Vector2(position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M31, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M32);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Transform(Vector2 position, Matrix4x4 matrix)
		{
			return new Vector2(position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix)
		{
			return new Vector2(normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix)
		{
			return new Vector2(normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Transform(Vector2 value, Quaternion rotation)
		{
			float num = rotation.X + rotation.X;
			float num2 = rotation.Y + rotation.Y;
			float num3 = rotation.Z + rotation.Z;
			float num4 = rotation.W * num3;
			float num5 = rotation.X * num;
			float num6 = rotation.X * num2;
			float num7 = rotation.Y * num2;
			float num8 = rotation.Z * num3;
			return new Vector2(value.X * (1f - num7 - num8) + value.Y * (num6 - num4), value.X * (num6 + num4) + value.Y * (1f - num5 - num8));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Add(Vector2 left, Vector2 right)
		{
			return left + right;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Subtract(Vector2 left, Vector2 right)
		{
			return left - right;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Multiply(Vector2 left, Vector2 right)
		{
			return left * right;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Multiply(Vector2 left, float right)
		{
			return left * right;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Multiply(float left, Vector2 right)
		{
			return left * right;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Divide(Vector2 left, Vector2 right)
		{
			return left / right;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Divide(Vector2 left, float divisor)
		{
			return left / divisor;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 Negate(Vector2 value)
		{
			return -value;
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public Vector2(float value)
			: this(value, value)
		{
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public Vector2(float x, float y)
		{
			X = x;
			Y = y;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void CopyTo(float[] array)
		{
			CopyTo(array, 0);
		}

		public void CopyTo(float[] array, int index)
		{
			if (array == null)
			{
				throw new NullReferenceException("The method was called with a null array argument.");
			}
			if (index < 0 || index >= array.Length)
			{
				throw new ArgumentOutOfRangeException("index", SR.Format("Index was out of bounds:", index));
			}
			if (array.Length - index < 2)
			{
				throw new ArgumentException(SR.Format("Number of elements in source vector is greater than the destination array", index));
			}
			array[index] = X;
			array[index + 1] = Y;
		}

		[System.Runtime.CompilerServices.Intrinsic]
		public bool Equals(Vector2 other)
		{
			if (X == other.X)
			{
				return Y == other.Y;
			}
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static float Dot(Vector2 value1, Vector2 value2)
		{
			return value1.X * value2.X + value1.Y * value2.Y;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 Min(Vector2 value1, Vector2 value2)
		{
			return new Vector2((value1.X < value2.X) ? value1.X : value2.X, (value1.Y < value2.Y) ? value1.Y : value2.Y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 Max(Vector2 value1, Vector2 value2)
		{
			return new Vector2((value1.X > value2.X) ? value1.X : value2.X, (value1.Y > value2.Y) ? value1.Y : value2.Y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 Abs(Vector2 value)
		{
			return new Vector2(MathF.Abs(value.X), MathF.Abs(value.Y));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 SquareRoot(Vector2 value)
		{
			return new Vector2(MathF.Sqrt(value.X), MathF.Sqrt(value.Y));
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 operator +(Vector2 left, Vector2 right)
		{
			return new Vector2(left.X + right.X, left.Y + right.Y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 operator -(Vector2 left, Vector2 right)
		{
			return new Vector2(left.X - right.X, left.Y - right.Y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 operator *(Vector2 left, Vector2 right)
		{
			return new Vector2(left.X * right.X, left.Y * right.Y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 operator *(float left, Vector2 right)
		{
			return new Vector2(left, left) * right;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 operator *(Vector2 left, float right)
		{
			return left * new Vector2(right, right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.CompilerServices.Intrinsic]
		public static Vector2 operator /(Vector2 left, Vector2 right)
		{
			return new Vector2(left.X / right.X, left.Y / right.Y);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 operator /(Vector2 value1, float value2)
		{
			return value1 / new Vector2(value2);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector2 operator -(Vector2 value)
		{
			return Zero - value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool operator ==(Vector2 left, Vector2 right)
		{
			return left.Equals(right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool operator !=(Vector2 left, Vector2 right)
		{
			return !(left == right);
		}
	}
	public struct Vector3 : IEquatable<Vector3>, IFormattable
	{
		public float X;

		public float Y;

		public float Z;

		public static Vector3 Zero => default(Vector3);

		public static Vector3 One => new Vector3(1f, 1f, 1f);

		public static Vector3 UnitX => new Vector3(1f, 0f, 0f);

		public static Vector3 UnitY => new Vector3(0f, 1f, 0f);

		public static Vector3 UnitZ => new Vector3(0f, 0f, 1f);

		public override int GetHashCode()
		{
			return HashHelpers.Combine(HashHelpers.Combine(X.GetHashCode(), Y.GetHashCode()), Z.GetHashCode());
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public override bool Equals(object obj)
		{
			if (!(obj is Vector3))
			{
				return false;
			}
			return Equals((Vector3)obj);
		}

		public override string ToString()
		{
			return ToString("G", CultureInfo.CurrentCulture);
		}

		public string ToString(string format)
		{
			return ToString(format, CultureInfo.CurrentCulture);
		}

		public string ToString(string format, IFormatProvider formatProvider)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string numberGroupSeparator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator;
			stringBuilder.Append('<');
			stringBuilder.Append(((IFormattable)X).ToString(format, formatProvider));
			stringBuilder.Append(numberGroupSeparator);
			stringBuilder.Append(' ');
			stringBuilder.Append(((IFormattable)Y).ToString(format, formatProvider));
			stringBuilder.Append(numberGroupSeparator);
			stringBuilder.Append(' ');
			stringBuilder.Append(((IFormattable)Z).ToString(format, formatProvider));
			stringBuilder.Append('>');
			return stringBuilder.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public float Length()
		{
			if (Vector.IsHardwareAccelerated)
			{
				return MathF.Sqrt(Dot(this, this));
			}
			return MathF.Sqrt(X * X + Y * Y + Z * Z);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public float LengthSquared()
		{
			if (Vector.IsHardwareAccelerated)
			{
				return Dot(this, this);
			}
			return X * X + Y * Y + Z * Z;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float Distance(Vector3 value1, Vector3 value2)
		{
			if (Vector.IsHardwareAccelerated)
			{
				Vector3 vector = value1 - value2;
				return MathF.Sqrt(Dot(vector, vector));
			}
			float num = value1.X - value2.X;
			float num2 = value1.Y - value2.Y;
			float num3 = value1.Z - value2.Z;
			return MathF.Sqrt(num * num + num2 * num2 + num3 * num3);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static float DistanceSquared(Vector3 value1, Vector3 value2)
		{
			if (Vector.IsHardwareAccelerated)
			{
				Vector3 vector = value1 - value2;
				return Dot(vector, vector);
			}
			float num = value1.X - value2.X;
			float num2 = value1.Y - value2.Y;
			float num3 = value1.Z - value2.Z;
			return num * num + num2 * num2 + num3 * num3;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector3 Normalize(Vector3 value)
		{
			if (Vector.IsHardwareAccelerated)
			{
				float num = value.Length();
				return value / num;
			}
			float num2 = MathF.Sqrt(value.X * value.X + value.Y * value.Y + value.Z * value.Z);
			return new Vector3(value.X / num2, value.Y / num2, value.Z / num2);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector3 Cross(Vector3 vector1, Vector3 vector2)
		{
			return new Vector3(vector1.Y * vector2.Z - vector1.Z * vector2.Y, vector1.Z * vector2.X - vector1.X * vector2.Z, vector1.X * vector2.Y - vector1.Y * vector2.X);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector3 Reflect(Vector3 vector, Vector3 normal)
		{
			if (Vector.IsHardwareAccelerated)
			{
				float num = Dot(vector, normal);
				Vector3 vector2 = normal * num * 2f;
				return vector - vector2;
			}
			float num2 = vector.X * normal.X + vector.Y * normal.Y + vector.Z * normal.Z;
			float num3 = normal.X * num2 * 2f;
			float num4 = normal.Y * num2 * 2f;
			float num5 = normal.Z * num2 * 2f;
			return new Vector3(vector.X - num3, vector.Y - num4, vector.Z - num5);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max)
		{
			float x = value1.X;
			x = ((x > max.X) ? max.X : x);
			x = ((x < min.X) ? min.X : x);
			float y = value1.Y;
			y = ((y > max.Y) ? max.Y : y);
			y = ((y < min.Y) ? min.Y : y);
			float z = value1.Z;
			z = ((z > max.Z) ? max.Z : z);
			z = ((z < min.Z) ? min.Z : z);
			return new Vector3(x, y, z);
		}

		[MethodImpl(MethodImplOption

BepInEx/core/System.Numerics.Tensors.dll

Decompiled 2 weeks ago
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using FxResources.System.Numerics.Tensors;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.Numerics.Tensors.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Numerics.Tensors")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides support for operating over tensors.")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Numerics.Tensors")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("10.0.0.1")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(true)]
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]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.System.Numerics.Tensors
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class ThrowHelper
	{
		[DoesNotReturn]
		public static void ThrowArgument_DestinationTooShort()
		{
			ThrowArgument_DestinationTooShort("destination");
		}

		[DoesNotReturn]
		public static void ThrowArgument_DestinationTooShort(string destinationName)
		{
			throw new ArgumentException(System.SR.Argument_DestinationTooShort, destinationName);
		}

		[DoesNotReturn]
		public static void ThrowArgument_SpansMustHaveSameLength()
		{
			throw new ArgumentException(System.SR.Argument_SpansMustHaveSameLength);
		}

		[DoesNotReturn]
		public static void ThrowArgument_SpansMustBeNonEmpty()
		{
			throw new ArgumentException(System.SR.Argument_SpansMustBeNonEmpty);
		}

		[DoesNotReturn]
		public static void ThrowArgument_InputAndDestinationSpanMustNotOverlap()
		{
			throw new ArgumentException(System.SR.Argument_InputAndDestinationSpanMustNotOverlap, "destination");
		}

		public static void ThrowIfArrayTypeMismatch<T>(Array? array)
		{
			if (array != null && array.GetType().GetElementType() != typeof(T))
			{
				ThrowArrayTypeMismatchException();
			}
		}

		public static void ThrowIfArrayTypeMismatch<T>(T[]? array)
		{
			if (array != null && !typeof(T).IsValueType && array.GetType() != typeof(T[]))
			{
				ThrowArrayTypeMismatchException();
			}
		}

		[DoesNotReturn]
		public static void ThrowArgument_DestinationSpansMustNotOverlap()
		{
			throw new ArgumentException(System.SR.Argument_DestinationSpansMustNotOverlap);
		}

		[DoesNotReturn]
		internal static void ThrowArrayTypeMismatchException()
		{
			throw new ArrayTypeMismatchException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException()
		{
			throw new ArgumentOutOfRangeException();
		}

		[DoesNotReturn]
		internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType)
		{
			throw new ArgumentException(System.SR.Format(System.SR.Argument_InvalidTypeWithPointersNotSupported, targetType));
		}

		[DoesNotReturn]
		internal static void ThrowIndexOutOfRangeException()
		{
			throw new IndexOutOfRangeException();
		}

		[DoesNotReturn]
		public static void ThrowArgument_LengthsMustEqualArrayLength()
		{
			throw new ArgumentOutOfRangeException();
		}

		[DoesNotReturn]
		public static void ThrowArgument_LengthIsNegative()
		{
			throw new ArgumentOutOfRangeException();
		}

		[DoesNotReturn]
		public static void ThrowArgument_StartIndexOutOfBounds()
		{
			throw new ArgumentOutOfRangeException();
		}

		[DoesNotReturn]
		public static void ThrowArgument_IndicesLengthMustEqualRank()
		{
			throw new ArgumentException(System.SR.ThrowArgument_IndicesLengthMustEqualRank);
		}

		private static ArgumentException GetArgumentException(string message)
		{
			return new ArgumentException(message);
		}

		[DoesNotReturn]
		public static void ThrowValueArgumentOutOfRange_NeedNonNegNumException()
		{
			throw new ArgumentOutOfRangeException("value", System.SR.ThrowArgument_ValueNonNegative);
		}

		[DoesNotReturn]
		public static void ThrowArgument_FilterTensorMustEqualTensorLength()
		{
			throw new ArgumentException(System.SR.ThrowArgument_FilterTensorMustEqualTensorLength);
		}

		[DoesNotReturn]
		public static void ThrowArgument_SetSliceNoRange(string? paramNames)
		{
			throw new ArgumentException(System.SR.ThrowArgument_SetSliceNoRange, paramNames);
		}

		[DoesNotReturn]
		public static void ThrowArgument_SetSliceInvalidShapes(string? paramNames)
		{
			throw new ArgumentException(System.SR.ThrowArgument_SetSliceInvalidShapes, paramNames);
		}

		[DoesNotReturn]
		public static void ThrowArgument_LengthsNotCompatible()
		{
			throw new ArgumentException(System.SR.ThrowArgument_LengthsNotCompatible);
		}

		[DoesNotReturn]
		public static void ThrowArgument_SplitNotSplitEvenly()
		{
			throw new ArgumentException(System.SR.ThrowArgument_SplitNotSplitEvenly);
		}

		[DoesNotReturn]
		public static void ThrowArgument_DimensionsNotSame(string? paramNames)
		{
			throw new ArgumentException(System.SR.ThrowArgument_DimensionsNotSame, paramNames);
		}

		[DoesNotReturn]
		public static void ThrowArgument_1DTensorRequired(string? paramNames)
		{
			throw new ArgumentException(System.SR.ThrowArgument_1DTensorRequired, paramNames);
		}

		[DoesNotReturn]
		public static void ThrowArgument_2DTensorRequired(string? paramNames)
		{
			throw new ArgumentException(System.SR.Argument_2DTensorRequired, paramNames);
		}

		[DoesNotReturn]
		public static void ThrowArgument_IncorrectNumberOfFilterItems(string? paramNames)
		{
			throw new ArgumentException(System.SR.ThrowArgument_IncorrectNumberOfFilterItems, paramNames);
		}

		[DoesNotReturn]
		public static void ThrowArgument_StackTooFewTensors()
		{
			throw new ArgumentException(System.SR.ThrowArgument_StackTooFewTensors);
		}

		[DoesNotReturn]
		public static void ThrowArgument_OnlyOneWildcard()
		{
			throw new ArgumentException(System.SR.ThrowArgument_OnlyOneWildcard);
		}

		[DoesNotReturn]
		public static void ThrowArgument_InvalidReshapeDimensions()
		{
			throw new ArgumentException(System.SR.ThrowArgument_InvalidReshapeDimensions);
		}

		[DoesNotReturn]
		public static void ThrowArgument_AxisLargerThanRank()
		{
			throw new ArgumentException(System.SR.ThrowArgument_AxisLargerThanRank);
		}

		[DoesNotReturn]
		public static void ThrowArgument_InvalidSqueezeAxis()
		{
			throw new ArgumentException(System.SR.ThrowArgument_InvalidSqueezeAxis);
		}

		[DoesNotReturn]
		public static void ThrowArgument_ConcatenateTooFewTensors()
		{
			throw new ArgumentException(System.SR.ThrowArgument_ConcatenateTooFewTensors);
		}

		[DoesNotReturn]
		public static void ThrowArgument_InvalidDimension()
		{
			throw new ArgumentException(System.SR.ThrowArgument_InvalidDimension);
		}

		[DoesNotReturn]
		public static void ThrowArgument_InvalidConcatenateShape()
		{
			throw new ArgumentException(System.SR.ThrowArgument_InvalidConcatenateShape);
		}

		[DoesNotReturn]
		public static void ThrowArgument_TransposeTooFewDimensions()
		{
			throw new ArgumentException(System.SR.ThrowArgument_TransposeTooFewDimensions);
		}

		[DoesNotReturn]
		public static void ThrowArgument_PermuteAxisOrder()
		{
			throw new ArgumentException(System.SR.ThrowArgument_PermuteAxisOrder);
		}

		[DoesNotReturn]
		public static void ThrowArgument_InPlaceInvalidShape()
		{
			throw new ArgumentException(System.SR.ThrowArgument_InPlaceInvalidShape);
		}

		[DoesNotReturn]
		public static void ThrowArgument_InvalidTensorShape()
		{
			throw new ArgumentException(System.SR.ThrowArgument_InvalidStridesAndLengths);
		}

		[DoesNotReturn]
		public static void ThrowArgument_LengthIsNonZeroForNullReference()
		{
			throw new ArgumentOutOfRangeException(System.SR.ThrowArgument_LengthIsNonZeroForNullReference);
		}

		[DoesNotReturn]
		public static void ThrowArgument_StrideIsNegative()
		{
			throw new ArgumentOutOfRangeException(System.SR.ThrowArgument_StrideLessThan0);
		}

		[DoesNotReturn]
		internal static void ThrowArgument_IncompatibleDimensions(nint leftDim, nint rightDim)
		{
			throw new ArgumentException(System.SR.Format(System.SR.Argument_IncompatibleDimensions, leftDim, rightDim));
		}

		[DoesNotReturn]
		internal static void ThrowArgument_StackShapesNotSame()
		{
			throw new ArgumentException(System.SR.ThrowArgument_StackShapesNotSame);
		}

		[DoesNotReturn]
		internal static void ThrowArgument_CannotReshapeNonContiguousOrDense()
		{
			throw new ArgumentException(System.SR.Argument_CannotReshapeNonContiguousOrDense);
		}

		[DoesNotReturn]
		internal static void ThrowArgument_MinGreaterThanMax()
		{
			throw new ArgumentException(System.SR.Argument_MinGreaterThanMax);
		}

		[DoesNotReturn]
		internal static void ThrowArithmetic_NaN()
		{
			throw new ArithmeticException(System.SR.Arithmetic_NaN);
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Argument_DestinationTooShort => GetResourceString("Argument_DestinationTooShort");

		internal static string Argument_SpansMustBeNonEmpty => GetResourceString("Argument_SpansMustBeNonEmpty");

		internal static string Argument_SpansMustHaveSameLength => GetResourceString("Argument_SpansMustHaveSameLength");

		internal static string Argument_InputAndDestinationSpanMustNotOverlap => GetResourceString("Argument_InputAndDestinationSpanMustNotOverlap");

		internal static string Argument_DestinationSpansMustNotOverlap => GetResourceString("Argument_DestinationSpansMustNotOverlap");

		internal static string Overflow_NegateTwosCompNum => GetResourceString("Overflow_NegateTwosCompNum");

		internal static string Argument_InvalidEnumValue => GetResourceString("Argument_InvalidEnumValue");

		internal static string Argument_InvalidTypeWithPointersNotSupported => GetResourceString("Argument_InvalidTypeWithPointersNotSupported");

		internal static string DestinationTooShort => GetResourceString("DestinationTooShort");

		internal static string NotSupported_CannotCallEqualsOnSpan => GetResourceString("NotSupported_CannotCallEqualsOnSpan");

		internal static string NotSupported_CannotCallGetHashCodeOnSpan => GetResourceString("NotSupported_CannotCallGetHashCodeOnSpan");

		internal static string ThrowArgument_IndicesLengthMustEqualRank => GetResourceString("ThrowArgument_IndicesLengthMustEqualRank");

		internal static string ThrowArgument_LengthsMustEqualArrayLength => GetResourceString("ThrowArgument_LengthsMustEqualArrayLength");

		internal static string ThrowArgument_1DTensorRequired => GetResourceString("ThrowArgument_1DTensorRequired");

		internal static string ThrowArgument_AxisLargerThanRank => GetResourceString("ThrowArgument_AxisLargerThanRank");

		internal static string ThrowArgument_ConcatenateTooFewTensors => GetResourceString("ThrowArgument_ConcatenateTooFewTensors");

		internal static string ThrowArgument_DimensionsNotSame => GetResourceString("ThrowArgument_DimensionsNotSame");

		internal static string ThrowArgument_FilterTensorMustEqualTensorLength => GetResourceString("ThrowArgument_FilterTensorMustEqualTensorLength");

		internal static string ThrowArgument_IncorrectNumberOfFilterItems => GetResourceString("ThrowArgument_IncorrectNumberOfFilterItems");

		internal static string ThrowArgument_InPlaceInvalidShape => GetResourceString("ThrowArgument_InPlaceInvalidShape");

		internal static string ThrowArgument_InvalidDimension => GetResourceString("ThrowArgument_InvalidDimension");

		internal static string ThrowArgument_InvalidConcatenateShape => GetResourceString("ThrowArgument_InvalidConcatenateShape");

		internal static string ThrowArgument_InvalidReshapeDimensions => GetResourceString("ThrowArgument_InvalidReshapeDimensions");

		internal static string ThrowArgument_InvalidSqueezeAxis => GetResourceString("ThrowArgument_InvalidSqueezeAxis");

		internal static string ThrowArgument_OnlyOneWildcard => GetResourceString("ThrowArgument_OnlyOneWildcard");

		internal static string ThrowArgument_PermuteAxisOrder => GetResourceString("ThrowArgument_PermuteAxisOrder");

		internal static string ThrowArgument_SetSliceInvalidShapes => GetResourceString("ThrowArgument_SetSliceInvalidShapes");

		internal static string ThrowArgument_SetSliceNoRange => GetResourceString("ThrowArgument_SetSliceNoRange");

		internal static string ThrowArgument_LengthsNotCompatible => GetResourceString("ThrowArgument_LengthsNotCompatible");

		internal static string ThrowArgument_SplitNotSplitEvenly => GetResourceString("ThrowArgument_SplitNotSplitEvenly");

		internal static string ThrowArgument_StackTooFewTensors => GetResourceString("ThrowArgument_StackTooFewTensors");

		internal static string ThrowArgument_TransposeTooFewDimensions => GetResourceString("ThrowArgument_TransposeTooFewDimensions");

		internal static string ThrowArgument_ValueNonNegative => GetResourceString("ThrowArgument_ValueNonNegative");

		internal static string ThrowArgument_InvalidStridesAndLengths => GetResourceString("ThrowArgument_InvalidStridesAndLengths");

		internal static string ThrowArgument_StrideLessThan0 => GetResourceString("ThrowArgument_StrideLessThan0");

		internal static string Argument_2DTensorRequired => GetResourceString("Argument_2DTensorRequired");

		internal static string Argument_IncompatibleDimensions => GetResourceString("Argument_IncompatibleDimensions");

		internal static string ThrowArgument_StackShapesNotSame => GetResourceString("ThrowArgument_StackShapesNotSame");

		internal static string Argument_CannotReshapeNonContiguousOrDense => GetResourceString("Argument_CannotReshapeNonContiguousOrDense");

		internal static string Argument_MinGreaterThanMax => GetResourceString("Argument_MinGreaterThanMax");

		internal static string Arithmetic_NaN => GetResourceString("Arithmetic_NaN");

		internal static string ThrowArgument_LengthIsNonZeroForNullReference => GetResourceString("ThrowArgument_LengthIsNonZeroForNullReference");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object? argument, [CallerArgumentExpression("argument")] string? paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string? EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type? StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Numerics.Tensors
{
	public static class TensorPrimitives
	{
		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct AddOperator_Single : IAggregationOperator, IBinaryOperator
		{
			public float IdentityValue => 0f;

			public float Invoke(float x, float y)
			{
				return x + y;
			}

			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				return x + y;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct SubtractOperator_Single : IBinaryOperator
		{
			public float Invoke(float x, float y)
			{
				return x - y;
			}

			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				return x - y;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct SubtractSquaredOperator_Single : IBinaryOperator
		{
			public float Invoke(float x, float y)
			{
				float num = x - y;
				return num * num;
			}

			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				Vector<float> vector = x - y;
				return vector * vector;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MultiplyOperator_Single : IAggregationOperator, IBinaryOperator
		{
			public float IdentityValue => 1f;

			public float Invoke(float x, float y)
			{
				return x * y;
			}

			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				return x * y;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct DivideOperator_Single : IBinaryOperator
		{
			public float Invoke(float x, float y)
			{
				return x / y;
			}

			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				return x / y;
			}
		}

		private interface IIndexOfOperator
		{
			int Invoke(ref float result, float current, int resultIndex, int currentIndex);

			int Invoke(Vector<float> result, Vector<int> resultIndex);

			void Invoke(ref Vector<float> result, Vector<float> current, ref Vector<int> resultIndex, Vector<int> currentIndex);
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct IndexOfMaxOperator_Single : IIndexOfOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int Invoke(ref float result, float current, int resultIndex, int currentIndex)
			{
				if (result == current)
				{
					bool flag = IsNegative(result);
					if ((flag == IsNegative(current)) ? (currentIndex < resultIndex) : flag)
					{
						result = current;
						return currentIndex;
					}
				}
				else if (current > result)
				{
					result = current;
					return currentIndex;
				}
				return resultIndex;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int Invoke(Vector<float> current, Vector<int> currentIndex)
			{
				float num = current[0];
				int num2 = currentIndex[0];
				for (int i = 1; i < Vector<float>.Count; i++)
				{
					if (current[i] == num)
					{
						bool flag = IsNegative(num);
						if ((flag == IsNegative(current[i])) ? (currentIndex[i] < num2) : flag)
						{
							num = current[i];
							num2 = currentIndex[i];
						}
					}
					else if (current[i] > num)
					{
						num = current[i];
						num2 = currentIndex[i];
					}
				}
				return num2;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public void Invoke(ref Vector<float> result, Vector<float> current, ref Vector<int> resultIndex, Vector<int> currentIndex)
			{
				Vector<int> condition = Vector.GreaterThan(result, current);
				Vector<int> vector = Vector.Equals(result, current);
				if (vector != Vector<int>.Zero)
				{
					Vector<float> vector2 = IsNegative(current);
					condition |= vector & Vector.ConditionalSelect(Vector.Equals(IsNegative(result), vector2), Vector.LessThan(resultIndex, currentIndex), (Vector<int>)vector2);
				}
				result = Vector.ConditionalSelect(condition, result, current);
				resultIndex = Vector.ConditionalSelect(condition, resultIndex, currentIndex);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct IndexOfMaxMagnitudeOperator_Single : IIndexOfOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int Invoke(ref float result, float current, int resultIndex, int currentIndex)
			{
				float num = MathF.Abs(result);
				float num2 = MathF.Abs(current);
				if (num == num2)
				{
					bool flag = IsNegative(result);
					if ((flag == IsNegative(current)) ? (currentIndex < resultIndex) : flag)
					{
						result = current;
						return currentIndex;
					}
				}
				else if (num2 > num)
				{
					result = current;
					return currentIndex;
				}
				return resultIndex;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int Invoke(Vector<float> current, Vector<int> currentIndex)
			{
				float num = current[0];
				float num2 = MathF.Abs(num);
				int num3 = currentIndex[0];
				for (int i = 1; i < Vector<float>.Count; i++)
				{
					float num4 = MathF.Abs(current[i]);
					if (num2 == num4)
					{
						bool flag = IsNegative(num);
						if ((flag == IsNegative(current[i])) ? (currentIndex[i] < num3) : flag)
						{
							num = current[i];
							num2 = num4;
							num3 = currentIndex[i];
						}
					}
					else if (num4 > num2)
					{
						num = current[i];
						num2 = num4;
						num3 = currentIndex[i];
					}
				}
				return num3;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public void Invoke(ref Vector<float> result, Vector<float> current, ref Vector<int> resultIndex, Vector<int> currentIndex)
			{
				Vector<float> left = Vector.Abs(result);
				Vector<float> right = Vector.Abs(current);
				Vector<int> condition = Vector.GreaterThan(left, right);
				Vector<int> vector = Vector.Equals(left, right);
				if (vector != Vector<int>.Zero)
				{
					Vector<float> vector2 = IsNegative(current);
					condition |= vector & Vector.ConditionalSelect(Vector.Equals(IsNegative(result), vector2), Vector.LessThan(resultIndex, currentIndex), (Vector<int>)vector2);
				}
				result = Vector.ConditionalSelect(condition, result, current);
				resultIndex = Vector.ConditionalSelect(condition, resultIndex, currentIndex);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct IndexOfMinOperator_Single : IIndexOfOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int Invoke(ref float result, float current, int resultIndex, int currentIndex)
			{
				if (result == current)
				{
					bool flag = IsNegative(current);
					if ((IsNegative(result) == flag) ? (currentIndex < resultIndex) : flag)
					{
						result = current;
						return currentIndex;
					}
				}
				else if (current < result)
				{
					result = current;
					return currentIndex;
				}
				return resultIndex;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int Invoke(Vector<float> current, Vector<int> currentIndex)
			{
				float num = current[0];
				int num2 = currentIndex[0];
				for (int i = 1; i < Vector<float>.Count; i++)
				{
					if (current[i] == num)
					{
						bool flag = IsNegative(current[i]);
						if ((IsNegative(num) == flag) ? (currentIndex[i] < num2) : flag)
						{
							num = current[i];
							num2 = currentIndex[i];
						}
					}
					else if (current[i] < num)
					{
						num = current[i];
						num2 = currentIndex[i];
					}
				}
				return num2;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public void Invoke(ref Vector<float> result, Vector<float> current, ref Vector<int> resultIndex, Vector<int> currentIndex)
			{
				Vector<int> condition = Vector.LessThan(result, current);
				Vector<int> vector = Vector.Equals(result, current);
				if (vector != Vector<int>.Zero)
				{
					Vector<float> vector2 = IsNegative(result);
					condition |= vector & Vector.ConditionalSelect(Vector.Equals(vector2, IsNegative(current)), Vector.LessThan(resultIndex, currentIndex), (Vector<int>)vector2);
				}
				result = Vector.ConditionalSelect(condition, result, current);
				resultIndex = Vector.ConditionalSelect(condition, resultIndex, currentIndex);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct IndexOfMinMagnitudeOperator_Single : IIndexOfOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int Invoke(ref float result, float current, int resultIndex, int currentIndex)
			{
				float num = MathF.Abs(result);
				float num2 = MathF.Abs(current);
				if (num == num2)
				{
					bool flag = IsNegative(current);
					if ((IsNegative(result) == flag) ? (currentIndex < resultIndex) : flag)
					{
						result = current;
						return currentIndex;
					}
				}
				else if (num2 < num)
				{
					result = current;
					return currentIndex;
				}
				return resultIndex;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public int Invoke(Vector<float> current, Vector<int> currentIndex)
			{
				float num = current[0];
				float num2 = MathF.Abs(num);
				int num3 = currentIndex[0];
				for (int i = 1; i < Vector<float>.Count; i++)
				{
					float num4 = MathF.Abs(current[i]);
					if (num2 == num4)
					{
						bool flag = IsNegative(current[i]);
						if ((IsNegative(num) == flag) ? (currentIndex[i] < num3) : flag)
						{
							num = current[i];
							num2 = num4;
							num3 = currentIndex[i];
						}
					}
					else if (num4 < num2)
					{
						num = current[i];
						num2 = num4;
						num3 = currentIndex[i];
					}
				}
				return num3;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public void Invoke(ref Vector<float> result, Vector<float> current, ref Vector<int> resultIndex, Vector<int> currentIndex)
			{
				Vector<float> left = Vector.Abs(result);
				Vector<float> right = Vector.Abs(current);
				Vector<int> condition = Vector.LessThan(left, right);
				Vector<int> vector = Vector.Equals(left, right);
				if (vector != Vector<int>.Zero)
				{
					Vector<float> vector2 = IsNegative(result);
					condition |= vector & Vector.ConditionalSelect(Vector.Equals(vector2, IsNegative(current)), Vector.LessThan(resultIndex, currentIndex), (Vector<int>)vector2);
				}
				result = Vector.ConditionalSelect(condition, result, current);
				resultIndex = Vector.ConditionalSelect(condition, resultIndex, currentIndex);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MaxOperator_Single : IBinaryOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public float Invoke(float x, float y)
			{
				if (x != y)
				{
					if (!(y > x))
					{
						return x;
					}
					return y;
				}
				if (!IsNegative(x))
				{
					return x;
				}
				return y;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				return Vector.ConditionalSelect(Vector.Equals(x, y), Vector.ConditionalSelect(IsNegative(x), y, x), Vector.Max(x, y));
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MaxPropagateNaNOperator_Single : IBinaryOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public float Invoke(float x, float y)
			{
				return MathF.Max(x, y);
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				return Vector.ConditionalSelect(Vector.Equals(x, x), Vector.ConditionalSelect(Vector.Equals(y, y), Vector.ConditionalSelect(Vector.Equals(x, y), Vector.ConditionalSelect(IsNegative(x), y, x), Vector.Max(x, y)), y), x);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MaxMagnitudeOperator_Single : IBinaryOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public float Invoke(float x, float y)
			{
				float num = MathF.Abs(x);
				float num2 = MathF.Abs(y);
				if (num2 != num)
				{
					if (!(num > num2))
					{
						return y;
					}
					return x;
				}
				if (!IsNegative(x))
				{
					return x;
				}
				return y;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				Vector<float> left = Vector.Abs(x);
				Vector<float> right = Vector.Abs(y);
				return Vector.ConditionalSelect(Vector.Equals(left, right), Vector.ConditionalSelect(IsNegative(x), y, x), Vector.ConditionalSelect(Vector.GreaterThan(left, right), x, y));
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MaxMagnitudePropagateNaNOperator_Single : IBinaryOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public float Invoke(float x, float y)
			{
				float num = MathF.Abs(x);
				float num2 = MathF.Abs(y);
				if (!(num > num2) && !float.IsNaN(num) && (num != num2 || IsNegative(x)))
				{
					return y;
				}
				return x;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				Vector<float> left = Vector.Abs(x);
				Vector<float> right = Vector.Abs(y);
				return Vector.ConditionalSelect(Vector.Equals(x, x), Vector.ConditionalSelect(Vector.Equals(y, y), Vector.ConditionalSelect(Vector.Equals(left, right), Vector.ConditionalSelect(IsNegative(x), y, x), Vector.ConditionalSelect(Vector.GreaterThan(left, right), x, y)), y), x);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MinOperator_Single : IBinaryOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public float Invoke(float x, float y)
			{
				if (x != y)
				{
					if (!(y < x))
					{
						return x;
					}
					return y;
				}
				if (!IsNegative(y))
				{
					return x;
				}
				return y;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				return Vector.ConditionalSelect(Vector.Equals(x, y), Vector.ConditionalSelect(IsNegative(y), y, x), Vector.Min(x, y));
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MinPropagateNaNOperator_Single : IBinaryOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public float Invoke(float x, float y)
			{
				return MathF.Min(x, y);
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				return Vector.ConditionalSelect(Vector.Equals(x, x), Vector.ConditionalSelect(Vector.Equals(y, y), Vector.ConditionalSelect(Vector.Equals(x, y), Vector.ConditionalSelect(IsNegative(x), x, y), Vector.Min(x, y)), y), x);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MinMagnitudeOperator_Single : IBinaryOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public float Invoke(float x, float y)
			{
				float num = MathF.Abs(x);
				float num2 = MathF.Abs(y);
				if (num2 != num)
				{
					if (!(num2 < num))
					{
						return x;
					}
					return y;
				}
				if (!IsNegative(y))
				{
					return x;
				}
				return y;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				Vector<float> right = Vector.Abs(x);
				Vector<float> left = Vector.Abs(y);
				return Vector.ConditionalSelect(Vector.Equals(left, right), Vector.ConditionalSelect(IsNegative(y), y, x), Vector.ConditionalSelect(Vector.LessThan(left, right), y, x));
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MinMagnitudePropagateNaNOperator_Single : IBinaryOperator
		{
			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public float Invoke(float x, float y)
			{
				float num = MathF.Abs(x);
				float num2 = MathF.Abs(y);
				if (!(num < num2) && !float.IsNaN(num) && (num != num2 || !IsNegative(x)))
				{
					return y;
				}
				return x;
			}

			[MethodImpl(MethodImplOptions.AggressiveInlining)]
			public Vector<float> Invoke(Vector<float> x, Vector<float> y)
			{
				Vector<float> vector = Vector.Abs(x);
				Vector<float> vector2 = Vector.Abs(y);
				return Vector.ConditionalSelect(Vector.Equals(x, x), Vector.ConditionalSelect(Vector.Equals(y, y), Vector.ConditionalSelect(Vector.Equals(vector2, vector), Vector.ConditionalSelect(IsNegative(x), x, y), Vector.ConditionalSelect(Vector.LessThan(vector, vector2), x, y)), y), x);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct NegateOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => true;

			public float Invoke(float x)
			{
				return 0f - x;
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				return -x;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct AddMultiplyOperator_Single : ITernaryOperator
		{
			public float Invoke(float x, float y, float z)
			{
				return (x + y) * z;
			}

			public Vector<float> Invoke(Vector<float> x, Vector<float> y, Vector<float> z)
			{
				return (x + y) * z;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct MultiplyAddOperator_Single : ITernaryOperator
		{
			public float Invoke(float x, float y, float z)
			{
				return x * y + z;
			}

			public Vector<float> Invoke(Vector<float> x, Vector<float> y, Vector<float> z)
			{
				return x * y + z;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct IdentityOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => true;

			public float Invoke(float x)
			{
				return x;
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				return x;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct SquaredOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => true;

			public float Invoke(float x)
			{
				return x * x;
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				return x * x;
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct AbsoluteOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => true;

			public float Invoke(float x)
			{
				return MathF.Abs(x);
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				return Vector.Abs(x);
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct ExpOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => false;

			public float Invoke(float x)
			{
				return MathF.Exp(x);
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				throw new NotSupportedException();
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct SinhOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => false;

			public float Invoke(float x)
			{
				return MathF.Sinh(x);
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				throw new NotSupportedException();
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct CoshOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => false;

			public float Invoke(float x)
			{
				return MathF.Cosh(x);
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				throw new NotSupportedException();
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct TanhOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => false;

			public float Invoke(float x)
			{
				return MathF.Tanh(x);
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				throw new NotSupportedException();
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct LogOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => false;

			public float Invoke(float x)
			{
				return MathF.Log(x);
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				throw new NotSupportedException();
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct Log2Operator_Single : IUnaryOperator
		{
			public bool CanVectorize => false;

			public float Invoke(float x)
			{
				return Log2(x);
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				throw new NotSupportedException();
			}
		}

		[StructLayout(LayoutKind.Sequential, Size = 1)]
		private readonly struct SigmoidOperator_Single : IUnaryOperator
		{
			public bool CanVectorize => false;

			public float Invoke(float x)
			{
				return 1f / (1f + MathF.Exp(0f - x));
			}

			public Vector<float> Invoke(Vector<float> x)
			{
				throw new NotSupportedException();
			}
		}

		private interface IUnaryOperator
		{
			bool CanVectorize { get; }

			float Invoke(float x);

			Vector<float> Invoke(Vector<float> x);
		}

		private interface IBinaryOperator
		{
			float Invoke(float x, float y);

			Vector<float> Invoke(Vector<float> x, Vector<float> y);
		}

		private interface IAggregationOperator : IBinaryOperator
		{
			float IdentityValue { get; }
		}

		private interface ITernaryOperator
		{
			float Invoke(float x, float y, float z);

			Vector<float> Invoke(Vector<float> x, Vector<float> y, Vector<float> z);
		}

		private static readonly int[] s_0through7 = new int[8] { 0, 1, 2, 3, 4, 5, 6, 7 };

		private static ReadOnlySpan<byte> AlignmentByteMask_64x65 => new byte[4160]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255
		};

		private static ReadOnlySpan<ushort> AlignmentUInt16Mask_32x33
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.D44F9DE7C2D0C7FF22B39EBBEAC78570D50737794528B164A7961894A1335B1E_A13;
				if (obj == null)
				{
					obj = new ushort[1056]
					{
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 65535, 65535, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 65535, 65535, 65535, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 0, 0, 0, 0, 0, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0, 0,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0,
						0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 0, 0, 0, 0, 0, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 0, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535
					};
					global::<PrivateImplementationDetails>.D44F9DE7C2D0C7FF22B39EBBEAC78570D50737794528B164A7961894A1335B1E_A13 = (ushort[])obj;
				}
				return new ReadOnlySpan<ushort>((ushort[]?)obj);
			}
		}

		private static ReadOnlySpan<uint> AlignmentUInt32Mask_16x17
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.90BB7C651B4D498B65ACD3AA4A5AF1A326FA517519CF8A40AE2630040EE89138_A14;
				if (obj == null)
				{
					obj = new uint[272]
					{
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u, 0u, 0u,
						0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
						0u, 0u, 4294967295u, 4294967295u, 0u, 0u, 0u, 0u, 0u, 0u,
						0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 4294967295u, 4294967295u,
						4294967295u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
						0u, 0u, 0u, 0u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u, 0u,
						0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u, 0u, 0u, 0u, 0u,
						0u, 0u, 0u, 0u, 0u, 0u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
						0u, 0u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u,
						0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u, 0u, 0u, 0u,
						0u, 0u, 0u, 0u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						0u, 0u, 0u, 0u, 0u, 0u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u, 0u, 0u,
						0u, 0u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u, 0u, 0u, 0u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 0u, 0u, 0u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u, 0u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 0u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u, 4294967295u,
						4294967295u, 4294967295u
					};
					global::<PrivateImplementationDetails>.90BB7C651B4D498B65ACD3AA4A5AF1A326FA517519CF8A40AE2630040EE89138_A14 = (uint[])obj;
				}
				return new ReadOnlySpan<uint>((uint[]?)obj);
			}
		}

		private static ReadOnlySpan<ulong> AlignmentUInt64Mask_8x9
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.1ED5EF4A0FD6513C9BE9C29F8C757AFAFF7B4903984F162562F58C0D5E71BA22_A15;
				if (obj == null)
				{
					obj = new ulong[72]
					{
						18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 0uL,
						0uL, 0uL, 0uL, 0uL, 0uL, 0uL, 18446744073709551615uL, 18446744073709551615uL, 0uL, 0uL,
						0uL, 0uL, 0uL, 0uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 0uL, 0uL, 0uL,
						0uL, 0uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 0uL, 0uL, 0uL, 0uL,
						18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 0uL, 0uL, 0uL, 18446744073709551615uL, 18446744073709551615uL,
						18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 0uL, 0uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL,
						18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 0uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL, 18446744073709551615uL,
						18446744073709551615uL, 18446744073709551615uL
					};
					global::<PrivateImplementationDetails>.1ED5EF4A0FD6513C9BE9C29F8C757AFAFF7B4903984F162562F58C0D5E71BA22_A15 = (ulong[])obj;
				}
				return new ReadOnlySpan<ulong>((ulong[]?)obj);
			}
		}

		private static ReadOnlySpan<byte> RemainderByteMask_64x65 => new byte[4160]
		{
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 0, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			0, 0, 0, 0, 0, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 0, 0, 0, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 0, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0
		};

		private static ReadOnlySpan<ushort> RemainderUInt16Mask_32x33
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.9BC2B021613E87C91695FC876416B1363DB7523322029CCB85E5ECC0AA4379AD_A13;
				if (obj == null)
				{
					obj = new ushort[1056]
					{
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 65535, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 65535, 65535, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 65535, 65535, 65535, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 65535, 65535, 65535, 65535,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 65535, 65535, 65535,
						65535, 65535, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0,
						0, 0, 0, 0, 0, 0, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						0, 0, 0, 0, 0, 0, 0, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 0, 0, 0, 0, 0, 0, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 0, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 0, 0, 0, 0,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 0, 0,
						0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						0, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 0, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535, 65535,
						65535, 65535, 65535, 65535, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
						0, 0, 0, 0, 0, 0
					};
					global::<PrivateImplementationDetails>.9BC2B021613E87C91695FC876416B1363DB7523322029CCB85E5ECC0AA4379AD_A13 = (ushort[])obj;
				}
				return new ReadOnlySpan<ushort>((ushort[]?)obj);
			}
		}

		private static ReadOnlySpan<uint> RemainderUInt32Mask_16x17
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.BB5F15BAC654FB0B58C167DEE72B17E14978ABB822EC64398678D84AB17093BD_A14;
				if (obj == null)
				{
					obj = new uint[272]
					{
						0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u,
						0u, 0u

BepInEx/core/System.Numerics.Vectors.dll

Decompiled 2 weeks ago
using System;
using System.Diagnostics;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Numerics.Vectors.dll")]
[assembly: AssemblyDescription("System.Numerics.Vectors.dll")]
[assembly: AssemblyDefaultAlias("System.Numerics.Vectors.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: SecurityCritical]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[assembly: TypeForwardedTo(typeof(Matrix3x2))]
[assembly: TypeForwardedTo(typeof(Matrix4x4))]
[assembly: TypeForwardedTo(typeof(Plane))]
[assembly: TypeForwardedTo(typeof(Quaternion))]
[assembly: TypeForwardedTo(typeof(Vector))]
[assembly: TypeForwardedTo(typeof(Vector<>))]
[assembly: TypeForwardedTo(typeof(Vector2))]
[assembly: TypeForwardedTo(typeof(Vector3))]
[assembly: TypeForwardedTo(typeof(Vector4))]
[module: UnverifiableCode]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}

BepInEx/core/System.Reflection.Metadata.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel;
using System.Configuration.Assemblies;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.IO.MemoryMappedFiles;
using System.Linq;
using System.Reflection;
using System.Reflection.Internal;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using FxResources.System.Reflection.Metadata;
using Microsoft.CodeAnalysis;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.Reflection.Metadata.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001004b86c4cb78549b34bab61a3b1800e23bfeb5b3ec390074041536a7e3cbd97f5f04cf0f857155a8928eaa29ebfd11cfbbad3ba70efea7bda3226c6a8d370a4cd303f714486b6ebc225985a638471e6ef571cc92a4613c00b8fa65d61ccee0cbe5f36330c9a01f4183559f1bef24cc2917c6d913e3a541333a1d05d9bed22b38cb")]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Reflection.Metadata")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("This package provides a low-level .NET (ECMA-335) metadata reader and writer. It's geared for performance and is the ideal choice for building higher-level libraries that intend to provide their own object model, such as compilers. The metadata format is defined by the ECMA-335 - Common Language Infrastructure (CLI) specification.\r\n\r\nThe System.Reflection.Metadata library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")]
[assembly: AssemblyFileVersion("9.0.24.52809")]
[assembly: AssemblyInformationalVersion("9.0.0+9d5a6a9aa463d6d10b0b0ba6d5982cc82f363dc3")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Reflection.Metadata")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("9.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(true)]
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
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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;
		}
	}
}
internal static class Interop
{
	internal static class Libraries
	{
		internal const string Activeds = "activeds.dll";

		internal const string Advapi32 = "advapi32.dll";

		internal const string Authz = "authz.dll";

		internal const string BCrypt = "BCrypt.dll";

		internal const string Credui = "credui.dll";

		internal const string Crypt32 = "crypt32.dll";

		internal const string CryptUI = "cryptui.dll";

		internal const string Dsrole = "dsrole.dll";

		internal const string Gdi32 = "gdi32.dll";

		internal const string HttpApi = "httpapi.dll";

		internal const string IpHlpApi = "iphlpapi.dll";

		internal const string Kernel32 = "kernel32.dll";

		internal const string Logoncli = "logoncli.dll";

		internal const string Mswsock = "mswsock.dll";

		internal const string NCrypt = "ncrypt.dll";

		internal const string Netapi32 = "netapi32.dll";

		internal const string Netutils = "netutils.dll";

		internal const string NtDll = "ntdll.dll";

		internal const string Odbc32 = "odbc32.dll";

		internal const string Ole32 = "ole32.dll";

		internal const string OleAut32 = "oleaut32.dll";

		internal const string Pdh = "pdh.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 Wevtapi = "wevtapi.dll";

		internal const string WinHttp = "winhttp.dll";

		internal const string WinMM = "winmm.dll";

		internal const string Wkscli = "wkscli.dll";

		internal const string Wldap32 = "wldap32.dll";

		internal const string Ws2_32 = "ws2_32.dll";

		internal const string Wtsapi32 = "wtsapi32.dll";

		internal const string CompressionNative = "System.IO.Compression.Native";

		internal const string GlobalizationNative = "System.Globalization.Native";

		internal const string MsQuic = "msquic.dll";

		internal const string HostPolicy = "hostpolicy";

		internal const string Ucrtbase = "ucrtbase.dll";

		internal const string Xolehlp = "xolehlp.dll";

		internal const string Comdlg32 = "comdlg32.dll";

		internal const string Gdiplus = "gdiplus.dll";

		internal const string Oleaut32 = "oleaut32.dll";

		internal const string Winspool = "winspool.drv";
	}

	internal static class Kernel32
	{
		[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
		[LibraryImport("kernel32.dll", SetLastError = true)]
		internal unsafe static extern int ReadFile(SafeHandle handle, byte* bytes, int numBytesToRead, out int numBytesRead, IntPtr mustBeZero);
	}
}
namespace FxResources.System.Reflection.Metadata
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> bytes, Span<char> chars, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < bytes.Length; i++)
			{
				ToCharsBuffer(bytes[i], chars, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(chars, bytes, out charsProcessed);
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> chars, Span<byte> bytes, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < bytes.Length)
			{
				num3 = FromChar(chars[num + 1]);
				num4 = FromChar(chars[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				bytes[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class Obsoletions
	{
		internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}";

		internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.";

		internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001";

		internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used.";

		internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002";

		internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime.";

		internal const string CodeAccessSecurityDiagId = "SYSLIB0003";

		internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported.";

		internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004";

		internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported.";

		internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005";

		internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadAbortDiagId = "SYSLIB0006";

		internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported.";

		internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007";

		internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException.";

		internal const string CreatePdbGeneratorDiagId = "SYSLIB0008";

		internal const string AuthenticationManagerMessage = "AuthenticationManager is not supported. Methods will no-op or throw PlatformNotSupportedException.";

		internal const string AuthenticationManagerDiagId = "SYSLIB0009";

		internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException.";

		internal const string RemotingApisDiagId = "SYSLIB0010";

		internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.";

		internal const string BinaryFormatterDiagId = "SYSLIB0011";

		internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead.";

		internal const string CodeBaseDiagId = "SYSLIB0012";

		internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead.";

		internal const string EscapeUriStringDiagId = "SYSLIB0013";

		internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.";

		internal const string WebRequestDiagId = "SYSLIB0014";

		internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+.";

		internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015";

		internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations.";

		internal const string GetContextInfoDiagId = "SYSLIB0016";

		internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException.";

		internal const string StrongNameKeyPairDiagId = "SYSLIB0017";

		internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException.";

		internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018";

		internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException.";

		internal const string RuntimeEnvironmentDiagId = "SYSLIB0019";

		internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull.";

		internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020";

		internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead.";

		internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021";

		internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead.";

		internal const string RijndaelDiagId = "SYSLIB0022";

		internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.";

		internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023";

		internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception.";

		internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024";

		internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+.";

		internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025";

		internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use X509CertificateLoader to create a new certificate.";

		internal const string X509CertificateImmutableDiagId = "SYSLIB0026";

		internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey.";

		internal const string PublicKeyPropertyDiagId = "SYSLIB0027";

		internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.";

		internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028";

		internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported.";

		internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029";

		internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter.";

		internal const string UseManagedSha1DiagId = "SYSLIB0030";

		internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1.";

		internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031";

		internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored.";

		internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032";

		internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead.";

		internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033";

		internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead.";

		internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034";

		internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner.";

		internal const string SignerInfoCounterSigDiagId = "SYSLIB0035";

		internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.";

		internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036";

		internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported.";

		internal const string AssemblyNameMembersDiagId = "SYSLIB0037";

		internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information.";

		internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038";

		internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults.";

		internal const string TlsVersion10and11DiagId = "SYSLIB0039";

		internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code.";

		internal const string EncryptionPolicyDiagId = "SYSLIB0040";

		internal const string Rfc2898OutdatedCtorMessage = "The default hash algorithm and iteration counts in Rfc2898DeriveBytes constructors are outdated and insecure. Use a constructor that accepts the hash algorithm and the number of iterations.";

		internal const string Rfc2898OutdatedCtorDiagId = "SYSLIB0041";

		internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys.";

		internal const string EccXmlExportImportDiagId = "SYSLIB0042";

		internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead.";

		internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043";

		internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.";

		internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044";

		internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead.";

		internal const string CryptoStringFactoryDiagId = "SYSLIB0045";

		internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code.";

		internal const string ControlledExecutionRunDiagId = "SYSLIB0046";

		internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution.";

		internal const string XmlSecureResolverDiagId = "SYSLIB0047";

		internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead.";

		internal const string RsaEncryptDecryptDiagId = "SYSLIB0048";

		internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties.";

		internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049";

		internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used.";

		internal const string LegacyFormatterDiagId = "SYSLIB0050";

		internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code.";

		internal const string LegacyFormatterImplDiagId = "SYSLIB0051";

		internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported.";

		internal const string RegexExtensibilityDiagId = "SYSLIB0052";

		internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size.";

		internal const string AesGcmTagConstructorDiagId = "SYSLIB0053";

		internal const string ThreadVolatileReadWriteMessage = "Thread.VolatileRead and Thread.VolatileWrite are obsolete. Use Volatile.Read or Volatile.Write respectively instead.";

		internal const string ThreadVolatileReadWriteDiagId = "SYSLIB0054";

		internal const string ArmIntrinsicPerformsUnsignedOperationMessage = "The underlying hardware instruction does not perform a signed saturate narrowing operation, and it always returns an unsigned result. Use the unsigned overload instead.";

		internal const string ArmIntrinsicPerformsUnsignedOperationDiagId = "SYSLIB0055";

		internal const string LoadFromHashAlgorithmMessage = "LoadFrom with a custom AssemblyHashAlgorithm is obsolete. Use overloads without an AssemblyHashAlgorithm.";

		internal const string LoadFromHashAlgorithmDiagId = "SYSLIB0056";

		internal const string X509CtorCertDataObsoleteMessage = "Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates.";

		internal const string X509CtorCertDataObsoleteDiagId = "SYSLIB0057";
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ImageTooSmall => GetResourceString("ImageTooSmall");

		internal static string InvalidCorHeaderSize => GetResourceString("InvalidCorHeaderSize");

		internal static string InvalidHandle => GetResourceString("InvalidHandle");

		internal static string UnexpectedHandleKind => GetResourceString("UnexpectedHandleKind");

		internal static string UnexpectedOpCode => GetResourceString("UnexpectedOpCode");

		internal static string InvalidLocalSignatureToken => GetResourceString("InvalidLocalSignatureToken");

		internal static string InvalidMetadataSectionSpan => GetResourceString("InvalidMetadataSectionSpan");

		internal static string InvalidMethodHeader1 => GetResourceString("InvalidMethodHeader1");

		internal static string InvalidMethodHeader2 => GetResourceString("InvalidMethodHeader2");

		internal static string InvalidPESignature => GetResourceString("InvalidPESignature");

		internal static string InvalidSehHeader => GetResourceString("InvalidSehHeader");

		internal static string InvalidToken => GetResourceString("InvalidToken");

		internal static string MetadataImageDoesNotRepresentAnAssembly => GetResourceString("MetadataImageDoesNotRepresentAnAssembly");

		internal static string StandaloneDebugMetadataImageDoesNotContainModuleTable => GetResourceString("StandaloneDebugMetadataImageDoesNotContainModuleTable");

		internal static string PEImageNotAvailable => GetResourceString("PEImageNotAvailable");

		internal static string MissingDataDirectory => GetResourceString("MissingDataDirectory");

		internal static string NotMetadataHeapHandle => GetResourceString("NotMetadataHeapHandle");

		internal static string NotMetadataTableOrUserStringHandle => GetResourceString("NotMetadataTableOrUserStringHandle");

		internal static string SectionTooSmall => GetResourceString("SectionTooSmall");

		internal static string StreamMustSupportReadAndSeek => GetResourceString("StreamMustSupportReadAndSeek");

		internal static string UnknownFileFormat => GetResourceString("UnknownFileFormat");

		internal static string UnknownPEMagicValue => GetResourceString("UnknownPEMagicValue");

		internal static string MetadataTableNotSorted => GetResourceString("MetadataTableNotSorted");

		internal static string ModuleTableInvalidNumberOfRows => GetResourceString("ModuleTableInvalidNumberOfRows");

		internal static string UnknownTables => GetResourceString("UnknownTables");

		internal static string IllegalTablesInCompressedMetadataStream => GetResourceString("IllegalTablesInCompressedMetadataStream");

		internal static string TableRowCountSpaceTooSmall => GetResourceString("TableRowCountSpaceTooSmall");

		internal static string OutOfBoundsRead => GetResourceString("OutOfBoundsRead");

		internal static string OutOfBoundsWrite => GetResourceString("OutOfBoundsWrite");

		internal static string MetadataHeaderTooSmall => GetResourceString("MetadataHeaderTooSmall");

		internal static string MetadataSignature => GetResourceString("MetadataSignature");

		internal static string NotEnoughSpaceForVersionString => GetResourceString("NotEnoughSpaceForVersionString");

		internal static string StreamHeaderTooSmall => GetResourceString("StreamHeaderTooSmall");

		internal static string NotEnoughSpaceForStreamHeaderName => GetResourceString("NotEnoughSpaceForStreamHeaderName");

		internal static string NotEnoughSpaceForStringStream => GetResourceString("NotEnoughSpaceForStringStream");

		internal static string NotEnoughSpaceForBlobStream => GetResourceString("NotEnoughSpaceForBlobStream");

		internal static string NotEnoughSpaceForGUIDStream => GetResourceString("NotEnoughSpaceForGUIDStream");

		internal static string NotEnoughSpaceForMetadataStream => GetResourceString("NotEnoughSpaceForMetadataStream");

		internal static string InvalidMetadataStreamFormat => GetResourceString("InvalidMetadataStreamFormat");

		internal static string MetadataTablesTooSmall => GetResourceString("MetadataTablesTooSmall");

		internal static string MetadataTableHeaderTooSmall => GetResourceString("MetadataTableHeaderTooSmall");

		internal static string WinMDMissingMscorlibRef => GetResourceString("WinMDMissingMscorlibRef");

		internal static string UnexpectedStreamEnd => GetResourceString("UnexpectedStreamEnd");

		internal static string InvalidMethodRva => GetResourceString("InvalidMethodRva");

		internal static string CantGetOffsetForVirtualHeapHandle => GetResourceString("CantGetOffsetForVirtualHeapHandle");

		internal static string InvalidNumberOfSections => GetResourceString("InvalidNumberOfSections");

		internal static string InvalidSignature => GetResourceString("InvalidSignature");

		internal static string PEImageDoesNotHaveMetadata => GetResourceString("PEImageDoesNotHaveMetadata");

		internal static string InvalidCodedIndex => GetResourceString("InvalidCodedIndex");

		internal static string InvalidCompressedInteger => GetResourceString("InvalidCompressedInteger");

		internal static string InvalidDocumentName => GetResourceString("InvalidDocumentName");

		internal static string RowIdOrHeapOffsetTooLarge => GetResourceString("RowIdOrHeapOffsetTooLarge");

		internal static string EnCMapNotSorted => GetResourceString("EnCMapNotSorted");

		internal static string InvalidSerializedString => GetResourceString("InvalidSerializedString");

		internal static string StreamTooLarge => GetResourceString("StreamTooLarge");

		internal static string ImageTooSmallOrContainsInvalidOffsetOrCount => GetResourceString("ImageTooSmallOrContainsInvalidOffsetOrCount");

		internal static string MetadataStringDecoderEncodingMustBeUtf8 => GetResourceString("MetadataStringDecoderEncodingMustBeUtf8");

		internal static string InvalidConstantValue => GetResourceString("InvalidConstantValue");

		internal static string InvalidConstantValueOfType => GetResourceString("InvalidConstantValueOfType");

		internal static string InvalidImportDefinitionKind => GetResourceString("InvalidImportDefinitionKind");

		internal static string ValueTooLarge => GetResourceString("ValueTooLarge");

		internal static string BlobTooLarge => GetResourceString("BlobTooLarge");

		internal static string InvalidTypeSize => GetResourceString("InvalidTypeSize");

		internal static string HandleBelongsToFutureGeneration => GetResourceString("HandleBelongsToFutureGeneration");

		internal static string InvalidRowCount => GetResourceString("InvalidRowCount");

		internal static string InvalidEntryPointToken => GetResourceString("InvalidEntryPointToken");

		internal static string TooManySubnamespaces => GetResourceString("TooManySubnamespaces");

		internal static string TooManyExceptionRegions => GetResourceString("TooManyExceptionRegions");

		internal static string SequencePointValueOutOfRange => GetResourceString("SequencePointValueOutOfRange");

		internal static string InvalidDirectoryRVA => GetResourceString("InvalidDirectoryRVA");

		internal static string InvalidDirectorySize => GetResourceString("InvalidDirectorySize");

		internal static string InvalidDebugDirectoryEntryCharacteristics => GetResourceString("InvalidDebugDirectoryEntryCharacteristics");

		internal static string UnexpectedCodeViewDataSignature => GetResourceString("UnexpectedCodeViewDataSignature");

		internal static string UnexpectedEmbeddedPortablePdbDataSignature => GetResourceString("UnexpectedEmbeddedPortablePdbDataSignature");

		internal static string InvalidPdbChecksumDataFormat => GetResourceString("InvalidPdbChecksumDataFormat");

		internal static string UnexpectedSignatureHeader => GetResourceString("UnexpectedSignatureHeader");

		internal static string UnexpectedSignatureHeader2 => GetResourceString("UnexpectedSignatureHeader2");

		internal static string NotTypeDefOrRefHandle => GetResourceString("NotTypeDefOrRefHandle");

		internal static string UnexpectedSignatureTypeCode => GetResourceString("UnexpectedSignatureTypeCode");

		internal static string SignatureTypeSequenceMustHaveAtLeastOneElement => GetResourceString("SignatureTypeSequenceMustHaveAtLeastOneElement");

		internal static string NotTypeDefOrRefOrSpecHandle => GetResourceString("NotTypeDefOrRefOrSpecHandle");

		internal static string UnexpectedDebugDirectoryType => GetResourceString("UnexpectedDebugDirectoryType");

		internal static string HeapSizeLimitExceeded => GetResourceString("HeapSizeLimitExceeded");

		internal static string BuilderMustAligned => GetResourceString("BuilderMustAligned");

		internal static string BuilderAlreadyLinked => GetResourceString("BuilderAlreadyLinked");

		internal static string ReturnedBuilderSizeTooSmall => GetResourceString("ReturnedBuilderSizeTooSmall");

		internal static string SignatureNotVarArg => GetResourceString("SignatureNotVarArg");

		internal static string LabelDoesntBelongToBuilder => GetResourceString("LabelDoesntBelongToBuilder");

		internal static string ControlFlowBuilderNotAvailable => GetResourceString("ControlFlowBuilderNotAvailable");

		internal static string BaseReaderMustBeFullMetadataReader => GetResourceString("BaseReaderMustBeFullMetadataReader");

		internal static string ModuleAlreadyAdded => GetResourceString("ModuleAlreadyAdded");

		internal static string AssemblyAlreadyAdded => GetResourceString("AssemblyAlreadyAdded");

		internal static string ExpectedListOfSize => GetResourceString("ExpectedListOfSize");

		internal static string ExpectedArrayOfSize => GetResourceString("ExpectedArrayOfSize");

		internal static string ExpectedNonEmptyList => GetResourceString("ExpectedNonEmptyList");

		internal static string ExpectedNonEmptyArray => GetResourceString("ExpectedNonEmptyArray");

		internal static string ExpectedNonEmptyString => GetResourceString("ExpectedNonEmptyString");

		internal static string ReadersMustBeDeltaReaders => GetResourceString("ReadersMustBeDeltaReaders");

		internal static string SignatureProviderReturnedInvalidSignature => GetResourceString("SignatureProviderReturnedInvalidSignature");

		internal static string UnknownSectionName => GetResourceString("UnknownSectionName");

		internal static string HashTooShort => GetResourceString("HashTooShort");

		internal static string UnexpectedArrayLength => GetResourceString("UnexpectedArrayLength");

		internal static string ValueMustBeMultiple => GetResourceString("ValueMustBeMultiple");

		internal static string MustNotReturnNull => GetResourceString("MustNotReturnNull");

		internal static string MetadataVersionTooLong => GetResourceString("MetadataVersionTooLong");

		internal static string RowCountMustBeZero => GetResourceString("RowCountMustBeZero");

		internal static string RowCountOutOfRange => GetResourceString("RowCountOutOfRange");

		internal static string SizeMismatch => GetResourceString("SizeMismatch");

		internal static string DataTooBig => GetResourceString("DataTooBig");

		internal static string UnsupportedFormatVersion => GetResourceString("UnsupportedFormatVersion");

		internal static string DistanceBetweenInstructionAndLabelTooBig => GetResourceString("DistanceBetweenInstructionAndLabelTooBig");

		internal static string LabelNotMarked => GetResourceString("LabelNotMarked");

		internal static string MethodHasNoExceptionRegions => GetResourceString("MethodHasNoExceptionRegions");

		internal static string InvalidExceptionRegionBounds => GetResourceString("InvalidExceptionRegionBounds");

		internal static string UnexpectedValue => GetResourceString("UnexpectedValue");

		internal static string UnexpectedValueUnknownType => GetResourceString("UnexpectedValueUnknownType");

		internal static string SwitchInstructionEncoderTooFewBranches => GetResourceString("SwitchInstructionEncoderTooFewBranches");

		internal static string SwitchInstructionEncoderTooManyBranches => GetResourceString("SwitchInstructionEncoderTooManyBranches");

		internal static string Argument_InvalidTypeName => GetResourceString("Argument_InvalidTypeName");

		internal static string InvalidOperation_MaxNodesExceeded => GetResourceString("InvalidOperation_MaxNodesExceeded");

		internal static string Argument_HasToBeArrayClass => GetResourceString("Argument_HasToBeArrayClass");

		internal static string InvalidOperation_NotGenericType => GetResourceString("InvalidOperation_NotGenericType");

		internal static string InvalidOperation_NotNestedType => GetResourceString("InvalidOperation_NotNestedType");

		internal static string InvalidOperation_NoElement => GetResourceString("InvalidOperation_NoElement");

		internal static string InvalidAssemblyName => GetResourceString("InvalidAssemblyName");

		internal static string Arg_NotSimpleTypeName => GetResourceString("Arg_NotSimpleTypeName");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider? provider, string resourceFormat, params object?[]? args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string? EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type? StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Text
{
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string? s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string? s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public unsafe void Append(char* value, int length)
		{
			if (_pos > _chars.Length - length)
			{
				Grow(length);
			}
			Span<char> span = _chars.Slice(_pos, length);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = *(value++);
			}
			_pos += length;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
}
namespace System.Reflection
{
	internal static class BlobUtilities
	{
		public const int SizeOfSerializedDecimal = 13;

		public const int SizeOfGuid = 16;

		public static void WriteBytes(this byte[] buffer, int start, byte value, int byteCount)
		{
			new Span<byte>(buffer, start, byteCount).Fill(value);
		}

		public unsafe static void WriteDouble(this byte[] buffer, int start, double value)
		{
			buffer.WriteUInt64(start, *(ulong*)(&value));
		}

		public unsafe static void WriteSingle(this byte[] buffer, int start, float value)
		{
			buffer.WriteUInt32(start, *(uint*)(&value));
		}

		public static void WriteByte(this byte[] buffer, int start, byte value)
		{
			buffer[start] = value;
		}

		public static void WriteUInt16(this byte[] buffer, int start, ushort value)
		{
			Unsafe.WriteUnaligned(ref buffer[start], (!BitConverter.IsLittleEndian) ? BinaryPrimitives.ReverseEndianness(value) : value);
		}

		public static void WriteUInt16BE(this byte[] buffer, int start, ushort value)
		{
			Unsafe.WriteUnaligned(ref buffer[start], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value);
		}

		public static void WriteUInt32BE(this byte[] buffer, int start, uint value)
		{
			Unsafe.WriteUnaligned(ref buffer[start], BitConverter.IsLittleEndian ? BinaryPrimitives.ReverseEndianness(value) : value);
		}

		public static void WriteUInt32(this byte[] buffer, int start, uint value)
		{
			Unsafe.WriteUnaligned(ref buffer[start], (!BitConverter.IsLittleEndian) ? BinaryPrimitives.ReverseEndianness(value) : value);
		}

		public static void WriteUInt64(this byte[] buffer, int start, ulong value)
		{
			Unsafe.WriteUnaligned(ref buffer[start], (!BitConverter.IsLittleEndian) ? BinaryPrimitives.ReverseEndianness(value) : value);
		}

		public static void WriteDecimal(this byte[] buffer, int start, decimal value)
		{
			value.GetBits(out var isNegative, out var scale, out var low, out var mid, out var high);
			buffer.WriteByte(start, (byte)(scale | (isNegative ? 128u : 0u)));
			buffer.WriteUInt32(start + 1, low);
			buffer.WriteUInt32(start + 5, mid);
			buffer.WriteUInt32(start + 9, high);
		}

		public unsafe static void WriteGuid(this byte[] buffer, int start, Guid value)
		{
			fixed (byte* ptr2 = &buffer[start])
			{
				byte* ptr = (byte*)(&value);
				uint num = *(uint*)ptr;
				*ptr2 = (byte)num;
				ptr2[1] = (byte)(num >> 8);
				ptr2[2] = (byte)(num >> 16);
				ptr2[3] = (byte)(num >> 24);
				ushort num2 = *(ushort*)(ptr + 4);
				ptr2[4] = (byte)num2;
				ptr2[5] = (byte)(num2 >> 8);
				ushort num3 = *(ushort*)(ptr + 6);
				ptr2[6] = (byte)num3;
				ptr2[7] = (byte)(num3 >> 8);
				ptr2[8] = ptr[8];
				ptr2[9] = ptr[9];
				ptr2[10] = ptr[10];
				ptr2[11] = ptr[11];
				ptr2[12] = ptr[12];
				ptr2[13] = ptr[13];
				ptr2[14] = ptr[14];
				ptr2[15] = ptr[15];
			}
		}

		public unsafe static void WriteUTF8(this byte[] buffer, int start, char* charPtr, int charCount, int byteCount, bool allowUnpairedSurrogates)
		{
			char* ptr = charPtr + charCount;
			fixed (byte* ptr2 = &buffer[0])
			{
				byte* ptr3 = ptr2 + start;
				if (byteCount == charCount)
				{
					while (charPtr < ptr)
					{
						*(ptr3++) = (byte)(*(charPtr++));
					}
					return;
				}
				while (charPtr < ptr)
				{
					char c = *(charPtr++);
					if (c < '\u0080')
					{
						*(ptr3++) = (byte)c;
						continue;
					}
					if (c < 'ࠀ')
					{
						*ptr3 = (byte)(((uint)((int)c >> 6) & 0x1Fu) | 0xC0u);
						ptr3[1] = (byte)((c & 0x3Fu) | 0x80u);
						ptr3 += 2;
						continue;
					}
					if (IsSurrogateChar(c))
					{
						if (IsHighSurrogateChar(c) && charPtr < ptr && IsLowSurrogateChar(*charPtr))
						{
							char num = c;
							int num2 = *(charPtr++);
							int num3 = (num - 55296 << 10) + num2 - 56320 + 65536;
							*ptr3 = (byte)(((uint)(num3 >> 18) & 7u) | 0xF0u);
							ptr3[1] = (byte)(((uint)(num3 >> 12) & 0x3Fu) | 0x80u);
							ptr3[2] = (byte)(((uint)(num3 >> 6) & 0x3Fu) | 0x80u);
							ptr3[3] = (byte)(((uint)num3 & 0x3Fu) | 0x80u);
							ptr3 += 4;
							continue;
						}
						if (!allowUnpairedSurrogates)
						{
							c = '\ufffd';
						}
					}
					*ptr3 = (byte)(((uint)((int)c >> 12) & 0xFu) | 0xE0u);
					ptr3[1] = (byte)(((uint)((int)c >> 6) & 0x3Fu) | 0x80u);
					ptr3[2] = (byte)((c & 0x3Fu) | 0x80u);
					ptr3 += 3;
				}
			}
		}

		internal unsafe static int GetUTF8ByteCount(string str)
		{
			fixed (char* str2 = str)
			{
				return GetUTF8ByteCount(str2, str.Length);
			}
		}

		internal unsafe static int GetUTF8ByteCount(char* str, int charCount)
		{
			char* remainder;
			return GetUTF8ByteCount(str, charCount, int.MaxValue, out remainder);
		}

		internal unsafe static int GetUTF8ByteCount(char* str, int charCount, int byteLimit, out char* remainder)
		{
			char* ptr = str + charCount;
			char* ptr2 = str;
			int num = 0;
			while (ptr2 < ptr)
			{
				char c = *(ptr2++);
				int num2;
				if (c < '\u0080')
				{
					num2 = 1;
				}
				else if (c < 'ࠀ')
				{
					num2 = 2;
				}
				else if (IsHighSurrogateChar(c) && ptr2 < ptr && IsLowSurrogateChar(*ptr2))
				{
					num2 = 4;
					ptr2++;
				}
				else
				{
					num2 = 3;
				}
				if (num + num2 > byteLimit)
				{
					ptr2 -= ((num2 < 4) ? 1 : 2);
					break;
				}
				num += num2;
			}
			remainder = ptr2;
			return num;
		}

		internal static bool IsSurrogateChar(int c)
		{
			return (uint)(c - 55296) <= 2047u;
		}

		internal static bool IsHighSurrogateChar(int c)
		{
			return (uint)(c - 55296) <= 1023u;
		}

		internal static bool IsLowSurrogateChar(int c)
		{
			return (uint)(c - 56320) <= 1023u;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static void ValidateRange(int bufferLength, int start, int byteCount, string byteCountParameterName)
		{
			if (start < 0 || start > bufferLength)
			{
				Throw.ArgumentOutOfRange("start");
			}
			if (byteCount < 0 || byteCount > bufferLength - start)
			{
				Throw.ArgumentOutOfRange(byteCountParameterName);
			}
		}

		internal static int GetUserStringByteLength(int characterCount)
		{
			return characterCount * 2 + 1;
		}

		internal static byte GetUserStringTrailingByte(string str)
		{
			foreach (char c in str)
			{
				if (c >= '\u007f')
				{
					return 1;
				}
				switch (c)
				{
				case '\u0001':
				case '\u0002':
				case '\u0003':
				case '\u0004':
				case '\u0005':
				case '\u0006':
				case '\a':
				case '\b':
				case '\u000e':
				case '\u000f':
				case '\u0010':
				case '\u0011':
				case '\u0012':
				case '\u0013':
				case '\u0014':
				case '\u0015':
				case '\u0016':
				case '\u0017':
				case '\u0018':
				case '\u0019':
				case '\u001a':
				case '\u001b':
				case '\u001c':
				case '\u001d':
				case '\u001e':
				case '\u001f':
				case '\'':
				case '-':
					return 1;
				}
			}
			return 0;
		}
	}
	internal static class Throw
	{
		[DoesNotReturn]
		internal static void InvalidCast()
		{
			throw new InvalidCastException();
		}

		[DoesNotReturn]
		internal static void InvalidArgument(string message, string parameterName)
		{
			throw new ArgumentException(message, parameterName);
		}

		[DoesNotReturn]
		internal static void InvalidArgument_OffsetForVirtualHeapHandle()
		{
			throw new ArgumentException(System.SR.CantGetOffsetForVirtualHeapHandle, "handle");
		}

		[DoesNotReturn]
		internal static Exception InvalidArgument_UnexpectedHandleKind(HandleKind kind)
		{
			throw new ArgumentException(System.SR.Format(System.SR.UnexpectedHandleKind, kind));
		}

		[DoesNotReturn]
		internal static Exception InvalidArgument_Handle(string parameterName)
		{
			throw new ArgumentException(System.SR.InvalidHandle, parameterName);
		}

		[DoesNotReturn]
		internal static void SignatureNotVarArg()
		{
			throw new InvalidOperationException(System.SR.SignatureNotVarArg);
		}

		[DoesNotReturn]
		internal static void ControlFlowBuilderNotAvailable()
		{
			throw new InvalidOperationException(System.SR.ControlFlowBuilderNotAvailable);
		}

		[DoesNotReturn]
		internal static void InvalidOperationBuilderAlreadyLinked()
		{
			throw new InvalidOperationException(System.SR.BuilderAlreadyLinked);
		}

		[DoesNotReturn]
		internal static void InvalidOperation(string message)
		{
			throw new InvalidOperationException(message);
		}

		[DoesNotReturn]
		internal static void InvalidOperation_LabelNotMarked(int id)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.LabelNotMarked, id));
		}

		[DoesNotReturn]
		internal static void LabelDoesntBelongToBuilder(string parameterName)
		{
			throw new ArgumentException(System.SR.LabelDoesntBelongToBuilder, parameterName);
		}

		[DoesNotReturn]
		internal static void HeapHandleRequired()
		{
			throw new ArgumentException(System.SR.NotMetadataHeapHandle, "handle");
		}

		[DoesNotReturn]
		internal static void EntityOrUserStringHandleRequired()
		{
			throw new ArgumentException(System.SR.NotMetadataTableOrUserStringHandle, "handle");
		}

		[DoesNotReturn]
		internal static void InvalidToken()
		{
			throw new ArgumentException(System.SR.InvalidToken, "token");
		}

		[DoesNotReturn]
		internal static void ArgumentNull(string parameterName)
		{
			throw new ArgumentNullException(parameterName);
		}

		[DoesNotReturn]
		internal static void ArgumentEmptyString(string parameterName)
		{
			throw new ArgumentException(System.SR.ExpectedNonEmptyString, parameterName);
		}

		[DoesNotReturn]
		internal static void ArgumentEmptyArray(string parameterName)
		{
			throw new ArgumentException(System.SR.ExpectedNonEmptyArray, parameterName);
		}

		[DoesNotReturn]
		internal static void ValueArgumentNull()
		{
			throw new ArgumentNullException("value");
		}

		[DoesNotReturn]
		internal static void BuilderArgumentNull()
		{
			throw new ArgumentNullException("builder");
		}

		[DoesNotReturn]
		internal static void ArgumentOutOfRange(string parameterName)
		{
			throw new ArgumentOutOfRangeException(parameterName);
		}

		[DoesNotReturn]
		internal static void ArgumentOutOfRange(string parameterName, string message)
		{
			throw new ArgumentOutOfRangeException(parameterName, message);
		}

		[DoesNotReturn]
		internal static void BlobTooLarge(string parameterName)
		{
			throw new ArgumentOutOfRangeException(parameterName, System.SR.BlobTooLarge);
		}

		[DoesNotReturn]
		internal static void IndexOutOfRange()
		{
			throw new ArgumentOutOfRangeException("index");
		}

		[DoesNotReturn]
		internal static void TableIndexOutOfRange()
		{
			throw new ArgumentOutOfRangeException("tableIndex");
		}

		[DoesNotReturn]
		internal static void ValueArgumentOutOfRange()
		{
			throw new ArgumentOutOfRangeException("value");
		}

		[DoesNotReturn]
		internal static void OutOfBounds()
		{
			throw new BadImageFormatException(System.SR.OutOfBoundsRead);
		}

		[DoesNotReturn]
		internal static void WriteOutOfBounds()
		{
			throw new InvalidOperationException(System.SR.OutOfBoundsWrite);
		}

		[DoesNotReturn]
		internal static void InvalidCodedIndex()
		{
			throw new BadImageFormatException(System.SR.InvalidCodedIndex);
		}

		[DoesNotReturn]
		internal static void InvalidHandle()
		{
			throw new BadImageFormatException(System.SR.InvalidHandle);
		}

		[DoesNotReturn]
		internal static void InvalidCompressedInteger()
		{
			throw new BadImageFormatException(System.SR.InvalidCompressedInteger);
		}

		[DoesNotReturn]
		internal static void InvalidSerializedString()
		{
			throw new BadImageFormatException(System.SR.InvalidSerializedString);
		}

		[DoesNotReturn]
		internal static void ImageTooSmall()
		{
			throw new BadImageFormatException(System.SR.ImageTooSmall);
		}

		[DoesNotReturn]
		internal static void ImageTooSmallOrContainsInvalidOffsetOrCount()
		{
			throw new BadImageFormatException(System.SR.ImageTooSmallOrContainsInvalidOffsetOrCount);
		}

		[DoesNotReturn]
		internal static void ReferenceOverflow()
		{
			throw new BadImageFormatException(System.SR.RowIdOrHeapOffsetTooLarge);
		}

		[DoesNotReturn]
		internal static void TableNotSorted(TableIndex tableIndex)
		{
			throw new BadImageFormatException(System.SR.Format(System.SR.MetadataTableNotSorted, tableIndex));
		}

		[DoesNotReturn]
		internal static void InvalidOperation_TableNotSorted(TableIndex tableIndex)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.MetadataTableNotSorted, tableIndex));
		}

		[DoesNotReturn]
		internal static void InvalidOperation_PEImageNotAvailable()
		{
			throw new InvalidOperationException(System.SR.PEImageNotAvailable);
		}

		[DoesNotReturn]
		internal static void TooManySubnamespaces()
		{
			throw new BadImageFormatException(System.SR.TooManySubnamespaces);
		}

		[DoesNotReturn]
		internal static void ValueOverflow()
		{
			throw new BadImageFormatException(System.SR.ValueTooLarge);
		}

		[DoesNotReturn]
		internal static void SequencePointValueOutOfRange()
		{
			throw new BadImageFormatException(System.SR.SequencePointValueOutOfRange);
		}

		[DoesNotReturn]
		internal static void HeapSizeLimitExceeded(HeapIndex heap)
		{
			throw new ImageFormatLimitationException(System.SR.Format(System.SR.HeapSizeLimitExceeded, heap));
		}

		[DoesNotReturn]
		internal static void PEReaderDisposed()
		{
			throw new ObjectDisposedException("PEReader");
		}
	}
	[Flags]
	public enum MethodSemanticsAttributes
	{
		Setter = 1,
		Getter = 2,
		Other = 4,
		Adder = 8,
		Remover = 0x10,
		Raiser = 0x20
	}
	public enum DeclarativeSecurityAction : short
	{
		None = 0,
		Demand = 2,
		Assert = 3,
		Deny = 4,
		PermitOnly = 5,
		LinkDemand = 6,
		InheritanceDemand = 7,
		RequestMinimum = 8,
		RequestOptional = 9,
		RequestRefuse = 10
	}
	[Flags]
	public enum MethodImportAttributes : short
	{
		None = 0,
		ExactSpelling = 1,
		BestFitMappingDisable = 0x20,
		BestFitMappingEnable = 0x10,
		BestFitMappingMask = 0x30,
		CharSetAnsi = 2,
		CharSetUnicode = 4,
		CharSetAuto = 6,
		CharSetMask = 6,
		ThrowOnUnmappableCharEnable = 0x1000,
		ThrowOnUnmappableCharDisable = 0x2000,
		ThrowOnUnmappableCharMask = 0x3000,
		SetLastError = 0x40,
		CallingConventionWinApi = 0x100,
		CallingConventionCDecl = 0x200,
		CallingConventionStdCall = 0x300,
		CallingConventionThisCall = 0x400,
		CallingConventionFastCall = 0x500,
		CallingConventionMask = 0x700
	}
	[Flags]
	public enum ManifestResourceAttributes
	{
		Public = 1,
		Private = 2,
		VisibilityMask = 7
	}
	public enum AssemblyHashAlgorithm
	{
		None = 0,
		MD5 = 32771,
		Sha1 = 32772,
		Sha256 = 32780,
		Sha384 = 32781,
		Sha512 = 32782
	}
	[Flags]
	public enum AssemblyFlags
	{
		PublicKey = 1,
		Retargetable = 0x100,
		WindowsRuntime = 0x200,
		ContentTypeMask = 0xE00,
		DisableJitCompileOptimizer = 0x4000,
		EnableJitCompileTracking = 0x8000
	}
	internal static class TypeAttributesExtensions
	{
		private const TypeAttributes Forwarder = (TypeAttributes)2097152;

		private const TypeAttributes NestedMask = TypeAttributes.NestedFamANDAssem;

		public static bool IsForwarder(this TypeAttributes flags)
		{
			return (flags & (TypeAttributes)2097152) != 0;
		}

		public static bool IsNested(this TypeAttributes flags)
		{
			return (flags & TypeAttributes.NestedFamANDAssem) != 0;
		}
	}
	internal static class AssemblyNameFormatter
	{
		public static string ComputeDisplayName(string name, Version? version, string? cultureName, byte[]? pkt, AssemblyNameFlags flags = AssemblyNameFlags.None, AssemblyContentType contentType = AssemblyContentType.Default, byte[]? pk = null)
		{
			Span<char> initialBuffer = stackalloc char[256];
			System.Text.ValueStringBuilder vsb = new System.Text.ValueStringBuilder(initialBuffer);
			vsb.AppendQuoted(name);
			if (version != null)
			{
				ushort num = (ushort)version.Major;
				if (num != ushort.MaxValue)
				{
					vsb.Append(", Version=");
					vsb.AppendSpanFormattable(num);
					ushort num2 = (ushort)version.Minor;
					if (num2 != ushort.MaxValue)
					{
						vsb.Append('.');
						vsb.AppendSpanFormattable(num2);
						ushort num3 = (ushort)version.Build;
						if (num3 != ushort.MaxValue)
						{
							vsb.Append('.');
							vsb.AppendSpanFormattable(num3);
							ushort num4 = (ushort)version.Revision;
							if (num4 != ushort.MaxValue)
							{
								vsb.Append('.');
								vsb.AppendSpanFormattable(num4);
							}
						}
					}
				}
			}
			if (cultureName != null)
			{
				if (cultureName.Length == 0)
				{
					cultureName = "neutral";
				}
				vsb.Append(", Culture=");
				vsb.AppendQuoted(cultureName);
			}
			byte[] array = pkt ?? pk;
			if (array != null)
			{
				if (pkt != null)
				{
					if (pkt.Length > 8)
					{
						throw new ArgumentException();
					}
					vsb.Append(", PublicKeyToken=");
				}
				else
				{
					vsb.Append(", PublicKey=");
				}
				if (array.Length == 0)
				{
					vsb.Append("null");
				}
				else
				{
					System.HexConverter.EncodeToUtf16(array, vsb.AppendSpan(array.Length * 2), System.HexConverter.Casing.Lower);
				}
			}
			if ((flags & AssemblyNameFlags.Retargetable) != 0)
			{
				vsb.Append(", Retargetable=Yes");
			}
			if (contentType == AssemblyContentType.WindowsRuntime)
			{
				vsb.Append(", ContentType=WindowsRuntime");
			}
			return vsb.ToString();
		}

		private static void AppendQuoted(this ref System.Text.ValueStringBuilder vsb, string s)
		{
			bool flag = false;
			ReadOnlySpan<char> span = s.AsSpan();
			if (s.Length != span.Trim().Length || span.IndexOfAny('"', '\'') >= 0)
			{
				flag = true;
			}
			if (flag)
			{
				vsb.Append('"');
			}
			for (int i = 0; i < s.Length; i++)
			{
				switch (s[i])
				{
				case '"':
				case '\'':
				case ',':
				case '=':
				case '\\':
					vsb.Append('\\');
					break;
				case '\t':
					vsb.Append("\\t");
					continue;
				case '\r':
					vsb.Append("\\r");
					continue;
				case '\n':
					vsb.Append("\\n");
					continue;
				}
				vsb.Append(s[i]);
			}
			if (flag)
			{
				vsb.Append('"');
			}
		}

		private static void AppendSpanFormattable(this ref System.Text.ValueStringBuilder vsb, ushort value)
		{
			vsb.Append(value.ToString());
		}
	}
	internal ref struct AssemblyNameParser
	{
		public readonly struct AssemblyNameParts
		{
			public readonly string _name;

			public readonly Version? _version;

			public readonly string? _cultureName;

			public readonly AssemblyNameFlags _flags;

			public readonly byte[]? _publicKeyOrToken;

			public AssemblyNameParts(string name, Version? version, string? cultureName, AssemblyNameFlags flags, byte[]? publicKeyOrToken)
			{
				_name = name;
				_version = version;
				_cultureName = cultureName;
				_flags = flags;
				_publicKeyOrToken = publicKeyOrToken;
			}
		}

		private enum Token
		{
			Equals = 1,
			Comma,
			String,
			End
		}

		private enum AttributeKind
		{
			Version = 1,
			Culture = 2,
			PublicKeyOrToken = 4,
			ProcessorArchitecture = 8,
			Retargetable = 0x10,
			ContentType = 0x20
		}

		private readonly ReadOnlySpan<char> _input;

		private int _index;

		private AssemblyNameParser(ReadOnlySpan<char> input)
		{
			_input = input;
			_index = 0;
		}

		internal static bool TryParse(ReadOnlySpan<char> name, ref AssemblyNameParts parts)
		{
			return new AssemblyNameParser(name).TryParse(ref parts);
		}

		private static bool TryRecordNewSeen(scoped ref AttributeKind seenAttributes, AttributeKind newAttribute)
		{
			if ((seenAttributes & newAttribute) != 0)
			{
				return false;
			}
			seenAttributes |= newAttribute;
			return true;
		}

		private bool TryParse(ref AssemblyNameParts result)
		{
			if (!TryGetNextToken(out var tokenString, out var token) || token != Token.String || string.IsNullOrEmpty(tokenString))
			{
				return false;
			}
			Version version = null;
			string result2 = null;
			byte[] result3 = null;
			AssemblyNameFlags assemblyNameFlags = AssemblyNameFlags.None;
			AttributeKind seenAttributes = (AttributeKind)0;
			if (!TryGetNextToken(out var tokenString2, out token))
			{
				return false;
			}
			do
			{
				switch (token)
				{
				default:
					return false;
				case Token.Comma:
				{
					if (!TryGetNextToken(out var tokenString3, out token) || token != Token.String)
					{
						return false;
					}
					if (!TryGetNextToken(out tokenString2, out token) || token != Token.Equals)
					{
						return false;
					}
					if (!TryGetNextToken(out var tokenString4, out token) || token != Token.String)
					{
						return false;
					}
					if (tokenString3 == string.Empty)
					{
						return false;
					}
					if (IsAttribute(tokenString3, "Version"))
					{
						if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.Version))
						{
							return false;
						}
						if (!TryParseVersion(tokenString4, ref version))
						{
							return false;
						}
					}
					else if (IsAttribute(tokenString3, "Culture"))
					{
						if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.Culture))
						{
							return false;
						}
						if (!TryParseCulture(tokenString4, out result2))
						{
							return false;
						}
					}
					else if (IsAttribute(tokenString3, "PublicKeyToken"))
					{
						if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.PublicKeyOrToken))
						{
							return false;
						}
						if (!TryParsePKT(tokenString4, isToken: true, out result3))
						{
							return false;
						}
					}
					else if (IsAttribute(tokenString3, "PublicKey"))
					{
						if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.PublicKeyOrToken))
						{
							return false;
						}
						if (!TryParsePKT(tokenString4, isToken: false, out result3))
						{
							return false;
						}
						assemblyNameFlags |= AssemblyNameFlags.PublicKey;
					}
					else if (IsAttribute(tokenString3, "ProcessorArchitecture"))
					{
						if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.ProcessorArchitecture))
						{
							return false;
						}
						if (!TryParseProcessorArchitecture(tokenString4, out var result4))
						{
							return false;
						}
						assemblyNameFlags = (AssemblyNameFlags)((int)assemblyNameFlags | ((int)result4 << 4));
					}
					else if (IsAttribute(tokenString3, "Retargetable"))
					{
						if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.Retargetable))
						{
							return false;
						}
						if (tokenString4.Equals("Yes", StringComparison.OrdinalIgnoreCase))
						{
							assemblyNameFlags |= AssemblyNameFlags.Retargetable;
						}
						else if (!tokenString4.Equals("No", StringComparison.OrdinalIgnoreCase))
						{
							return false;
						}
					}
					else if (IsAttribute(tokenString3, "ContentType"))
					{
						if (!TryRecordNewSeen(ref seenAttributes, AttributeKind.ContentType))
						{
							return false;
						}
						if (!tokenString4.Equals("WindowsRuntime", StringComparison.OrdinalIgnoreCase))
						{
							return false;
						}
						assemblyNameFlags |= (AssemblyNameFlags)512;
					}
					break;
				}
				case Token.End:
					result = new AssemblyNameParts(tokenString, version, result2, assemblyNameFlags, result3);
					return true;
				}
			}
			while (TryGetNextToken(out tokenString2, out token));
			return false;
		}

		private static bool IsAttribute(string candidate, string attributeKind)
		{
			return candidate.Equals(attributeKind, StringComparison.OrdinalIgnoreCase);
		}

		private static bool TryParseVersion(string attributeValue, ref Version version)
		{
			string[] array = attributeValue.Split(new char[1] { '.' });
			int num = array.Length;
			if ((num < 2 || num > 4) ? true : false)
			{
				return false;
			}
			Span<ushort> span = new Span<ushort>(new ushort[4] { 65535, 65535, 65535, 65535 });
			for (int i = 0; i < array.Length; i++)
			{
				if (!ushort.TryParse(array[i], NumberStyles.None, NumberFormatInfo.InvariantInfo, out span[i]))
				{
					return false;
				}
			}
			if (span[0] == ushort.MaxValue || span[1] == ushort.MaxValue)
			{
				return false;
			}
			version = ((span[2] == ushort.MaxValue) ? new Version(span[0], span[1]) : ((span[3] == ushort.MaxValue) ? new Version(span[0], span[1], span[2]) : new Version(span[0], span[1], span[2], span[3])));
			return true;
		}

		private static bool TryParseCulture(string attributeValue, out string result)
		{
			if (attributeValue.Equals("Neutral", StringComparison.OrdinalIgnoreCase))
			{
				result = "";
				return true;
			}
			result = attributeValue;
			return true;
		}

		private static bool TryParsePKT(string attributeValue, bool isToken, out byte[] result)
		{
			if (attributeValue.Equals("null", StringComparison.OrdinalIgnoreCase) || attributeValue == string.Empty)
			{
				result = Array.Empty<byte>();
				return true;
			}
			if (attributeValue.Length % 2 != 0 || (isToken && attributeValue.Length != 16))
			{
				result = null;
				return false;
			}
			byte[] array = new byte[attributeValue.Length / 2];
			if (!System.HexConverter.TryDecodeFromUtf16(attributeValue.AsSpan(), array, out var _))
			{
				result = null;
				return false;
			}
			result = array;
			return true;
		}

		private static bool TryParseProcessorArchitecture(string attributeValue, out ProcessorArchitecture result)
		{
			ProcessorArchitecture processorArchitecture = (attributeValue.Equals("msil", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.MSIL : (attributeValue.Equals("x86", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.X86 : (attributeValue.Equals("ia64", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.IA64 : (attributeValue.Equals("amd64", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.Amd64 : (attributeValue.Equals("arm", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.Arm : (attributeValue.Equals("msil", StringComparison.OrdinalIgnoreCase) ? ProcessorArchitecture.MSIL : ProcessorArchitecture.None))))));
			result = processorArchitecture;
			return result != ProcessorArchitecture.None;
		}

		private static bool IsWhiteSpace(char ch)
		{
			switch (ch)
			{
			case '\t':
			case '\n':
			case '\r':
			case ' ':
				return true;
			default:
				return false;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private bool TryGetNextChar(out char ch)
		{
			if (_index < _input.Length)
			{
				ch = _input[_index++];
				if (ch == '\0')
				{
					return false;
				}
			}
			else
			{
				ch = '\0';
			}
			return true;
		}

		private bool TryGetNextToken(out string tokenString, out Token token)
		{
			tokenString = string.Empty;
			char ch;
			do
			{
				if (!TryGetNextChar(out ch))
				{
					token = (Token)0;
					return false;
				}
				switch (ch)
				{
				case ',':
					token = Token.Comma;
					return true;
				case '=':
					token = Token.Equals;
					return true;
				case '\0':
					token = Token.End;
					return true;
				}
			}
			while (IsWhiteSpace(ch));
			Span<char> initialBuffer = stackalloc char[64];
			bool flag;
			using (System.Text.ValueStringBuilder valueStringBuilder = new System.Text.ValueStringBuilder(initialBuffer))
			{
				char c = '\0';
				flag = ((ch == '"' || ch == '\'') ? true : false);
				if (!flag)
				{
					goto IL_0085;
				}
				c = ch;
				if (TryGetNextChar(out ch))
				{
					goto IL_0085;
				}
				token = (Token)0;
				flag = false;
				goto end_IL_0056;
				IL_0085:
				while (true)
				{
					if (ch == '\0')
					{
						if (c != 0)
						{
							token = (Token)0;
							flag = false;
							break;
						}
					}
					else if (c == '\0' || ch != c)
					{
						bool flag2 = c == '\0';
						if (flag2)
						{
							bool flag3 = ((ch == ',' || ch == '=') ? true : false);
							flag2 = flag3;
						}
						if (!flag2)
						{
							flag2 = c == '\0';
							if (flag2)
							{
								bool flag3 = ((ch == '"' || ch == '\'') ? true : false);
								flag2 = flag3;
							}
							if (flag2)
							{
								token = (Token)0;
								flag = false;
								break;
							}
							if (ch == '\\')
							{
								if (!TryGetNextChar(out ch))
								{
									token = (Token)0;
									flag = false;
									break;
								}
								switch (ch)
								{
								case '"':
								case '\'':
								case ',':
								case '=':
								case '\\':
									valueStringBuilder.Append(ch);
									goto IL_01a0;
								case 't':
									valueStringBuilder.Append('\t');
									goto IL_01a0;
								case 'r':
									valueStringBuilder.Append('\r');
									goto IL_01a0;
								case 'n':
									valueStringBuilder.Append('\n');
									goto IL_01a0;
								default:
									token = (Token)0;
									flag = false;
									break;
								}
								break;
							}
							valueStringBuilder.Append(ch);
							goto IL_01a0;
						}
						_index--;
					}
					int num = valueStringBuilder.Length;
					if (c == '\0')
					{
						while (num > 0 && IsWhiteSpace(valueStringBuilder[num - 1]))
						{
							num--;
						}
					}
					tokenString = valueStringBuilder.AsSpan(0, num).ToString();
					token = Token.String;
					flag = true;
					break;
					IL_01a0:
					if (!TryGetNextChar(out ch))
					{
						token = (Token)0;
						flag = false;
						break;
					}
				}
				end_IL_0056:;
			}
			return flag;
		}
	}
}
namespace System.Reflection.PortableExecutable
{
	public class ManagedPEBuilder : PEBuilder
	{
		public const int ManagedResourcesDataAlignment = 8;

		public const int MappedFieldDataAlignment = 8;

		private const int DefaultStrongNameSignatureSize = 128;

		private const string TextSectionName = ".text";

		private const string ResourceSectionName = ".rsrc";

		private const string RelocationSectionName = ".reloc";

		private readonly PEDirectoriesBuilder _peDirectoriesBuilder;

		private readonly MetadataRootBuilder _metadataRootBuilder;

		private readonly BlobBuilder _ilStream;

		private readonly BlobBuilder _mappedFieldDataOpt;

		private readonly BlobBuilder _managedResourcesOpt;

		private readonly ResourceSectionBuilder _nativeResourcesOpt;

		private readonly int _strongNameSignatureSize;

		private readonly MethodDefinitionHandle _entryPointOpt;

		private readonly DebugDirectoryBuilder _debugDirectoryBuilderOpt;

		private readonly CorFlags _corFlags;

		private int _lazyEntryPointAddress;

		private Blob _lazyStrongNameSignature;

		public ManagedPEBuilder(PEHeaderBuilder header, MetadataRootBuilder metadataRootBuilder, BlobBuilder ilStream, BlobBuilder? mappedFieldData = null, BlobBuilder? managedResources = null, ResourceSectionBuilder? nativeResources = null, DebugDirectoryBuilder? debugDirectoryBuilder = null, int strongNameSignatureSize = 128, MethodDefinitionHandle entryPoint = default(MethodDefinitionHandle), CorFlags flags = CorFlags.ILOnly, Func<IEnumerable<Blob>, BlobContentId>? deterministicIdProvider = null)
			: base(header, deterministicIdProvider)
		{
			if (header == null)
			{
				Throw.ArgumentNull("header");
			}
			if (metadataRootBuilder == null)
			{
				Throw.ArgumentNull("metadataRootBuilder");
			}
			if (ilStream == null)
			{
				Throw.ArgumentNull("ilStream");
			}
			if (strongNameSignatureSize < 0)
			{
				Throw.ArgumentOutOfRange("strongNameSignatureSize");
			}
			_metadataRootBuilder = metadataRootBuilder;
			_ilStream = ilStream;
			_mappedFieldDataOpt = mappedFieldData;
			_managedResourcesOpt = managedResources;
			_nativeResourcesOpt = nativeResources;
			_strongNameSignatureSize = strongNameSignatureSize;
			_entryPointOpt = entryPoint;
			_debugDirectoryBuilderOpt = debugDirectoryBuilder ?? CreateDefaultDebugDirectoryBuilder();
			_corFlags = flags;
			_peDirectoriesBuilder = new PEDirectoriesBuilder();
		}

		private DebugDirectoryBuilder CreateDefaultDebugDirectoryBuilder()
		{
			if (base.IsDeterministic)
			{
				DebugDirectoryBuilder debugDirectoryBuilder = new DebugDirectoryBuilder();
				debugDirectoryBuilder.AddReproducibleEntry();
				return debugDirectoryBuilder;
			}
			return null;
		}

		protected override ImmutableArray<Section> CreateSections()
		{
			ImmutableArray<Section>.Builder builder = ImmutableArray.CreateBuilder<Section>(3);
			builder.Add(new Section(".text", SectionCharacteristics.ContainsCode | SectionCharacteristics.MemExecute | SectionCharacteristics.MemRead));
			if (_nativeResourcesOpt != null)
			{
				builder.Add(new Section(".rsrc", SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemRead));
			}
			if (base.Header.Machine == Machine.I386 || base.Header.Machine == Machine.Unknown)
			{
				builder.Add(new Section(".reloc", SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable | SectionCharacteristics.MemRead));
			}
			return builder.ToImmutable();
		}

		protected override BlobBuilder SerializeSection(string name, SectionLocation location)
		{
			return name switch
			{
				".text" => SerializeTextSection(location), 
				".rsrc" => SerializeResourceSection(location), 
				".reloc" => SerializeRelocationSection(location), 
				_ => throw new ArgumentException(System.SR.Format(System.SR.UnknownSectionName, name), "name"), 
			};
		}

		private BlobBuilder SerializeTextSection(SectionLocation location)
		{
			BlobBuilder blobBuilder = new BlobBuilder();
			BlobBuilder blobBuilder2 = new BlobBuilder();
			MetadataSizes sizes = _metadataRootBuilder.Sizes;
			ManagedTextSection managedTextSection = new ManagedTextSection(base.Header.ImageCharacteristics, base.Header.Machine, _ilStream.Count, sizes.MetadataSize, _managedResourcesOpt?.Count ?? 0, _strongNameSignatureSize, _debugDirectoryBuilderOpt?.Size ?? 0, _mappedFieldDataOpt?.Count ?? 0);
			int methodBodyStreamRva = location.RelativeVirtualAddress + managedTextSection.OffsetToILStream;
			int mappedFieldDataStreamRva = location.RelativeVirtualAddress + managedTextSection.CalculateOffsetToMappedFieldDataStream();
			_metadataRootBuilder.Serialize(blobBuilder2, methodBodyStreamRva, mappedFieldDataStreamRva);
			BlobBuilder blobBuilder3;
			DirectoryEntry debugTable;
			if (_debugDirectoryBuilderOpt != null)
			{
				int num = managedTextSection.ComputeOffsetToDebugDirectory();
				blobBuilder3 = new BlobBuilder(_debugDirectoryBuilderOpt.TableSize);
				_debugDirectoryBuilderOpt.Serialize(blobBuilder3, location, num);
				debugTable = new DirectoryEntry(location.RelativeVirtualAddress + num, _debugDirectoryBuilderOpt.TableSize);
			}
			else
			{
				blobBuilder3 = null;
				debugTable = default(DirectoryEntry);
			}
			_lazyEntryPointAddress = managedTextSection.GetEntryPointAddress(location.RelativeVirtualAddress);
			managedTextSection.Serialize(blobBuilder, location.RelativeVirtualAddress, (!_entryPointOpt.IsNil) ? MetadataTokens.GetToken(_entryPointOpt) : 0, _corFlags, base.Header.ImageBase, blobBuilder2, _ilStream, _mappedFieldDataOpt, _managedResourcesOpt, blobBuilder3, out _lazyStrongNameSignature);
			_peDirectoriesBuilder.AddressOfEntryPoint = _lazyEntryPointAddress;
			_peDirectoriesBuilder.DebugTable = debugTable;
			_peDirectoriesBuilder.ImportAddressTable = managedTextSection.GetImportAddressTableDirectoryEntry(location.RelativeVirtualAddress);
			_peDirectoriesBuilder.ImportTable = managedTextSection.GetImportTableDirectoryEntry(location.RelativeVirtualAddress);
			_peDirectoriesBuilder.CorHeaderTable = managedTextSection.GetCorHeaderDirectoryEntry(location.RelativeVirtualAddress);
			return blobBuilder;
		}

		private BlobBuilder SerializeResourceSection(SectionLocation location)
		{
			BlobBuilder blobBuilder = new BlobBuilder();
			_nativeResourcesOpt.Serialize(blobBuilder, location);
			_peDirectoriesBuilder.ResourceTable = new DirectoryEntry(location.RelativeVirtualAddress, blobBuilder.Count);
			return blobBuilder;
		}

		private BlobBuilder SerializeRelocationSection(SectionLocation location)
		{
			BlobBuilder blobBuilder = new BlobBuilder();
			WriteRelocationSection(blobBuilder, base.Header.Machine, _lazyEntryPointAddress);
			_peDirectoriesBuilder.BaseRelocationTable = new DirectoryEntry(location.RelativeVirtualAddress, blobBuilder.Count);
			return blobBuilder;
		}

		private static void WriteRelocationSection(BlobBuilder builder, Machine machine, int entryPointAddress)
		{
			builder.WriteUInt32((uint)(entryPointAddress + 2) / 4096u * 4096);
			builder.WriteUInt32((machine == Machine.IA64) ? 14u : 12u);
			uint num = (uint)(entryPointAddress + 2) % 4096u;
			uint num2 = ((machine == Machine.Amd64 || machine == Machine.IA64 || machine == Machine.Arm64) ? 10u : 3u);
			ushort value = (ushort)((num2 << 12) | num);
			builder.WriteUInt16(value);
			if (machine == Machine.IA64)
			{
				builder.WriteUInt32(num2 << 12);
			}
			builder.WriteUInt16(0);
		}

		protected internal override PEDirectoriesBuilder GetDirectories()
		{
			return _peDirectoriesBuilder;
		}

		public void Sign(BlobBuilder peImage, Func<IEnumerable<Blob>, byte[]> signatureProvider)
		{
			if (peImage == null)
			{
				Throw.ArgumentNull("peImage");
			}
			if (signatureProvider == null)
			{
				Throw.ArgumentNull("signatureProvider");
			}
			Sign(peImage, _lazyStrongNameSignature, signatureProvider);
		}
	}
	internal sealed class ManagedTextSection
	{
		public const int ManagedResourcesDataAlignment = 8;

		public const int MappedFieldDataAlignment = 8;

		private const int CorHeaderSize = 72;

		public Characteristics ImageCharacteristics { get; }

		public Machine Machine { get; }

		public int ILStreamSize { get; }

		public int MetadataSize { get; }

		public int ResourceDataSize { get; }

		public int StrongNameSignatureSize { get; }

		public int DebugDataSize { get; }

		public int MappedFieldDataSize { get; }

		internal bool RequiresStartupStub
		{
			get
			{
				if (Machine != Machine.I386)
				{
					return Machine == Machine.Unknown;
				}
				return true;
			}
		}

		internal bool Requires64bits
		{
			get
			{
				if (Machine != Machine.Amd64 && Machine != Machine.IA64)
				{
					return Machine == Machine.Arm64;
				}
				return true;
			}
		}

		public bool Is32Bit => !Requires64bits;

		private static ReadOnlySpan<byte> CorEntryPointDll => "mscoree.dll"u8;

		private ReadOnlySpan<byte> CorEntryPointName
		{
			get
			{
				if ((ImageCharacteristics & Characteristics.Dll) != 0)
				{
					return "_CorDllMain"u8;
				}
				return "_CorExeMain"u8;
			}
		}

		private int SizeOfImportAddressTable
		{
			get
			{
				if (!RequiresStartupStub)
				{
					return 0;
				}
				if (!Is32Bit)
				{
					return 16;
				}
				return 8;
			}
		}

		private int SizeOfImportTable => 40 + (Is32Bit ? 12 : 16) + 2 + CorEntryPointName.Length + 1;

		private static int SizeOfNameTable => CorEntryPointDll.Length + 1 + 2;

		private int SizeOfRuntimeStartupStub
		{
			get
			{
				if (!Is32Bit)
				{
					return 16;
				}
				return 8;
			}
		}

		public int OffsetToILStream => SizeOfImportAddressTable + 72;

		public ManagedTextSection(Characteristics imageCharacteristics, Machine machine, int ilStreamSize, int metadataSize, int resourceDataSize, int strongNameSignatureSize, int debugDataSize, int mappedFieldDataSize)
		{
			MetadataSize = metadataSize;
			ResourceDataSize = resourceDataSize;
			ILStreamSize = ilStreamSize;
			MappedFieldDataSize = mappedFieldDataSize;
			StrongNameSignatureSize = strongNameSignatureSize;
			ImageCharacteristics = imageCharacteristics;
			Machine = machine;
			DebugDataSize = debugDataSize;
		}

		internal int CalculateOffsetToMappedFieldDataStreamUnaligned()
		{
			int num = ComputeOffsetToImportTable();
			if (RequiresStartupStub)
			{
				num += SizeOfImportTable + SizeOfNameTable;
				num = BitArithmetic.Align(num, Is32Bit ? 4 : 8);
				num += SizeOfRuntimeStartupStub;
			}
			return num;
		}

		public int CalculateOffsetToMappedFieldDataStream()
		{
			int num = CalculateOffsetToMappedFieldDataStreamUnaligned();
			if (MappedFieldDataSize != 0)
			{
				num = BitArithmetic.Align(num, 8);
			}
			return num;
		}

		internal int ComputeOffsetToDebugDirectory()
		{
			return ComputeOffsetToMetadata() + MetadataSize + ResourceDataSize + StrongNameSignatureSize;
		}

		private int ComputeOffsetToImportTable()
		{
			return ComputeOffsetToDebugDirectory() + DebugDataSize;
		}

		private int ComputeOffsetToMetadata()
		{
			return OffsetToILStream + BitArithmetic.Align(ILStreamSize, 4);
		}

		public int ComputeSizeOfTextSection()
		{
			return CalculateOffsetToMappedFieldDataStream() + MappedFieldDataSize;
		}

		public int GetEntryPointAddress(int rva)
		{
			if (!RequiresStartupStub)
			{
				return 0;
			}
			return rva + CalculateOffsetToMappedFieldDataStreamUnaligned() - (Is32Bit ? 6 : 10);
		}

		public DirectoryEntry GetImportAddressTableDirectoryEntry(int rva)
		{
			if (!RequiresStartupStub)
			{
				return default(DirectoryEntry);
			}
			return new DirectoryEntry(rva, SizeOfImportAddressTable);
		}

		public DirectoryEntry GetImportTableDirectoryEntry(int rva)
		{
			if (!RequiresStartupStub)
			{
				return default(DirectoryEntry);
			}
			return new DirectoryEntry(rva + ComputeOffsetToImportTable(), (Is32Bit ? 66 : 70) + 13);
		}

		public DirectoryEntry GetCorHeaderDirectoryEntry(int rva)
		{
			return new DirectoryEntry(rva + SizeOfImportAddressTable, 72);
		}

		public void Serialize(BlobBuilder builder, int relativeVirtualAddess, int entryPointTokenOrRelativeVirtualAddress, CorFlags corFlags, ulong baseAddress, BlobBuilder metadataBuilder, BlobBuilder ilBuilder, BlobBuilder? mappedFieldDataBuilderOpt, BlobBuilder? resourceBuilderOpt, BlobBuilder? debugDataBuilderOpt, out Blob strongNameSignature)
		{
			int relativeVirtualAddress = GetImportTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress;
			int relativeVirtualAddress2 = GetImportAddressTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress;
			if (RequiresStartupStub)
			{
				WriteImportAddressTable(builder, relativeVirtualAddress);
			}
			WriteCorHeader(builder, relativeVirtualAddess, entryPointTokenOrRelativeVirtualAddress, corFlags);
			ilBuilder.Align(4);
			builder.LinkSuffix(ilBuilder);
			builder.LinkSuffix(metadataBuilder);
			if (resourceBuilderOpt != null)
			{
				builder.LinkSuffix(resourceBuilderOpt);
			}
			strongNameSignature = builder.ReserveBytes(StrongNameSignatureSize);
			new BlobWriter(strongNameSignature).WriteBytes(0, StrongNameSignatureSize);
			if (debugDataBuilderOpt != null)
			{
				builder.LinkSuffix(debugDataBuilderOpt);
			}
			if (RequiresStartupStub)
			{
				WriteImportTable(builder, relativeVirtualAddress, relativeVirtualAddress2);
				WriteNameTable(builder);
				WriteRuntimeStartupStub(builder, relativeVirtualAddress2, baseAddress);
			}
			if (mappedFieldDataBuilderOpt != null)
			{
				if (mappedFieldDataBuilderOpt.Count != 0)
				{
					builder.Align(8);
				}
				builder.LinkSuffix(mappedFieldDataBuilderOpt);
			}
		}

		private void WriteImportAddressTable(BlobBuilder builder, int importTableRva)
		{
			_ = builder.Count;
			int num = importTableRva + 40 + (Is32Bit ? 12 : 16);
			if (Is32Bit)
			{
				builder.WriteUInt32((uint)num);
				builder.WriteUInt32(0u);
			}
			else
			{
				builder.WriteUInt64((uint)num);
				builder.WriteUInt64(0uL);
			}
		}

		private void WriteImportTable(BlobBuilder builder, int importTableRva, int importAddressTableRva)
		{
			_ = builder.Count;
			int num = importTableRva + 40;
			int num2 = num + (Is32Bit ? 12 : 16);
			int value = num2 + 12 + 2;
			builder.WriteUInt32((uint)num);
			builder.WriteUInt32(0u);
			builder.WriteUInt32(0u);
			builder.WriteUInt32((uint)value);
			builder.WriteUInt32((uint)importAddressTableRva);
			builder.WriteBytes(0, 20);
			if (Is32Bit)
			{
				builder.WriteUInt32((uint)num2);
				builder.WriteUInt32(0u);
				builder.WriteUInt32(0u);
			}
			else
			{
				builder.WriteUInt64((uint)num2);
				builder.WriteUInt64(0uL);
			}
			builder.WriteUInt16(0);
			builder.WriteBytes(CorEntryPointName);
			builder.WriteByte(0);
		}

		private static void WriteNameTable(BlobBuilder builder)
		{
			_ = builder.Count;
			builder.WriteBytes(CorEntryPointDll);
			builder.WriteByte(0);
			builder.WriteUInt16(0);
		}

		private void WriteCorHeader(BlobBuilder builder, int textSectionRva, int entryPointTokenOrRva, CorFlags corFlags)
		{
			int num = textSectionRva + ComputeOffsetToMetadata();
			int num2 = num + MetadataSize;
			int num3 = num2 + ResourceDataSize;
			_ = builder.Count;
			builder.WriteUInt32(72u);
			builder.WriteUInt16(2);
			builder.WriteUInt16(5);
			builder.WriteUInt32((uint)num);
			builder.WriteUInt32((uint)MetadataSize);
			builder.WriteUInt32((uint)corFlags);
			builder.WriteUInt32((uint)entryPointTokenOrRva);
			builder.WriteUInt32((ResourceDataSize != 0) ? ((uint)num2) : 0u);
			builder.WriteUInt32((uint)ResourceDataSize);
			builder.WriteUInt32((StrongNameSignatureSize != 0) ? ((uint)num3) : 0u);
			builder.WriteUInt32((uint)StrongNameSignatureSize);
			builder.WriteUInt32(0u);
			builder.WriteUInt32(0u);
			builder.WriteUInt32(0u);
			builder.WriteUInt32(0u);
			builder.WriteUInt32(0u);
			builder.WriteUInt32(0u);
			builder.WriteUInt32(0u);
			builder.WriteUInt32(0u);
		}

		private void WriteRuntimeStartupStub(BlobBuilder sectionBuilder, int importAddressTableRva, ulong baseAddress)
		{
			if (Is32Bit)
			{
				sectionBuilder.Align(4);
				sectionBuilder.WriteUInt16(0);
				sectionBuilder.WriteByte(byte.MaxValue);
				sectionBuilder.WriteByte(37);
				sectionBuilder.WriteUInt32((uint)(importAddressTableRva + (int)baseAddress));
			}
			else
			{
				sectionBuilder.Align(8);
				sectionBuilder.WriteUInt32(0u);
				sectionBuilder.WriteUInt16(0);
				sectionBuilder.WriteByte(byte.MaxValue);
				sectionBuilder.WriteByte(37);
				sectionBuilder.WriteUInt64((ulong)importAddressTableRva + baseAddress);
			}
		}
	}
	public abstract class PEBuilder
	{
		protected readonly struct Section
		{
			public readonly string Name;

			public readonly SectionCharacteristics Characteristics;

			public Section(string name, SectionCharacteristics characteristics)
			{
				if (name == null)
				{
					Throw.ArgumentNull("name");
				}
				Name = name;
				Characteristics = characteristics;
			}
		}

		private readonly struct SerializedSection
		{
			public readonly BlobBuilder Builder;

			public readonly string Name;

			public readonly SectionCharacteristics Characteristics;

			public readonly int RelativeVirtualAddress;

			public readonly int SizeOfRawData;

			public readonly int PointerToRawData;

			public int VirtualSize => Builder.Count;

			public SerializedSection(BlobBuilder builder, string name, SectionCharacteristics characteristics, int relativeVirtualAddress, int sizeOfRawData, int pointerToRawData)
			{
				Name = name;
				Characteristics = characteristics;
				Builder = builder;
				RelativeVirtualAddress = relativeVirtualAddress;
				SizeOfRawData = sizeOfRawData;
				PointerToRawData = pointerToRawData;
			}
		}

		private readonly Lazy<ImmutableArray<Section>> _lazySections;

		private Blob _lazyChecksum;

		internal const int DosHeaderSize = 128;

		public PEHeaderBuilder Header { get; }

		public Func<IEnumerable<Blob>, BlobContentId> IdProvider { get; }

		public bool IsDeterministic { get; }

		private static ReadOnlySpan<byte> DosHeader => new byte[128]
		{
			77, 90, 144, 0, 3, 0, 0, 0, 4, 0,
			0, 0, 255, 255, 0, 0, 184, 0, 0, 0,
			0, 0, 0, 0, 64, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			128, 0, 0, 0, 14, 31, 186, 14, 0, 180,
			9, 205, 33, 184, 1, 76, 205, 33, 84, 104,
			105, 115, 32, 112, 114, 111, 103, 114, 97, 109,
			32, 99, 97, 110, 110, 111, 116, 32, 98, 101,
			32, 114, 117, 110, 32, 105, 110, 32, 68, 79,
			83, 32, 109, 111, 100, 101, 46, 13, 13, 10,
			36, 0, 0, 0, 0, 0, 0, 0
		};

		protected PEBuilder(PEHeaderBuilder header, Func<IEnumerable<Blob>, BlobContentId>? deterministicIdProvider)
		{
			if (header == null)
			{
				Throw.ArgumentNull("header");
			}
			IdProvider = deterministicIdProvider ?? BlobContentId.GetTimeBasedProvider();
			IsDeterministic = deterministicIdProvider != null;
			Header = header;
			_lazySections = new Lazy<ImmutableArray<Section>>(CreateSections);
		}

		protected ImmutableArray<Section> GetSections()
		{
			ImmutableArray<Section> value = _lazySections.Value;
			if (value.IsDefault)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.MustNotReturnNull, "CreateSections"));
			}
			return value;
		}

		protected abstract ImmutableArray<Section> CreateSections();

		protected abstract BlobBuilder SerializeSection(string name, SectionLocation location);

		protected internal abstract PEDirectoriesBuilder GetDirectories();

		public BlobContentId Serialize(BlobBuilder builder)
		{
			ImmutableArray<SerializedSection> immutableArray = SerializeSections();
			PEDirectoriesBuilder directories = GetDirectories();
			WritePESignature(builder);
			WriteCoffHeader(builder, immutableArray, out var stampFixup);
			WritePEHeader(builder, directories, immutableArray);
			WriteSectionHeaders(builder, immutableArray);
			builder.Align(Header.FileAlignment);
			ImmutableArray<SerializedSection>.Enumerator enumerator = immutableArray.GetEnumerator();
			while (enumerator.MoveNext())
			{
				builder.LinkSuffix(enumerator.Current.Builder);
				builder.Align(Header.FileAlignment);
			}
			BlobContentId result = IdProvider(builder.GetBlobs());
			new BlobWriter(stampFixup).WriteUInt32(result.Stamp);
			return result;
		}

		private ImmutableArray<SerializedSection> SerializeSections()
		{
			ImmutableArray<Section> sections = GetSections();
			ImmutableArray<SerializedSection>.Builder builder = ImmutableArray.CreateBuilder<SerializedSection>(sections.Length);
			int posi

BepInEx/core/System.Runtime.CompilerServices.Unsafe.dll

Decompiled 2 weeks ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Microsoft.CodeAnalysis;

[assembly: AssemblyProduct("Microsoft® .NET Framework")]
[assembly: CLSCompliant(false)]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyDescription("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyFileVersion("6.100.225.20307")]
[assembly: AssemblyInformationalVersion("6.1.2")]
[assembly: AssemblyTitle("System.Runtime.CompilerServices.Unsafe")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyCopyright("© Microsoft Corporation.  All rights reserved.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyVersion("6.0.0.0")]
namespace System.Runtime.CompilerServices
{
	public static class Unsafe
	{
		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T Read<T>(void* source)
		{
			return Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static T ReadUnaligned<T>(void* source)
		{
			return Unsafe.ReadUnaligned<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T ReadUnaligned<T>(ref byte source)
		{
			return Unsafe.ReadUnaligned<T>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Write<T>(void* destination, T value)
		{
			Unsafe.Write(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void WriteUnaligned<T>(void* destination, T value)
		{
			Unsafe.WriteUnaligned(destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void WriteUnaligned<T>(ref byte destination, T value)
		{
			Unsafe.WriteUnaligned(ref destination, value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(void* destination, ref T source)
		{
			Unsafe.Write(destination, source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void Copy<T>(ref T destination, void* source)
		{
			destination = Unsafe.Read<T>(source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* AsPointer<T>(ref T value)
		{
			return Unsafe.AsPointer(ref value);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void SkipInit<T>(out T value)
		{
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static int SizeOf<T>()
		{
			return Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlock(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlock(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlock(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void CopyBlockUnaligned(void* destination, void* source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(destination, source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void CopyBlockUnaligned(ref byte destination, ref byte source, uint byteCount)
		{
			// IL cpblk instruction
			Unsafe.CopyBlockUnaligned(ref destination, ref source, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlock(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlock(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlock(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void InitBlockUnaligned(void* startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static void InitBlockUnaligned(ref byte startAddress, byte value, uint byteCount)
		{
			// IL initblk instruction
			Unsafe.InitBlockUnaligned(ref startAddress, value, byteCount);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static T As<T>(object o) where T : class
		{
			return (T)o;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T AsRef<T>(void* source)
		{
			return ref *(T*)source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AsRef<T>(in T source)
		{
			return ref source;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref TTo As<TFrom, TTo>(ref TFrom source)
		{
			return ref Unsafe.As<TFrom, TTo>(ref source);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Unbox<T>(object box) where T : struct
		{
			return ref (T)box;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Add<T>(void* source, int elementOffset)
		{
			return (byte*)source + (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Add<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Add<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Add(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T AddByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T AddByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.AddByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, int elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static void* Subtract<T>(void* source, int elementOffset)
		{
			return (byte*)source - (nint)elementOffset * (nint)Unsafe.SizeOf<T>();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T Subtract<T>(ref T source, IntPtr elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T Subtract<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint elementOffset)
		{
			return ref Unsafe.Subtract(ref source, elementOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static ref T SubtractByteOffset<T>(ref T source, IntPtr byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static ref T SubtractByteOffset<T>(ref T source, [System.Runtime.Versioning.NonVersionable] nuint byteOffset)
		{
			return ref Unsafe.SubtractByteOffset(ref source, byteOffset);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static IntPtr ByteOffset<T>(ref T origin, ref T target)
		{
			return Unsafe.ByteOffset(target: ref target, origin: ref origin);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool AreSame<T>(ref T left, ref T right)
		{
			return Unsafe.AreSame(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressGreaterThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressGreaterThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public static bool IsAddressLessThan<T>(ref T left, ref T right)
		{
			return Unsafe.IsAddressLessThan(ref left, ref right);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static bool IsNullRef<T>(ref T source)
		{
			return Unsafe.AsPointer(ref source) == null;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		[System.Runtime.Versioning.NonVersionable]
		public unsafe static ref T NullRef<T>()
		{
			return ref *(T*)null;
		}
	}
}
namespace System.Runtime.Versioning
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class NonVersionableAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	[Microsoft.CodeAnalysis.Embedded]
	[CompilerGenerated]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

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

		public NativeIntegerAttribute(bool[] A_0)
		{
			TransformFlags = A_0;
		}
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}

BepInEx/core/System.Runtime.Serialization.dll

Decompiled 2 weeks ago
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Configuration;
using System.Runtime.Serialization.Diagnostics;
using System.Runtime.Serialization.Diagnostics.Application;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Json;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.XPath;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Runtime.Serialization.dll")]
[assembly: AssemblyDescription("System.Runtime.Serialization.dll")]
[assembly: AssemblyDefaultAlias("System.Runtime.Serialization.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyKeyFile("../ecma.pub")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: SecurityCritical(SecurityCriticalScope.Explicit)]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class SR
{
	internal static string GetString(string name, params object[] args)
	{
		return GetString(CultureInfo.InvariantCulture, name, args);
	}

	internal static string GetString(CultureInfo culture, string name, params object[] args)
	{
		return string.Format(culture, name, args);
	}

	internal static string GetString(string name)
	{
		return name;
	}

	internal static string GetString(CultureInfo culture, string name)
	{
		return name;
	}

	internal static string Format(string resourceFormat, params object[] args)
	{
		if (args != null)
		{
			return string.Format(CultureInfo.InvariantCulture, resourceFormat, args);
		}
		return resourceFormat;
	}

	internal static string Format(string resourceFormat, object p1)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1);
	}

	internal static string Format(string resourceFormat, object p1, object p2)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2);
	}

	internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2)
	{
		return string.Format(ci, resourceFormat, p1, p2);
	}

	internal static string Format(string resourceFormat, object p1, object p2, object p3)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3);
	}

	internal static string GetResourceString(string str)
	{
		return str;
	}
}
namespace System
{
	internal static class LocalAppContextSwitches
	{
		public static readonly bool DoNotUseTimeZoneInfo;

		public static readonly bool DoNotUseEcmaScriptV6EscapeControlCharacter;
	}
	internal static class NotImplemented
	{
		internal static Exception ByDesign => new NotImplementedException();

		internal static Exception ByDesignWithMessage(string message)
		{
			return new NotImplementedException(message);
		}
	}
}
namespace System.Xml
{
	internal abstract class ArrayHelper<TArgument, TArray>
	{
		public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, int maxArrayLength)
		{
			TArray[][] array = null;
			TArray[] array2 = null;
			int num = 0;
			int num2 = 0;
			if (reader.TryGetArrayLength(out var count))
			{
				if (count > maxArrayLength)
				{
					XmlExceptionHelper.ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(reader, maxArrayLength);
				}
				if (count > 65535)
				{
					count = 65535;
				}
			}
			else
			{
				count = 32;
			}
			while (true)
			{
				array2 = new TArray[count];
				int i;
				int num3;
				for (i = 0; i < array2.Length; i += num3)
				{
					num3 = ReadArray(reader, localName, namespaceUri, array2, i, array2.Length - i);
					if (num3 == 0)
					{
						break;
					}
				}
				if (num2 > maxArrayLength - i)
				{
					XmlExceptionHelper.ThrowMaxArrayLengthOrMaxItemsQuotaExceeded(reader, maxArrayLength);
				}
				num2 += i;
				if (i < array2.Length || reader.NodeType == XmlNodeType.EndElement)
				{
					break;
				}
				if (array == null)
				{
					array = new TArray[32][];
				}
				array[num++] = array2;
				count *= 2;
			}
			if (num2 != array2.Length || num > 0)
			{
				TArray[] array3 = new TArray[num2];
				int num4 = 0;
				for (int j = 0; j < num; j++)
				{
					Array.Copy(array[j], 0, array3, num4, array[j].Length);
					num4 += array[j].Length;
				}
				Array.Copy(array2, 0, array3, num4, num2 - num4);
				array2 = array3;
			}
			return array2;
		}

		public void WriteArray(XmlDictionaryWriter writer, string prefix, TArgument localName, TArgument namespaceUri, XmlDictionaryReader reader)
		{
			int count = ((!reader.TryGetArrayLength(out count)) ? 256 : Math.Min(count, 256));
			TArray[] array = new TArray[count];
			while (true)
			{
				int num = ReadArray(reader, localName, namespaceUri, array, 0, array.Length);
				if (num != 0)
				{
					WriteArray(writer, prefix, localName, namespaceUri, array, 0, num);
					continue;
				}
				break;
			}
		}

		protected abstract int ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, TArray[] array, int offset, int count);

		protected abstract void WriteArray(XmlDictionaryWriter writer, string prefix, TArgument localName, TArgument namespaceUri, TArray[] array, int offset, int count);
	}
	internal class BooleanArrayHelperWithString : ArrayHelper<string, bool>
	{
		public static readonly BooleanArrayHelperWithString Instance = new BooleanArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, bool[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, bool[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class BooleanArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, bool>
	{
		public static readonly BooleanArrayHelperWithDictionaryString Instance = new BooleanArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class Int16ArrayHelperWithString : ArrayHelper<string, short>
	{
		public static readonly Int16ArrayHelperWithString Instance = new Int16ArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, short[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, short[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class Int16ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, short>
	{
		public static readonly Int16ArrayHelperWithDictionaryString Instance = new Int16ArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class Int32ArrayHelperWithString : ArrayHelper<string, int>
	{
		public static readonly Int32ArrayHelperWithString Instance = new Int32ArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, int[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, int[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class Int32ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, int>
	{
		public static readonly Int32ArrayHelperWithDictionaryString Instance = new Int32ArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class Int64ArrayHelperWithString : ArrayHelper<string, long>
	{
		public static readonly Int64ArrayHelperWithString Instance = new Int64ArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, long[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, long[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class Int64ArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, long>
	{
		public static readonly Int64ArrayHelperWithDictionaryString Instance = new Int64ArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class SingleArrayHelperWithString : ArrayHelper<string, float>
	{
		public static readonly SingleArrayHelperWithString Instance = new SingleArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, float[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, float[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class SingleArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, float>
	{
		public static readonly SingleArrayHelperWithDictionaryString Instance = new SingleArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class DoubleArrayHelperWithString : ArrayHelper<string, double>
	{
		public static readonly DoubleArrayHelperWithString Instance = new DoubleArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, double[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, double[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class DoubleArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, double>
	{
		public static readonly DoubleArrayHelperWithDictionaryString Instance = new DoubleArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class DecimalArrayHelperWithString : ArrayHelper<string, decimal>
	{
		public static readonly DecimalArrayHelperWithString Instance = new DecimalArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, decimal[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class DecimalArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, decimal>
	{
		public static readonly DecimalArrayHelperWithDictionaryString Instance = new DecimalArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class DateTimeArrayHelperWithString : ArrayHelper<string, DateTime>
	{
		public static readonly DateTimeArrayHelperWithString Instance = new DateTimeArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, DateTime[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class DateTimeArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, DateTime>
	{
		public static readonly DateTimeArrayHelperWithDictionaryString Instance = new DateTimeArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class GuidArrayHelperWithString : ArrayHelper<string, Guid>
	{
		public static readonly GuidArrayHelperWithString Instance = new GuidArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, Guid[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class GuidArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, Guid>
	{
		public static readonly GuidArrayHelperWithDictionaryString Instance = new GuidArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class TimeSpanArrayHelperWithString : ArrayHelper<string, TimeSpan>
	{
		public static readonly TimeSpanArrayHelperWithString Instance = new TimeSpanArrayHelperWithString();

		protected override int ReadArray(XmlDictionaryReader reader, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class TimeSpanArrayHelperWithDictionaryString : ArrayHelper<XmlDictionaryString, TimeSpan>
	{
		public static readonly TimeSpanArrayHelperWithDictionaryString Instance = new TimeSpanArrayHelperWithDictionaryString();

		protected override int ReadArray(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
		{
			return reader.ReadArray(localName, namespaceUri, array, offset, count);
		}

		protected override void WriteArray(XmlDictionaryWriter writer, string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count)
		{
			writer.WriteArray(prefix, localName, namespaceUri, array, offset, count);
		}
	}
	internal class EncodingStreamWrapper : Stream
	{
		private enum SupportedEncoding
		{
			UTF8,
			UTF16LE,
			UTF16BE,
			None
		}

		private static readonly UTF8Encoding SafeUTF8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false);

		private static readonly UnicodeEncoding SafeUTF16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: false);

		private static readonly UnicodeEncoding SafeBEUTF16 = new UnicodeEncoding(bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: false);

		private static readonly UTF8Encoding ValidatingUTF8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

		private static readonly UnicodeEncoding ValidatingUTF16 = new UnicodeEncoding(bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true);

		private static readonly UnicodeEncoding ValidatingBEUTF16 = new UnicodeEncoding(bigEndian: true, byteOrderMark: false, throwOnInvalidBytes: true);

		private const int BufferLength = 128;

		private static readonly byte[] encodingAttr = new byte[8] { 101, 110, 99, 111, 100, 105, 110, 103 };

		private static readonly byte[] encodingUTF8 = new byte[5] { 117, 116, 102, 45, 56 };

		private static readonly byte[] encodingUnicode = new byte[6] { 117, 116, 102, 45, 49, 54 };

		private static readonly byte[] encodingUnicodeLE = new byte[8] { 117, 116, 102, 45, 49, 54, 108, 101 };

		private static readonly byte[] encodingUnicodeBE = new byte[8] { 117, 116, 102, 45, 49, 54, 98, 101 };

		private SupportedEncoding encodingCode;

		private Encoding encoding;

		private Encoder enc;

		private Decoder dec;

		private bool isReading;

		private Stream stream;

		private char[] chars;

		private byte[] bytes;

		private int byteOffset;

		private int byteCount;

		private byte[] byteBuffer = new byte[1];

		public override bool CanRead
		{
			get
			{
				if (!isReading)
				{
					return false;
				}
				return stream.CanRead;
			}
		}

		public override bool CanSeek => false;

		public override bool CanWrite
		{
			get
			{
				if (isReading)
				{
					return false;
				}
				return stream.CanWrite;
			}
		}

		public override long Position
		{
			get
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
			}
			set
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
			}
		}

		public override bool CanTimeout => stream.CanTimeout;

		public override long Length => stream.Length;

		public override int ReadTimeout
		{
			get
			{
				return stream.ReadTimeout;
			}
			set
			{
				stream.ReadTimeout = value;
			}
		}

		public override int WriteTimeout
		{
			get
			{
				return stream.WriteTimeout;
			}
			set
			{
				stream.WriteTimeout = value;
			}
		}

		public EncodingStreamWrapper(Stream stream, Encoding encoding)
		{
			try
			{
				isReading = true;
				this.stream = new BufferedStream(stream);
				SupportedEncoding supportedEncoding = GetSupportedEncoding(encoding);
				SupportedEncoding supportedEncoding2 = ReadBOMEncoding(encoding == null);
				if (supportedEncoding != SupportedEncoding.None && supportedEncoding != supportedEncoding2)
				{
					ThrowExpectedEncodingMismatch(supportedEncoding, supportedEncoding2);
				}
				if (supportedEncoding2 == SupportedEncoding.UTF8)
				{
					FillBuffer(2);
					if (bytes[byteOffset + 1] == 63 && bytes[byteOffset] == 60)
					{
						FillBuffer(128);
						CheckUTF8DeclarationEncoding(bytes, byteOffset, byteCount, supportedEncoding2, supportedEncoding);
					}
					return;
				}
				EnsureBuffers();
				FillBuffer(254);
				SetReadDocumentEncoding(supportedEncoding2);
				CleanupCharBreak();
				int charCount = this.encoding.GetChars(bytes, byteOffset, byteCount, chars, 0);
				byteOffset = 0;
				byteCount = ValidatingUTF8.GetBytes(chars, 0, charCount, bytes, 0);
				if (bytes[1] == 63 && bytes[0] == 60)
				{
					CheckUTF8DeclarationEncoding(bytes, 0, byteCount, supportedEncoding2, supportedEncoding);
				}
				else if (supportedEncoding == SupportedEncoding.None)
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents.")));
				}
			}
			catch (DecoderFallbackException innerException)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException));
			}
		}

		private void SetReadDocumentEncoding(SupportedEncoding e)
		{
			EnsureBuffers();
			encodingCode = e;
			encoding = GetEncoding(e);
		}

		private static Encoding GetEncoding(SupportedEncoding e)
		{
			return e switch
			{
				SupportedEncoding.UTF8 => ValidatingUTF8, 
				SupportedEncoding.UTF16LE => ValidatingUTF16, 
				SupportedEncoding.UTF16BE => ValidatingBEUTF16, 
				_ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), 
			};
		}

		private static Encoding GetSafeEncoding(SupportedEncoding e)
		{
			return e switch
			{
				SupportedEncoding.UTF8 => SafeUTF8, 
				SupportedEncoding.UTF16LE => SafeUTF16, 
				SupportedEncoding.UTF16BE => SafeBEUTF16, 
				_ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), 
			};
		}

		private static string GetEncodingName(SupportedEncoding enc)
		{
			return enc switch
			{
				SupportedEncoding.UTF8 => "utf-8", 
				SupportedEncoding.UTF16LE => "utf-16LE", 
				SupportedEncoding.UTF16BE => "utf-16BE", 
				_ => throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported."))), 
			};
		}

		private static SupportedEncoding GetSupportedEncoding(Encoding encoding)
		{
			if (encoding == null)
			{
				return SupportedEncoding.None;
			}
			if (encoding.WebName == ValidatingUTF8.WebName)
			{
				return SupportedEncoding.UTF8;
			}
			if (encoding.WebName == ValidatingUTF16.WebName)
			{
				return SupportedEncoding.UTF16LE;
			}
			if (encoding.WebName == ValidatingBEUTF16.WebName)
			{
				return SupportedEncoding.UTF16BE;
			}
			throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("XML encoding not supported.")));
		}

		public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM)
		{
			isReading = false;
			this.encoding = encoding;
			this.stream = new BufferedStream(stream);
			encodingCode = GetSupportedEncoding(encoding);
			if (encodingCode == SupportedEncoding.UTF8)
			{
				return;
			}
			EnsureBuffers();
			dec = ValidatingUTF8.GetDecoder();
			enc = this.encoding.GetEncoder();
			if (emitBOM)
			{
				byte[] preamble = this.encoding.GetPreamble();
				if (preamble.Length != 0)
				{
					this.stream.Write(preamble, 0, preamble.Length);
				}
			}
		}

		private SupportedEncoding ReadBOMEncoding(bool notOutOfBand)
		{
			int num = stream.ReadByte();
			int num2 = stream.ReadByte();
			int num3 = stream.ReadByte();
			int num4 = stream.ReadByte();
			if (num4 == -1)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file.")));
			}
			int preserve;
			SupportedEncoding result = ReadBOMEncoding((byte)num, (byte)num2, (byte)num3, (byte)num4, notOutOfBand, out preserve);
			EnsureByteBuffer();
			switch (preserve)
			{
			case 1:
				bytes[0] = (byte)num4;
				break;
			case 2:
				bytes[0] = (byte)num3;
				bytes[1] = (byte)num4;
				break;
			case 4:
				bytes[0] = (byte)num;
				bytes[1] = (byte)num2;
				bytes[2] = (byte)num3;
				bytes[3] = (byte)num4;
				break;
			}
			byteCount = preserve;
			return result;
		}

		private static SupportedEncoding ReadBOMEncoding(byte b1, byte b2, byte b3, byte b4, bool notOutOfBand, out int preserve)
		{
			SupportedEncoding result = SupportedEncoding.UTF8;
			preserve = 0;
			if (b1 == 60 && b2 != 0)
			{
				result = SupportedEncoding.UTF8;
				preserve = 4;
			}
			else if (b1 == byte.MaxValue && b2 == 254)
			{
				result = SupportedEncoding.UTF16LE;
				preserve = 2;
			}
			else if (b1 == 254 && b2 == byte.MaxValue)
			{
				result = SupportedEncoding.UTF16BE;
				preserve = 2;
			}
			else if (b1 == 0 && b2 == 60)
			{
				result = SupportedEncoding.UTF16BE;
				if (notOutOfBand && (b3 != 0 || b4 != 63))
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration is required for all non-UTF8 documents.")));
				}
				preserve = 4;
			}
			else if (b1 == 60 && b2 == 0)
			{
				result = SupportedEncoding.UTF16LE;
				if (notOutOfBand && (b3 != 63 || b4 != 0))
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration is required for all non-UTF8 documents.")));
				}
				preserve = 4;
			}
			else if (b1 == 239 && b2 == 187)
			{
				if (notOutOfBand && b3 != 191)
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unrecognized Byte Order Mark.")));
				}
				preserve = 1;
			}
			else
			{
				preserve = 4;
			}
			return result;
		}

		private void FillBuffer(int count)
		{
			count -= byteCount;
			while (count > 0)
			{
				int num = stream.Read(bytes, byteOffset + byteCount, count);
				if (num != 0)
				{
					byteCount += num;
					count -= num;
					continue;
				}
				break;
			}
		}

		private void EnsureBuffers()
		{
			EnsureByteBuffer();
			if (chars == null)
			{
				chars = new char[128];
			}
		}

		private void EnsureByteBuffer()
		{
			if (bytes == null)
			{
				bytes = new byte[512];
				byteOffset = 0;
				byteCount = 0;
			}
		}

		private static void CheckUTF8DeclarationEncoding(byte[] buffer, int offset, int count, SupportedEncoding e, SupportedEncoding expectedEnc)
		{
			byte b = 0;
			int num = -1;
			int num2 = offset + Math.Min(count, 128);
			int num3 = 0;
			int num4 = 0;
			for (num3 = offset + 2; num3 < num2; num3++)
			{
				if (b != 0)
				{
					if (buffer[num3] == b)
					{
						b = 0;
					}
				}
				else if (buffer[num3] == 39 || buffer[num3] == 34)
				{
					b = buffer[num3];
				}
				else if (buffer[num3] == 61)
				{
					if (num4 == 1)
					{
						num = num3;
						break;
					}
					num4++;
				}
				else if (buffer[num3] == 63)
				{
					break;
				}
			}
			if (num == -1)
			{
				if (e != 0 && expectedEnc == SupportedEncoding.None)
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents.")));
				}
				return;
			}
			if (num < 28)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration.")));
			}
			num3 = num - 1;
			while (IsWhitespace(buffer[num3]))
			{
				num3--;
			}
			if (!Compare(encodingAttr, buffer, num3 - encodingAttr.Length + 1))
			{
				if (e == SupportedEncoding.UTF8 || expectedEnc != SupportedEncoding.None)
				{
					return;
				}
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents.")));
			}
			for (num3 = num + 1; num3 < num2 && IsWhitespace(buffer[num3]); num3++)
			{
			}
			if (buffer[num3] != 39 && buffer[num3] != 34)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration.")));
			}
			b = buffer[num3];
			int num5 = num3++;
			for (; buffer[num3] != b && num3 < num2; num3++)
			{
			}
			if (buffer[num3] != b)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Malformed XML declaration.")));
			}
			int num6 = num5 + 1;
			int num7 = num3 - num6;
			SupportedEncoding supportedEncoding = e;
			if (num7 == encodingUTF8.Length && CompareCaseInsensitive(encodingUTF8, buffer, num6))
			{
				supportedEncoding = SupportedEncoding.UTF8;
			}
			else if (num7 == encodingUnicodeLE.Length && CompareCaseInsensitive(encodingUnicodeLE, buffer, num6))
			{
				supportedEncoding = SupportedEncoding.UTF16LE;
			}
			else if (num7 == encodingUnicodeBE.Length && CompareCaseInsensitive(encodingUnicodeBE, buffer, num6))
			{
				supportedEncoding = SupportedEncoding.UTF16BE;
			}
			else if (num7 == encodingUnicode.Length && CompareCaseInsensitive(encodingUnicode, buffer, num6))
			{
				if (e == SupportedEncoding.UTF8)
				{
					ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), SafeUTF8.GetString(encodingUTF8, 0, encodingUTF8.Length));
				}
			}
			else
			{
				ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), e);
			}
			if (e != supportedEncoding)
			{
				ThrowEncodingMismatch(SafeUTF8.GetString(buffer, num6, num7), e);
			}
		}

		private static bool CompareCaseInsensitive(byte[] key, byte[] buffer, int offset)
		{
			for (int i = 0; i < key.Length; i++)
			{
				if (key[i] != buffer[offset + i] && key[i] != char.ToLower((char)buffer[offset + i], CultureInfo.InvariantCulture))
				{
					return false;
				}
			}
			return true;
		}

		private static bool Compare(byte[] key, byte[] buffer, int offset)
		{
			for (int i = 0; i < key.Length; i++)
			{
				if (key[i] != buffer[offset + i])
				{
					return false;
				}
			}
			return true;
		}

		private static bool IsWhitespace(byte ch)
		{
			if (ch != 32 && ch != 10 && ch != 9)
			{
				return ch == 13;
			}
			return true;
		}

		internal static ArraySegment<byte> ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding)
		{
			if (count < 4)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file.")));
			}
			try
			{
				SupportedEncoding supportedEncoding = GetSupportedEncoding(encoding);
				int preserve;
				SupportedEncoding supportedEncoding2 = ReadBOMEncoding(buffer[offset], buffer[offset + 1], buffer[offset + 2], buffer[offset + 3], encoding == null, out preserve);
				if (supportedEncoding != SupportedEncoding.None && supportedEncoding != supportedEncoding2)
				{
					ThrowExpectedEncodingMismatch(supportedEncoding, supportedEncoding2);
				}
				offset += 4 - preserve;
				count -= 4 - preserve;
				if (supportedEncoding2 == SupportedEncoding.UTF8)
				{
					if (buffer[offset + 1] != 63 || buffer[offset] != 60)
					{
						return new ArraySegment<byte>(buffer, offset, count);
					}
					CheckUTF8DeclarationEncoding(buffer, offset, count, supportedEncoding2, supportedEncoding);
					return new ArraySegment<byte>(buffer, offset, count);
				}
				Encoding safeEncoding = GetSafeEncoding(supportedEncoding2);
				int num = Math.Min(count, 256);
				char[] array = new char[safeEncoding.GetMaxCharCount(num)];
				int charCount = safeEncoding.GetChars(buffer, offset, num, array, 0);
				byte[] array2 = new byte[ValidatingUTF8.GetMaxByteCount(charCount)];
				int count2 = ValidatingUTF8.GetBytes(array, 0, charCount, array2, 0);
				if (array2[1] == 63 && array2[0] == 60)
				{
					CheckUTF8DeclarationEncoding(array2, 0, count2, supportedEncoding2, supportedEncoding);
				}
				else if (supportedEncoding == SupportedEncoding.None)
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("An XML declaration with an encoding is required for all non-UTF8 documents.")));
				}
				return new ArraySegment<byte>(ValidatingUTF8.GetBytes(GetEncoding(supportedEncoding2).GetChars(buffer, offset, count)));
			}
			catch (DecoderFallbackException innerException)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException));
			}
		}

		private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, SupportedEncoding actualEnc)
		{
			throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("The expected encoding '{0}' does not match the actual encoding '{1}'.", GetEncodingName(expEnc), GetEncodingName(actualEnc))));
		}

		private static void ThrowEncodingMismatch(string declEnc, SupportedEncoding enc)
		{
			ThrowEncodingMismatch(declEnc, GetEncodingName(enc));
		}

		private static void ThrowEncodingMismatch(string declEnc, string docEnc)
		{
			throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("The encoding in the declaration '{0}' does not match the encoding of the document '{1}'.", declEnc, docEnc)));
		}

		public override void Close()
		{
			Flush();
			base.Close();
			stream.Close();
		}

		public override void Flush()
		{
			stream.Flush();
		}

		public override int ReadByte()
		{
			if (byteCount == 0 && encodingCode == SupportedEncoding.UTF8)
			{
				return stream.ReadByte();
			}
			if (Read(byteBuffer, 0, 1) == 0)
			{
				return -1;
			}
			return byteBuffer[0];
		}

		public override int Read(byte[] buffer, int offset, int count)
		{
			try
			{
				if (byteCount == 0)
				{
					if (encodingCode == SupportedEncoding.UTF8)
					{
						return stream.Read(buffer, offset, count);
					}
					byteOffset = 0;
					byteCount = stream.Read(bytes, byteCount, (chars.Length - 1) * 2);
					if (byteCount == 0)
					{
						return 0;
					}
					CleanupCharBreak();
					int charCount = encoding.GetChars(bytes, 0, byteCount, chars, 0);
					byteCount = Encoding.UTF8.GetBytes(chars, 0, charCount, bytes, 0);
				}
				if (byteCount < count)
				{
					count = byteCount;
				}
				Buffer.BlockCopy(bytes, byteOffset, buffer, offset, count);
				byteOffset += count;
				byteCount -= count;
				return count;
			}
			catch (DecoderFallbackException innerException)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Invalid byte encoding."), innerException));
			}
		}

		private void CleanupCharBreak()
		{
			int num = byteOffset + byteCount;
			if (byteCount % 2 != 0)
			{
				int num2 = stream.ReadByte();
				if (num2 < 0)
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file.")));
				}
				bytes[num++] = (byte)num2;
				byteCount++;
			}
			int num3 = ((encodingCode != SupportedEncoding.UTF16LE) ? (bytes[num - 1] + (bytes[num - 2] << 8)) : (bytes[num - 2] + (bytes[num - 1] << 8)));
			if ((num3 & 0xDC00) != 56320 && num3 >= 55296 && num3 <= 56319)
			{
				int num4 = stream.ReadByte();
				int num5 = stream.ReadByte();
				if (num5 < 0)
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(System.Runtime.Serialization.SR.GetString("Unexpected end of file.")));
				}
				bytes[num++] = (byte)num4;
				bytes[num++] = (byte)num5;
				byteCount += 2;
			}
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
		}

		public override void WriteByte(byte b)
		{
			if (encodingCode == SupportedEncoding.UTF8)
			{
				stream.WriteByte(b);
				return;
			}
			byteBuffer[0] = b;
			Write(byteBuffer, 0, 1);
		}

		public override void Write(byte[] buffer, int offset, int count)
		{
			if (encodingCode == SupportedEncoding.UTF8)
			{
				stream.Write(buffer, offset, count);
				return;
			}
			while (count > 0)
			{
				int num = ((chars.Length < count) ? chars.Length : count);
				int charCount = dec.GetChars(buffer, offset, num, chars, 0, flush: false);
				byteCount = enc.GetBytes(chars, 0, charCount, bytes, 0, flush: false);
				stream.Write(bytes, 0, byteCount);
				offset += num;
				count -= num;
			}
		}

		public override void SetLength(long value)
		{
			throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
		}
	}
	public interface IFragmentCapableXmlDictionaryWriter
	{
		bool CanFragment { get; }

		void StartFragment(Stream stream, bool generateSelfContainedTextFragment);

		void EndFragment();

		void WriteFragment(byte[] buffer, int offset, int count);
	}
	public interface IStreamProvider
	{
		Stream GetStream();

		void ReleaseStream(Stream stream);
	}
	public interface IXmlDictionary
	{
		bool TryLookup(string value, out XmlDictionaryString result);

		bool TryLookup(int key, out XmlDictionaryString result);

		bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result);
	}
	internal enum PrefixHandleType
	{
		Empty,
		A,
		B,
		C,
		D,
		E,
		F,
		G,
		H,
		I,
		J,
		K,
		L,
		M,
		N,
		O,
		P,
		Q,
		R,
		S,
		T,
		U,
		V,
		W,
		X,
		Y,
		Z,
		Buffer,
		Max
	}
	internal class PrefixHandle
	{
		private XmlBufferReader bufferReader;

		private PrefixHandleType type;

		private int offset;

		private int length;

		private static string[] prefixStrings = new string[27]
		{
			"", "a", "b", "c", "d", "e", "f", "g", "h", "i",
			"j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
			"t", "u", "v", "w", "x", "y", "z"
		};

		private static byte[] prefixBuffer = new byte[26]
		{
			97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
			107, 108, 109, 110, 111, 112, 113, 114, 115, 116,
			117, 118, 119, 120, 121, 122
		};

		public bool IsEmpty => type == PrefixHandleType.Empty;

		public bool IsXmlns
		{
			get
			{
				if (type != PrefixHandleType.Buffer)
				{
					return false;
				}
				if (length != 5)
				{
					return false;
				}
				byte[] buffer = bufferReader.Buffer;
				int num = offset;
				if (buffer[num] == 120 && buffer[num + 1] == 109 && buffer[num + 2] == 108 && buffer[num + 3] == 110)
				{
					return buffer[num + 4] == 115;
				}
				return false;
			}
		}

		public bool IsXml
		{
			get
			{
				if (type != PrefixHandleType.Buffer)
				{
					return false;
				}
				if (length != 3)
				{
					return false;
				}
				byte[] buffer = bufferReader.Buffer;
				int num = offset;
				if (buffer[num] == 120 && buffer[num + 1] == 109)
				{
					return buffer[num + 2] == 108;
				}
				return false;
			}
		}

		public PrefixHandle(XmlBufferReader bufferReader)
		{
			this.bufferReader = bufferReader;
		}

		public void SetValue(PrefixHandleType type)
		{
			this.type = type;
		}

		public void SetValue(PrefixHandle prefix)
		{
			type = prefix.type;
			offset = prefix.offset;
			length = prefix.length;
		}

		public void SetValue(int offset, int length)
		{
			switch (length)
			{
			case 0:
				SetValue(PrefixHandleType.Empty);
				return;
			case 1:
			{
				byte @byte = bufferReader.GetByte(offset);
				if (@byte >= 97 && @byte <= 122)
				{
					SetValue(GetAlphaPrefix(@byte - 97));
					return;
				}
				break;
			}
			}
			type = PrefixHandleType.Buffer;
			this.offset = offset;
			this.length = length;
		}

		public bool TryGetShortPrefix(out PrefixHandleType type)
		{
			type = this.type;
			return type != PrefixHandleType.Buffer;
		}

		public static string GetString(PrefixHandleType type)
		{
			return prefixStrings[(int)type];
		}

		public static PrefixHandleType GetAlphaPrefix(int index)
		{
			return (PrefixHandleType)(1 + index);
		}

		public static byte[] GetString(PrefixHandleType type, out int offset, out int length)
		{
			if (type == PrefixHandleType.Empty)
			{
				offset = 0;
				length = 0;
			}
			else
			{
				length = 1;
				offset = (int)(type - 1);
			}
			return prefixBuffer;
		}

		public string GetString(XmlNameTable nameTable)
		{
			PrefixHandleType prefixHandleType = type;
			if (prefixHandleType != PrefixHandleType.Buffer)
			{
				return GetString(prefixHandleType);
			}
			return bufferReader.GetString(offset, length, nameTable);
		}

		public string GetString()
		{
			PrefixHandleType prefixHandleType = type;
			if (prefixHandleType != PrefixHandleType.Buffer)
			{
				return GetString(prefixHandleType);
			}
			return bufferReader.GetString(offset, length);
		}

		public byte[] GetString(out int offset, out int length)
		{
			PrefixHandleType prefixHandleType = type;
			if (prefixHandleType != PrefixHandleType.Buffer)
			{
				return GetString(prefixHandleType, out offset, out length);
			}
			offset = this.offset;
			length = this.length;
			return bufferReader.Buffer;
		}

		public int CompareTo(PrefixHandle that)
		{
			return GetString().CompareTo(that.GetString());
		}

		private bool Equals2(PrefixHandle prefix2)
		{
			PrefixHandleType prefixHandleType = type;
			PrefixHandleType prefixHandleType2 = prefix2.type;
			if (prefixHandleType != prefixHandleType2)
			{
				return false;
			}
			if (prefixHandleType != PrefixHandleType.Buffer)
			{
				return true;
			}
			if (bufferReader == prefix2.bufferReader)
			{
				return bufferReader.Equals2(offset, length, prefix2.offset, prefix2.length);
			}
			return bufferReader.Equals2(offset, length, prefix2.bufferReader, prefix2.offset, prefix2.length);
		}

		private bool Equals2(string prefix2)
		{
			PrefixHandleType prefixHandleType = type;
			if (prefixHandleType != PrefixHandleType.Buffer)
			{
				return GetString(prefixHandleType) == prefix2;
			}
			return bufferReader.Equals2(offset, length, prefix2);
		}

		private bool Equals2(XmlDictionaryString prefix2)
		{
			return Equals2(prefix2.Value);
		}

		public static bool operator ==(PrefixHandle prefix1, string prefix2)
		{
			return prefix1.Equals2(prefix2);
		}

		public static bool operator !=(PrefixHandle prefix1, string prefix2)
		{
			return !prefix1.Equals2(prefix2);
		}

		public static bool operator ==(PrefixHandle prefix1, XmlDictionaryString prefix2)
		{
			return prefix1.Equals2(prefix2);
		}

		public static bool operator !=(PrefixHandle prefix1, XmlDictionaryString prefix2)
		{
			return !prefix1.Equals2(prefix2);
		}

		public static bool operator ==(PrefixHandle prefix1, PrefixHandle prefix2)
		{
			return prefix1.Equals2(prefix2);
		}

		public static bool operator !=(PrefixHandle prefix1, PrefixHandle prefix2)
		{
			return !prefix1.Equals2(prefix2);
		}

		public override bool Equals(object obj)
		{
			if (!(obj is PrefixHandle prefixHandle))
			{
				return false;
			}
			return this == prefixHandle;
		}

		public override string ToString()
		{
			return GetString();
		}

		public override int GetHashCode()
		{
			return GetString().GetHashCode();
		}
	}
	internal enum StringHandleConstStringType
	{
		Type,
		Root,
		Item
	}
	internal class StringHandle
	{
		private enum StringHandleType
		{
			Dictionary,
			UTF8,
			EscapedUTF8,
			ConstString
		}

		private XmlBufferReader bufferReader;

		private StringHandleType type;

		private int key;

		private int offset;

		private int length;

		private static string[] constStrings = new string[3] { "type", "root", "item" };

		public bool IsEmpty
		{
			get
			{
				if (type == StringHandleType.UTF8)
				{
					return length == 0;
				}
				return Equals2(string.Empty);
			}
		}

		public bool IsXmlns
		{
			get
			{
				if (type == StringHandleType.UTF8)
				{
					if (length != 5)
					{
						return false;
					}
					byte[] buffer = bufferReader.Buffer;
					int num = offset;
					if (buffer[num] == 120 && buffer[num + 1] == 109 && buffer[num + 2] == 108 && buffer[num + 3] == 110)
					{
						return buffer[num + 4] == 115;
					}
					return false;
				}
				return Equals2("xmlns");
			}
		}

		public StringHandle(XmlBufferReader bufferReader)
		{
			this.bufferReader = bufferReader;
			SetValue(0, 0);
		}

		public void SetValue(int offset, int length)
		{
			type = StringHandleType.UTF8;
			this.offset = offset;
			this.length = length;
		}

		public void SetConstantValue(StringHandleConstStringType constStringType)
		{
			type = StringHandleType.ConstString;
			key = (int)constStringType;
		}

		public void SetValue(int offset, int length, bool escaped)
		{
			type = ((!escaped) ? StringHandleType.UTF8 : StringHandleType.EscapedUTF8);
			this.offset = offset;
			this.length = length;
		}

		public void SetValue(int key)
		{
			type = StringHandleType.Dictionary;
			this.key = key;
		}

		public void SetValue(StringHandle value)
		{
			type = value.type;
			key = value.key;
			offset = value.offset;
			length = value.length;
		}

		public void ToPrefixHandle(PrefixHandle prefix)
		{
			prefix.SetValue(offset, length);
		}

		public string GetString(XmlNameTable nameTable)
		{
			return type switch
			{
				StringHandleType.UTF8 => bufferReader.GetString(offset, length, nameTable), 
				StringHandleType.Dictionary => nameTable.Add(bufferReader.GetDictionaryString(key).Value), 
				StringHandleType.ConstString => nameTable.Add(constStrings[key]), 
				_ => bufferReader.GetEscapedString(offset, length, nameTable), 
			};
		}

		public string GetString()
		{
			return type switch
			{
				StringHandleType.UTF8 => bufferReader.GetString(offset, length), 
				StringHandleType.Dictionary => bufferReader.GetDictionaryString(key).Value, 
				StringHandleType.ConstString => constStrings[key], 
				_ => bufferReader.GetEscapedString(offset, length), 
			};
		}

		public byte[] GetString(out int offset, out int length)
		{
			switch (type)
			{
			case StringHandleType.UTF8:
				offset = this.offset;
				length = this.length;
				return bufferReader.Buffer;
			case StringHandleType.Dictionary:
			{
				byte[] array3 = bufferReader.GetDictionaryString(key).ToUTF8();
				offset = 0;
				length = array3.Length;
				return array3;
			}
			case StringHandleType.ConstString:
			{
				byte[] array2 = XmlConverter.ToBytes(constStrings[key]);
				offset = 0;
				length = array2.Length;
				return array2;
			}
			default:
			{
				byte[] array = XmlConverter.ToBytes(bufferReader.GetEscapedString(this.offset, this.length));
				offset = 0;
				length = array.Length;
				return array;
			}
			}
		}

		public bool TryGetDictionaryString(out XmlDictionaryString value)
		{
			if (type == StringHandleType.Dictionary)
			{
				value = bufferReader.GetDictionaryString(key);
				return true;
			}
			if (IsEmpty)
			{
				value = XmlDictionaryString.Empty;
				return true;
			}
			value = null;
			return false;
		}

		public override string ToString()
		{
			return GetString();
		}

		private bool Equals2(int key2, XmlBufferReader bufferReader2)
		{
			return type switch
			{
				StringHandleType.Dictionary => bufferReader.Equals2(key, key2, bufferReader2), 
				StringHandleType.UTF8 => bufferReader.Equals2(offset, length, bufferReader2.GetDictionaryString(key2).Value), 
				_ => GetString() == bufferReader.GetDictionaryString(key2).Value, 
			};
		}

		private bool Equals2(XmlDictionaryString xmlString2)
		{
			return type switch
			{
				StringHandleType.Dictionary => bufferReader.Equals2(key, xmlString2), 
				StringHandleType.UTF8 => bufferReader.Equals2(offset, length, xmlString2.ToUTF8()), 
				_ => GetString() == xmlString2.Value, 
			};
		}

		private bool Equals2(string s2)
		{
			return type switch
			{
				StringHandleType.Dictionary => bufferReader.GetDictionaryString(key).Value == s2, 
				StringHandleType.UTF8 => bufferReader.Equals2(offset, length, s2), 
				_ => GetString() == s2, 
			};
		}

		private bool Equals2(int offset2, int length2, XmlBufferReader bufferReader2)
		{
			return type switch
			{
				StringHandleType.Dictionary => bufferReader2.Equals2(offset2, length2, bufferReader.GetDictionaryString(key).Value), 
				StringHandleType.UTF8 => bufferReader.Equals2(offset, length, bufferReader2, offset2, length2), 
				_ => GetString() == bufferReader.GetString(offset2, length2), 
			};
		}

		private bool Equals2(StringHandle s2)
		{
			return s2.type switch
			{
				StringHandleType.Dictionary => Equals2(s2.key, s2.bufferReader), 
				StringHandleType.UTF8 => Equals2(s2.offset, s2.length, s2.bufferReader), 
				_ => Equals2(s2.GetString()), 
			};
		}

		public static bool operator ==(StringHandle s1, XmlDictionaryString xmlString2)
		{
			return s1.Equals2(xmlString2);
		}

		public static bool operator !=(StringHandle s1, XmlDictionaryString xmlString2)
		{
			return !s1.Equals2(xmlString2);
		}

		public static bool operator ==(StringHandle s1, string s2)
		{
			return s1.Equals2(s2);
		}

		public static bool operator !=(StringHandle s1, string s2)
		{
			return !s1.Equals2(s2);
		}

		public static bool operator ==(StringHandle s1, StringHandle s2)
		{
			return s1.Equals2(s2);
		}

		public static bool operator !=(StringHandle s1, StringHandle s2)
		{
			return !s1.Equals2(s2);
		}

		public int CompareTo(StringHandle that)
		{
			if (type == StringHandleType.UTF8 && that.type == StringHandleType.UTF8)
			{
				return bufferReader.Compare(offset, length, that.offset, that.length);
			}
			return string.Compare(GetString(), that.GetString(), StringComparison.Ordinal);
		}

		public override bool Equals(object obj)
		{
			if (!(obj is StringHandle stringHandle))
			{
				return false;
			}
			return this == stringHandle;
		}

		public override int GetHashCode()
		{
			return GetString().GetHashCode();
		}
	}
	public class UniqueId
	{
		private long idLow;

		private long idHigh;

		[SecurityCritical]
		private string s;

		private const int guidLength = 16;

		private const int uuidLength = 45;

		private static short[] char2val = new short[256]
		{
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 0, 16,
			32, 48, 64, 80, 96, 112, 128, 144, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 160, 176, 192,
			208, 224, 240, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 0, 1, 2, 3,
			4, 5, 6, 7, 8, 9, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 10, 11, 12, 13, 14,
			15, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256, 256, 256, 256, 256,
			256, 256, 256, 256, 256, 256
		};

		private const string val2char = "0123456789abcdef";

		public int CharArrayLength
		{
			[SecuritySafeCritical]
			get
			{
				if (s != null)
				{
					return s.Length;
				}
				return 45;
			}
		}

		public bool IsGuid => (idLow | idHigh) != 0;

		public UniqueId()
			: this(Guid.NewGuid())
		{
		}

		public UniqueId(Guid guid)
			: this(guid.ToByteArray())
		{
		}

		public UniqueId(byte[] guid)
			: this(guid, 0)
		{
		}

		[SecuritySafeCritical]
		public unsafe UniqueId(byte[] guid, int offset)
		{
			if (guid == null)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("guid"));
			}
			if (offset < 0)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative.")));
			}
			if (offset > guid.Length)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", guid.Length)));
			}
			if (16 > guid.Length - offset)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.Runtime.Serialization.SR.GetString("Array too small.  Length of available data must be at least {0}.", 16), "guid"));
			}
			fixed (byte* ptr = &guid[offset])
			{
				idLow = UnsafeGetInt64(ptr);
				idHigh = UnsafeGetInt64(ptr + 8);
			}
		}

		[SecuritySafeCritical]
		public unsafe UniqueId(string value)
		{
			if (value == null)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
			}
			if (value.Length == 0)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("UniqueId cannot be zero length.")));
			}
			fixed (char* chars = value)
			{
				UnsafeParse(chars, value.Length);
			}
			s = value;
		}

		[SecuritySafeCritical]
		public unsafe UniqueId(char[] chars, int offset, int count)
		{
			if (chars == null)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
			}
			if (offset < 0)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative.")));
			}
			if (offset > chars.Length)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length)));
			}
			if (count < 0)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative.")));
			}
			if (count > chars.Length - offset)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("count", System.Runtime.Serialization.SR.GetString("The specified size exceeds the remaining buffer space ({0} bytes).", chars.Length - offset)));
			}
			if (count == 0)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new FormatException(System.Runtime.Serialization.SR.GetString("UniqueId cannot be zero length.")));
			}
			fixed (char* chars2 = &chars[offset])
			{
				UnsafeParse(chars2, count);
			}
			if (!IsGuid)
			{
				s = new string(chars, offset, count);
			}
		}

		[SecurityCritical]
		private unsafe int UnsafeDecode(short* char2val, char ch1, char ch2)
		{
			if ((ch1 | ch2) >= 128)
			{
				return 256;
			}
			return char2val[(int)ch1] | char2val[128 + ch2];
		}

		[SecurityCritical]
		private unsafe void UnsafeEncode(char* val2char, byte b, char* pch)
		{
			*pch = val2char[b >> 4];
			pch[1] = val2char[b & 0xF];
		}

		[SecurityCritical]
		private unsafe void UnsafeParse(char* chars, int charCount)
		{
			if (charCount != 45 || *chars != 'u' || chars[1] != 'r' || chars[2] != 'n' || chars[3] != ':' || chars[4] != 'u' || chars[5] != 'u' || chars[6] != 'i' || chars[7] != 'd' || chars[8] != ':' || chars[17] != '-' || chars[22] != '-' || chars[27] != '-' || chars[32] != '-')
			{
				return;
			}
			byte* ptr = stackalloc byte[16];
			int num = 0;
			fixed (short* ptr2 = char2val)
			{
				short* ptr3 = ptr2;
				num = UnsafeDecode(ptr3, chars[15], chars[16]);
				*ptr = (byte)num;
				int num2 = 0 | num;
				num = UnsafeDecode(ptr3, chars[13], chars[14]);
				ptr[1] = (byte)num;
				int num3 = num2 | num;
				num = UnsafeDecode(ptr3, chars[11], chars[12]);
				ptr[2] = (byte)num;
				int num4 = num3 | num;
				num = UnsafeDecode(ptr3, chars[9], chars[10]);
				ptr[3] = (byte)num;
				int num5 = num4 | num;
				num = UnsafeDecode(ptr3, chars[20], chars[21]);
				ptr[4] = (byte)num;
				int num6 = num5 | num;
				num = UnsafeDecode(ptr3, chars[18], chars[19]);
				ptr[5] = (byte)num;
				int num7 = num6 | num;
				num = UnsafeDecode(ptr3, chars[25], chars[26]);
				ptr[6] = (byte)num;
				int num8 = num7 | num;
				num = UnsafeDecode(ptr3, chars[23], chars[24]);
				ptr[7] = (byte)num;
				int num9 = num8 | num;
				num = UnsafeDecode(ptr3, chars[28], chars[29]);
				ptr[8] = (byte)num;
				int num10 = num9 | num;
				num = UnsafeDecode(ptr3, chars[30], chars[31]);
				ptr[9] = (byte)num;
				int num11 = num10 | num;
				num = UnsafeDecode(ptr3, chars[33], chars[34]);
				ptr[10] = (byte)num;
				int num12 = num11 | num;
				num = UnsafeDecode(ptr3, chars[35], chars[36]);
				ptr[11] = (byte)num;
				int num13 = num12 | num;
				num = UnsafeDecode(ptr3, chars[37], chars[38]);
				ptr[12] = (byte)num;
				int num14 = num13 | num;
				num = UnsafeDecode(ptr3, chars[39], chars[40]);
				ptr[13] = (byte)num;
				int num15 = num14 | num;
				num = UnsafeDecode(ptr3, chars[41], chars[42]);
				ptr[14] = (byte)num;
				int num16 = num15 | num;
				num = UnsafeDecode(ptr3, chars[43], chars[44]);
				ptr[15] = (byte)num;
				if ((num16 | num) >= 256)
				{
					return;
				}
				idLow = UnsafeGetInt64(ptr);
				idHigh = UnsafeGetInt64(ptr + 8);
			}
		}

		[SecuritySafeCritical]
		public unsafe int ToCharArray(char[] chars, int offset)
		{
			int charArrayLength = CharArrayLength;
			if (chars == null)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("chars"));
			}
			if (offset < 0)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative.")));
			}
			if (offset > chars.Length)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", chars.Length)));
			}
			if (charArrayLength > chars.Length - offset)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("chars", System.Runtime.Serialization.SR.GetString("Array too small.  Must be able to hold at least {0}.", charArrayLength)));
			}
			if (s != null)
			{
				s.CopyTo(0, chars, offset, charArrayLength);
			}
			else
			{
				byte* ptr = stackalloc byte[16];
				UnsafeSetInt64(idLow, ptr);
				UnsafeSetInt64(idHigh, ptr + 8);
				fixed (char* ptr2 = &chars[offset])
				{
					*ptr2 = 'u';
					ptr2[1] = 'r';
					ptr2[2] = 'n';
					ptr2[3] = ':';
					ptr2[4] = 'u';
					ptr2[5] = 'u';
					ptr2[6] = 'i';
					ptr2[7] = 'd';
					ptr2[8] = ':';
					ptr2[17] = '-';
					ptr2[22] = '-';
					ptr2[27] = '-';
					ptr2[32] = '-';
					fixed (char* ptr3 = "0123456789abcdef")
					{
						char* ptr4 = ptr3;
						UnsafeEncode(ptr4, *ptr, ptr2 + 15);
						UnsafeEncode(ptr4, ptr[1], ptr2 + 13);
						UnsafeEncode(ptr4, ptr[2], ptr2 + 11);
						UnsafeEncode(ptr4, ptr[3], ptr2 + 9);
						UnsafeEncode(ptr4, ptr[4], ptr2 + 20);
						UnsafeEncode(ptr4, ptr[5], ptr2 + 18);
						UnsafeEncode(ptr4, ptr[6], ptr2 + 25);
						UnsafeEncode(ptr4, ptr[7], ptr2 + 23);
						UnsafeEncode(ptr4, ptr[8], ptr2 + 28);
						UnsafeEncode(ptr4, ptr[9], ptr2 + 30);
						UnsafeEncode(ptr4, ptr[10], ptr2 + 33);
						UnsafeEncode(ptr4, ptr[11], ptr2 + 35);
						UnsafeEncode(ptr4, ptr[12], ptr2 + 37);
						UnsafeEncode(ptr4, ptr[13], ptr2 + 39);
						UnsafeEncode(ptr4, ptr[14], ptr2 + 41);
						UnsafeEncode(ptr4, ptr[15], ptr2 + 43);
					}
				}
			}
			return charArrayLength;
		}

		public bool TryGetGuid(out Guid guid)
		{
			byte[] array = new byte[16];
			if (!TryGetGuid(array, 0))
			{
				guid = Guid.Empty;
				return false;
			}
			guid = new Guid(array);
			return true;
		}

		[SecuritySafeCritical]
		public unsafe bool TryGetGuid(byte[] buffer, int offset)
		{
			if (!IsGuid)
			{
				return false;
			}
			if (buffer == null)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("buffer"));
			}
			if (offset < 0)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The value of this argument must be non-negative.")));
			}
			if (offset > buffer.Length)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("offset", System.Runtime.Serialization.SR.GetString("The specified offset exceeds the buffer size ({0} bytes).", buffer.Length)));
			}
			if (16 > buffer.Length - offset)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("buffer", System.Runtime.Serialization.SR.GetString("Array too small.  Must be able to hold at least {0}.", 16)));
			}
			fixed (byte* ptr = &buffer[offset])
			{
				UnsafeSetInt64(idLow, ptr);
				UnsafeSetInt64(idHigh, ptr + 8);
			}
			return true;
		}

		[SecuritySafeCritical]
		public override string ToString()
		{
			if (s == null)
			{
				int charArrayLength = CharArrayLength;
				char[] array = new char[charArrayLength];
				ToCharArray(array, 0);
				s = new string(array, 0, charArrayLength);
			}
			return s;
		}

		public static bool operator ==(UniqueId id1, UniqueId id2)
		{
			if ((object)id1 == null && (object)id2 == null)
			{
				return true;
			}
			if ((object)id1 == null || (object)id2 == null)
			{
				return false;
			}
			if (id1.IsGuid && id2.IsGuid)
			{
				if (id1.idLow == id2.idLow)
				{
					return id1.idHigh == id2.idHigh;
				}
				return false;
			}
			return id1.ToString() == id2.ToString();
		}

		public static bool operator !=(UniqueId id1, UniqueId id2)
		{
			return !(id1 == id2);
		}

		public override bool Equals(object obj)
		{
			return this == obj as UniqueId;
		}

		public override int GetHashCode()
		{
			if (IsGuid)
			{
				long num = idLow ^ idHigh;
				return (int)(num >> 32) ^ (int)num;
			}
			return ToString().GetHashCode();
		}

		[SecurityCritical]
		private unsafe long UnsafeGetInt64(byte* pb)
		{
			int num = UnsafeGetInt32(pb);
			return ((long)UnsafeGetInt32(pb + 4) << 32) | (uint)num;
		}

		[SecurityCritical]
		private unsafe int UnsafeGetInt32(byte* pb)
		{
			return (((((pb[3] << 8) | pb[2]) << 8) | pb[1]) << 8) | *pb;
		}

		[SecurityCritical]
		private unsafe void UnsafeSetInt64(long value, byte* pb)
		{
			UnsafeSetInt32((int)value, pb);
			UnsafeSetInt32((int)(value >> 32), pb + 4);
		}

		[SecurityCritical]
		private unsafe void UnsafeSetInt32(int value, byte* pb)
		{
			*pb = (byte)value;
			value >>= 8;
			pb[1] = (byte)value;
			value >>= 8;
			pb[2] = (byte)value;
			value >>= 8;
			pb[3] = (byte)value;
		}
	}
	internal enum ValueHandleConstStringType
	{
		String,
		Number,
		Array,
		Object,
		Boolean,
		Null
	}
	internal static class ValueHandleLength
	{
		public const int Int8 = 1;

		public const int Int16 = 2;

		public const int Int32 = 4;

		public const int Int64 = 8;

		public const int UInt64 = 8;

		public const int Single = 4;

		public const int Double = 8;

		public const int Decimal = 16;

		public const int DateTime = 8;

		public const int TimeSpan = 8;

		public const int Guid = 16;

		public const int UniqueId = 16;
	}
	internal enum ValueHandleType
	{
		Empty,
		True,
		False,
		Zero,
		One,
		Int8,
		Int16,
		Int32,
		Int64,
		UInt64,
		Single,
		Double,
		Decimal,
		DateTime,
		TimeSpan,
		Guid,
		UniqueId,
		UTF8,
		EscapedUTF8,
		Base64,
		Dictionary,
		List,
		Char,
		Unicode,
		QName,
		ConstString
	}
	internal class ValueHandle
	{
		private XmlBufferReader bufferReader;

		private ValueHandleType type;

		private int offset;

		private int length;

		private static Base64Encoding base64Encoding;

		private static string[] constStrings = new string[6] { "string", "number", "array", "object", "boolean", "null" };

		private static Base64Encoding Base64Encoding
		{
			get
			{
				if (base64Encoding == null)
				{
					base64Encoding = new Base64Encoding();
				}
				return base64Encoding;
			}
		}

		public ValueHandle(XmlBufferReader bufferReader)
		{
			this.bufferReader = bufferReader;
			type = ValueHandleType.Empty;
		}

		public void SetConstantValue(ValueHandleConstStringType constStringType)
		{
			type = ValueHandleType.ConstString;
			offset = (int)constStringType;
		}

		public void SetValue(ValueHandleType type)
		{
			this.type = type;
		}

		public void SetDictionaryValue(int key)
		{
			SetValue(ValueHandleType.Dictionary, key, 0);
		}

		public void SetCharValue(int ch)
		{
			SetValue(ValueHandleType.Char, ch, 0);
		}

		public void SetQNameValue(int prefix, int key)
		{
			SetValue(ValueHandleType.QName, key, prefix);
		}

		public void SetValue(ValueHandleType type, int offset, int length)
		{
			this.type = type;
			this.offset = offset;
			this.length = length;
		}

		public bool IsWhitespace()
		{
			switch (type)
			{
			case ValueHandleType.UTF8:
				return bufferReader.IsWhitespaceUTF8(offset, length);
			case ValueHandleType.Dictionary:
				return bufferReader.IsWhitespaceKey(offset);
			case ValueHandleType.Char:
			{
				int @char = GetChar();
				if (@char > 65535)
				{
					return false;
				}
				return XmlConverter.IsWhitespace((char)@char);
			}
			case ValueHandleType.EscapedUTF8:
				return bufferReader.IsWhitespaceUTF8(offset, length);
			case ValueHandleType.Unicode:
				return bufferReader.IsWhitespaceUnicode(offset, length);
			case ValueHandleType.True:
			case ValueHandleType.False:
			case ValueHandleType.Zero:
			case ValueHandleType.One:
				return false;
			case ValueHandleType.ConstString:
				return constStrings[offset].Length == 0;
			default:
				return length == 0;
			}
		}

		public Type ToType()
		{
			switch (type)
			{
			case ValueHandleType.True:
			case ValueHandleType.False:
				return typeof(bool);
			case ValueHandleType.Zero:
			case ValueHandleType.One:
			case ValueHandleType.Int8:
			case ValueHandleType.Int16:
			case ValueHandleType.Int32:
				return typeof(int);
			case ValueHandleType.Int64:
				return typeof(long);
			case ValueHandleType.UInt64:
				return typeof(ulong);
			case ValueHandleType.Single:
				return typeof(float);
			case ValueHandleType.Double:
				return typeof(double);
			case ValueHandleType.Decimal:
				return typeof(decimal);
			case ValueHandleType.DateTime:
				return typeof(DateTime);
			case ValueHandleType.Empty:
			case ValueHandleType.UTF8:
			case ValueHandleType.EscapedUTF8:
			case ValueHandleType.Dictionary:
			case ValueHandleType.Char:
			case ValueHandleType.Unicode:
			case ValueHandleType.QName:
			case ValueHandleType.ConstString:
				return typeof(string);
			case ValueHandleType.Base64:
				return typeof(byte[]);
			case ValueHandleType.List:
				return typeof(object[]);
			case ValueHandleType.UniqueId:
				return typeof(UniqueId);
			case ValueHandleType.Guid:
				return typeof(Guid);
			case ValueHandleType.TimeSpan:
				return typeof(TimeSpan);
			default:
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
			}
		}

		public bool ToBoolean()
		{
			switch (type)
			{
			case ValueHandleType.False:
				return false;
			case ValueHandleType.True:
				return true;
			case ValueHandleType.UTF8:
				return XmlConverter.ToBoolean(bufferReader.Buffer, offset, length);
			case ValueHandleType.Int8:
				switch (GetInt8())
				{
				case 0:
					return false;
				case 1:
					return true;
				}
				break;
			}
			return XmlConverter.ToBoolean(GetString());
		}

		public int ToInt()
		{
			ValueHandleType valueHandleType = type;
			switch (valueHandleType)
			{
			case ValueHandleType.Zero:
				return 0;
			case ValueHandleType.One:
				return 1;
			case ValueHandleType.Int8:
				return GetInt8();
			case ValueHandleType.Int16:
				return GetInt16();
			case ValueHandleType.Int32:
				return GetInt32();
			case ValueHandleType.Int64:
			{
				long @int = GetInt64();
				if (@int >= int.MinValue && @int <= int.MaxValue)
				{
					return (int)@int;
				}
				break;
			}
			}
			if (valueHandleType == ValueHandleType.UInt64)
			{
				ulong uInt = GetUInt64();
				if (uInt <= int.MaxValue)
				{
					return (int)uInt;
				}
			}
			if (valueHandleType == ValueHandleType.UTF8)
			{
				return XmlConverter.ToInt32(bufferReader.Buffer, offset, length);
			}
			return XmlConverter.ToInt32(GetString());
		}

		public long ToLong()
		{
			ValueHandleType valueHandleType = type;
			switch (valueHandleType)
			{
			case ValueHandleType.Zero:
				return 0L;
			case ValueHandleType.One:
				return 1L;
			case ValueHandleType.Int8:
				return GetInt8();
			case ValueHandleType.Int16:
				return GetInt16();
			case ValueHandleType.Int32:
				return GetInt32();
			case ValueHandleType.Int64:
				return GetInt64();
			case ValueHandleType.UInt64:
			{
				ulong uInt = GetUInt64();
				if (uInt <= long.MaxValue)
				{
					return (long)uInt;
				}
				break;
			}
			}
			if (valueHandleType == ValueHandleType.UTF8)
			{
				return XmlConverter.ToInt64(bufferReader.Buffer, offset, length);
			}
			return XmlConverter.ToInt64(GetString());
		}

		public ulong ToULong()
		{
			ValueHandleType valueHandleType = type;
			switch (valueHandleType)
			{
			case ValueHandleType.Zero:
				return 0uL;
			case ValueHandleType.One:
				return 1uL;
			case ValueHandleType.Int8:
			case ValueHandleType.Int16:
			case ValueHandleType.Int32:
			case ValueHandleType.Int64:
			{
				long num = ToLong();
				if (num >= 0)
				{
					return (ulong)num;
				}
				break;
			}
			}
			return valueHandleType switch
			{
				ValueHandleType.UInt64 => GetUInt64(), 
				ValueHandleType.UTF8 => XmlConverter.ToUInt64(bufferReader.Buffer, offset, length), 
				_ => XmlConverter.ToUInt64(GetString()), 
			};
		}

		public float ToSingle()
		{
			ValueHandleType valueHandleType = type;
			switch (valueHandleType)
			{
			case ValueHandleType.Single:
				return GetSingle();
			case ValueHandleType.Double:
			{
				double @double = GetDouble();
				if ((@double >= -3.4028234663852886E+38 && @double <= 3.4028234663852886E+38) || double.IsInfinity(@double) || double.IsNaN(@double))
				{
					return (float)@double;
				}
				break;
			}
			}
			return valueHandleType switch
			{
				ValueHandleType.Zero => 0f, 
				ValueHandleType.One => 1f, 
				ValueHandleType.Int8 => GetInt8(), 
				ValueHandleType.Int16 => GetInt16(), 
				ValueHandleType.UTF8 => XmlConverter.ToSingle(bufferReader.Buffer, offset, length), 
				_ => XmlConverter.ToSingle(GetString()), 
			};
		}

		public double ToDouble()
		{
			return type switch
			{
				ValueHandleType.Double => GetDouble(), 
				ValueHandleType.Single => GetSingle(), 
				ValueHandleType.Zero => 0.0, 
				ValueHandleType.One => 1.0, 
				ValueHandleType.Int8 => GetInt8(), 
				ValueHandleType.Int16 => GetInt16(), 
				ValueHandleType.Int32 => GetInt32(), 
				ValueHandleType.UTF8 => XmlConverter.ToDouble(bufferReader.Buffer, offset, length), 
				_ => XmlConverter.ToDouble(GetString()), 
			};
		}

		public decimal ToDecimal()
		{
			ValueHandleType valueHandleType = type;
			switch (valueHandleType)
			{
			case ValueHandleType.Decimal:
				return GetDecimal();
			case ValueHandleType.Zero:
				return 0m;
			case ValueHandleType.One:
				return 1m;
			case ValueHandleType.Int8:
			case ValueHandleType.Int16:
			case ValueHandleType.Int32:
			case ValueHandleType.Int64:
				return ToLong();
			default:
				return valueHandleType switch
				{
					ValueHandleType.UInt64 => GetUInt64(), 
					ValueHandleType.UTF8 => XmlConverter.ToDecimal(bufferReader.Buffer, offset, length), 
					_ => XmlConverter.ToDecimal(GetString()), 
				};
			}
		}

		public DateTime ToDateTime()
		{
			if (type == ValueHandleType.DateTime)
			{
				return XmlConverter.ToDateTime(GetInt64());
			}
			if (type == ValueHandleType.UTF8)
			{
				return XmlConverter.ToDateTime(bufferReader.Buffer, offset, length);
			}
			return XmlConverter.ToDateTime(GetString());
		}

		public UniqueId ToUniqueId()
		{
			if (type == ValueHandleType.UniqueId)
			{
				return GetUniqueId();
			}
			if (type == ValueHandleType.UTF8)
			{
				return XmlConverter.ToUniqueId(bufferReader.Buffer, offset, length);
			}
			return XmlConverter.ToUniqueId(GetString());
		}

		public TimeSpan ToTimeSpan()
		{
			if (type == ValueHandleType.TimeSpan)
			{
				return new TimeSpan(GetInt64());
			}
			if (type == ValueHandleType.UTF8)
			{
				return XmlConverter.ToTimeSpan(bufferReader.Buffer, offset, length);
			}
			return XmlConverter.ToTimeSpan(GetString());
		}

		public Guid ToGuid()
		{
			if (type == ValueHandleType.Guid)
			{
				return GetGuid();
			}
			if (type == ValueHandleType.UTF8)
			{
				return XmlConverter.ToGuid(bufferReader.Buffer, offset, length);
			}
			return XmlConverter.ToGuid(GetString());
		}

		public override string ToString()
		{
			return GetString();
		}

		public byte[] ToByteArray()
		{
			if (type == ValueHandleType.Base64)
			{
				byte[] array = new byte[length];
				GetBase64(array, 0, length);
				return array;
			}
			if (type == ValueHandleType.UTF8 && length % 4 == 0)
			{
				try
				{
					int num = length / 4 * 3;
					if (length > 0 && bufferReader.Buffer[offset + length - 1] == 61)
					{
						num--;
						if (bufferReader.Buffer[offset + length - 2] == 61)
						{
							num--;
						}
					}
					byte[] array2 = new byte[num];
					int bytes = Base64Encoding.GetBytes(bufferReader.Buffer, offset, length, array2, 0);
					if (bytes != array2.Length)
					{
						byte[] array3 = new byte[bytes];
						Buffer.BlockCopy(array2, 0, array3, 0, bytes);
						array2 = array3;
					}
					return array2;
				}
				catch (FormatException)
				{
				}
			}
			try
			{
				return Base64Encoding.GetBytes(XmlConverter.StripWhitespace(GetString()));
			}
			catch (FormatException ex2)
			{
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(ex2.Message, ex2.InnerException));
			}
		}

		public string GetString()
		{
			ValueHandleType valueHandleType = type;
			if (valueHandleType == ValueHandleType.UTF8)
			{
				return GetCharsText();
			}
			switch (valueHandleType)
			{
			case ValueHandleType.False:
				return "false";
			case ValueHandleType.True:
				return "true";
			case ValueHandleType.Zero:
				return "0";
			case ValueHandleType.One:
				return "1";
			case ValueHandleType.Int8:
			case ValueHandleType.Int16:
			case ValueHandleType.Int32:
				return XmlConverter.ToString(ToInt());
			case ValueHandleType.Int64:
				return XmlConverter.ToString(GetInt64());
			case ValueHandleType.UInt64:
				return XmlConverter.ToString(GetUInt64());
			case ValueHandleType.Single:
				return XmlConverter.ToString(GetSingle());
			case ValueHandleType.Double:
				return XmlConverter.ToString(GetDouble());
			case ValueHandleType.Decimal:
				return XmlConverter.ToString(GetDecimal());
			case ValueHandleType.DateTime:
				return XmlConverter.ToString(ToDateTime());
			case ValueHandleType.Empty:
				return string.Empty;
			case ValueHandleType.UTF8:
				return GetCharsText();
			case ValueHandleType.Unicode:
				return GetUnicodeCharsText();
			case ValueHandleType.EscapedUTF8:
				return GetEscapedCharsText();
			case ValueHandleType.Char:
				return GetCharText();
			case ValueHandleType.Dictionary:
				return GetDictionaryString().Value;
			case ValueHandleType.Base64:
				return Base64Encoding.GetString(ToByteArray());
			case ValueHandleType.List:
				return XmlConverter.ToString(ToList());
			case ValueHandleType.UniqueId:
				return XmlConverter.ToString(ToUniqueId());
			case ValueHandleType.Guid:
				return XmlConverter.ToString(ToGuid());
			case ValueHandleType.TimeSpan:
				return XmlConverter.ToString(ToTimeSpan());
			case ValueHandleType.QName:
				return GetQNameDictionaryText();
			case ValueHandleType.ConstString:
				return constStrings[offset];
			default:
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
			}
		}

		public bool Equals2(string str, bool checkLower)
		{
			if (type != ValueHandleType.UTF8)
			{
				return GetString() == str;
			}
			if (length != str.Length)
			{
				return false;
			}
			byte[] buffer = bufferReader.Buffer;
			for (int i = 0; i < length; i++)
			{
				byte b = buffer[i + offset];
				if (b != str[i] && (!checkLower || char.ToLowerInvariant((char)b) != str[i]))
				{
					return false;
				}
			}
			return true;
		}

		public void Sign(XmlSigningNodeWriter writer)
		{
			switch (type)
			{
			case ValueHandleType.Int8:
			case ValueHandleType.Int16:
			case ValueHandleType.Int32:
				writer.WriteInt32Text(ToInt());
				break;
			case ValueHandleType.Int64:
				writer.WriteInt64Text(GetInt64());
				break;
			case ValueHandleType.UInt64:
				writer.WriteUInt64Text(GetUInt64());
				break;
			case ValueHandleType.Single:
				writer.WriteFloatText(GetSingle());
				break;
			case ValueHandleType.Double:
				writer.WriteDoubleText(GetDouble());
				break;
			case ValueHandleType.Decimal:
				writer.WriteDecimalText(GetDecimal());
				break;
			case ValueHandleType.DateTime:
				writer.WriteDateTimeText(ToDateTime());
				break;
			case ValueHandleType.UTF8:
				writer.WriteEscapedText(bufferReader.Buffer, offset, length);
				break;
			case ValueHandleType.Base64:
				writer.WriteBase64Text(bufferReader.Buffer, 0, bufferReader.Buffer, offset, length);
				break;
			case ValueHandleType.UniqueId:
				writer.WriteUniqueIdText(ToUniqueId());
				break;
			case ValueHandleType.Guid:
				writer.WriteGuidText(ToGuid());
				break;
			case ValueHandleType.TimeSpan:
				writer.WriteTimeSpanText(ToTimeSpan());
				break;
			default:
				writer.WriteEscapedText(GetString());
				break;
			case ValueHandleType.Empty:
				break;
			}
		}

		public object[] ToList()
		{
			return bufferReader.GetList(offset, length);
		}

		public object ToObject()
		{
			switch (type)
			{
			case ValueHandleType.True:
			case ValueHandleType.False:
				return ToBoolean();
			case ValueHandleType.Zero:
			case ValueHandleType.One:
			case ValueHandleType.Int8:
			case ValueHandleType.Int16:
			case ValueHandleType.Int32:
				return ToInt();
			case ValueHandleType.Int64:
				return ToLong();
			case ValueHandleType.UInt64:
				return GetUInt64();
			case ValueHandleType.Single:
				return ToSingle();
			case ValueHandleType.Double:
				return ToDouble();
			case ValueHandleType.Decimal:
				return ToDecimal();
			case ValueHandleType.DateTime:
				return ToDateTime();
			case ValueHandleType.Empty:
			case ValueHandleType.UTF8:
			case ValueHandleType.EscapedUTF8:
			case ValueHandleType.Dictionary:
			case ValueHandleType.Char:
			case ValueHandleType.Unicode:
			case ValueHandleType.ConstString:
				return ToString();
			case ValueHandleType.Base64:
				return ToByteArray();
			case ValueHandleType.List:
				return ToList();
			case ValueHandleType.UniqueId:
				return ToUniqueId();
			case ValueHandleType.Guid:
				return ToGuid();
			case ValueHandleType.TimeSpan:
				return ToTimeSpan();
			default:
				throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
			}
		}

		public bool TryReadBase64(byte[] buffer, int offset, int count, out int actual)
		{
			if (type == ValueHandleType.Base64)
			{
				actual = Math.Min(length, count);
				GetBase64(buffer, offset, actual);
				this.offset += actual;
				length -= actual;
				return true;
			}
			if (type == ValueHandleType.UTF8 && count >= 3 && length % 4 == 0)
			{
				try
				{
					int num = Math.Min(count / 3 * 4, length);
					actual = Base64Encoding.GetBytes(bufferReader.Buffer, this.offset, num, buffer, offset);
					this.offset += num;
					length -= num;
					return true;
				}
				catch (FormatException)
				{
				}
			}
			actual = 0;
			return false;
		}

		public bool TryReadChars(char[] chars, int offset, int count, out int actual)
		{
			if (type == ValueHandleType.Unicode)
			{
				return TryReadUnicodeChars(chars, offset, count, out actual);
			}
			if (type != ValueHandleType.UTF8)
			{
				actual = 0;
				return false;
			}
			int num = offset;
			int num2 = count;
			byte[] buffer = bufferReader.Buffer;
			int num3 = this.offset;
			int num4 = length;
			bool flag = false;
			while (true)
			{
				if (num2 > 0 && num4 > 0)
				{
					byte b = buffer[num3];
					if (b < 128)
					{
						chars[num] = (char)b;
						num3++;
						num4--;
						num++;
						num2--;
						continue;
					}
				}
				if (num2 == 0 || num4 == 0 || flag)
				{
					break;
				}
				UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
				int chars2;
				int num5;
				try
				{
					if (num2 >= uTF8Encoding.GetMaxCharCount(num4) || num2 >= uTF8Encoding.GetCharCount(buffer, num3, num4))
					{
						chars2 = uTF8Encoding.GetChars(buffer, num3, num4, chars, num);
						num5 = num4;
					}
					else
					{
						Decoder decoder = uTF8Encoding.GetDecoder();
						num5 = Math.Min(num2, num4);
						chars2 = decoder.GetChars(buffer, num3, num5, chars, num);
						while (chars2 == 0)
						{
							if (num5 >= 3 && num2 < 2)
							{
								flag = true;
								break;
							}
							chars2 = decoder.GetChars(buffer, num3 + num5, 1, chars, num);
							num5++;
						}
						num5 = uTF8Encoding.GetByteCount(chars, num, chars2);
					}
				}
				catch (FormatException exception)
				{
					throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(buffer, num3, num4, exception));
				}
				num3 += num5;
				num4 -= num5;
				num += chars2;
				num2 -= chars2;
			}
			this.offset = num3;
			length = num4;
			actual = count - num2;
			return true;
		}

		private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int actual)
		{
			int num = Math.Min(count, length / 2);
			for (int i = 0; i < num; i++)
			{
				chars[offset + i] = (char)bufferReader.GetInt16(this.offset + i * 2);
			}
			this.offset += num * 2;
			length -= num * 2;
			actual = num;
			return true;
		}

		public bool TryGetDictionaryString(out XmlDictionaryString value)
		{
			if (type == ValueHandleType.Dictionary)
			{
				value = GetDictionaryString();
				return true;
			}
			value = null;
			return false;
		}

		public bool TryGetByteArrayLength(out int length)
		{
			if (type == ValueHandleType.Base64)
			{
				length = this.length;
				return true;
			}
			length = 0;
			return false;
		}

		private string GetCharsText()
		{
			if (length == 1 && bufferReader.GetByte(offset) == 49)
			{
				return "1";
			}
			return bufferReader.GetString(offset, length);
		}

		private string GetUnicodeCharsText()
		{
			return bufferReader.GetUnicodeString(offset, length);
		}

		private string GetEscapedCharsText()
		{
			return bufferReader.GetEscapedString(offset, length);
		}

		private string GetCharText()
		{
			int @char = GetChar();
			if (@char > 65535)
			{
				SurrogateChar surrogateChar = new SurrogateChar(@char);
				return new string(new char[2] { surrogateChar.HighChar, surrogateChar.LowChar }, 0, 2);
			}
			return ((char)@char).ToString();
		}

		private int GetChar()
		{
			return offset;
		}

		private int GetInt8()
		{
			return bufferReader.GetInt8(offset);
		}

		private int GetInt16()
		{
			return bufferReader.GetInt16(offset);
		}

		private int GetInt32()
		{
			return bufferReader.GetInt32(offset);
		}

		private long GetInt64()
		{
			return bufferReader.GetInt64(offset);
		}

		private ulong GetUInt64()
		{
			return bufferReader.GetUInt64(offset);
		}

		private float GetSingle()
		{
			return bufferReader.GetSingle(offset);
		}

		private double GetDouble()
		{
			return bufferReader.GetDouble(offset);
		}

		private decimal GetDecimal()
		{
			return bufferReader.GetDecimal(offset);
		}

		private UniqueId GetUniqueId()
		{
			return bufferReader.GetUniqueId(offset);
		}

		private Guid GetGuid()
		{
			return bufferReader.GetGuid(offset);
		}

		private void GetBase64(byte[] buffer, int offset, int count)
		{
			bufferReader.GetBase64(this.offset, buffer, offset, count);
		}

		private XmlDictionaryString GetDictionaryString()
		{
			return bufferReader.GetDictionaryString(offset);
		}

		private string GetQNameDictionaryText()
		{
			return PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(length)) + ":" + bufferReader.GetDictionaryString(offset);
		}
	}
	internal abstract class XmlBaseReader : XmlDictionaryReader
	{
		protected enum QNameType
		{
			Normal,
			Xmlns
		}

		protected class XmlNode
		{
			protected enum XmlNodeFlags
			{
				None = 0,
				CanGetAttribute = 1,
				CanMoveToElement = 2,
				HasValue = 4,
				AtomicValue = 8,
				SkipValue = 0x10,
				HasContent = 0x20
			}

			private XmlNodeType nodeType;

			private PrefixHandle prefix;

			private StringHandle localName;

			private ValueHandle value;

			private Namespace ns;

			private bool hasValue;

			private bool canGetAttribute;

			private bool canMoveToElement;

			private ReadState readState;

			private XmlAttributeTextNode attributeTextNode;

			private bool exitScope;

			private int depthDelta;

			private bool isAtomicValue;

			private bool skipValue;

			private QNameType qnameType;

			private bool hasContent;

			private bool isEmptyElement;

			private char quoteChar;

			public bool HasValue => hasValue;

			public ReadState ReadState => readState;

			public StringHandle LocalName => localName;

			public PrefixHandle Prefix => prefix;

			public bool CanGetAttribute => canGetAttribute;

			public bool CanMoveToElement => canMoveToElement;

			public XmlAttributeTextNode AttributeText => attributeTextNode;

			public bool SkipValue => skipValue;

			public ValueHandle Value => value;

			public int DepthDelta => depthDelta;

			public bool HasContent => hasContent;

			public XmlNodeType NodeType
			{
				get
				{
					return nodeType;
				}
				set
				{
					nodeType = value;
				}
			}

			public QNameType QNameType
			{
				get
				{
					return qnameType;
				}
				set
				{
					qnameType = value;
				}
			}

			public Namespace Namespace
			{
				get
				{
					return ns;
				}
				set
				{
					ns = value;
				}
			}

			public bool IsAtomicValue
			{
				get
				{
					return isAtomicValue;
				}
				set
				{
					isAtomicValue = value;
				}
			}

			public bool ExitScope
			{
				get
				{
					return exitScope;
				}
				set
				{
					exitScope = value;
				}
			}

			public bool IsEmptyElement
			{
				get
				{
					return isEmptyElement;
				}
				set
				{
					isEmptyElement = value;
				}
			}

			public char QuoteChar
			{
				get
				{
					return quoteChar;
				}
				set
				{
					quoteChar = value;
				}
			}

			public string ValueAsString
			{
				get
				{
					if (qnameType == QNameType.Normal)
					{
						return Value.GetString();
					}
					return Namespace.Uri.GetString();
				}
			}

			protected XmlNode(XmlNodeType nodeType, PrefixHandle prefix, StringHandle localName, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, XmlAttributeTextNode attributeTextNode, int depthDelta)
			{
				this.nodeType = nodeType;
				this.prefix = prefix;
				this.localName = localName;
				this.value = value;
				ns = NamespaceManager.EmptyNamespace;
				hasValue = (nodeFlags & XmlNodeFlags.HasValue) != 0;
				canGetAttribute = (nodeFlags & XmlNodeFlags.CanGetAttribute) != 0;
				canMoveToElement = (nodeFlags & XmlNodeFlags.CanMoveToElement) != 0;
				isAtomicValue = (nodeFlags & XmlNodeFlags.AtomicValue) != 0;
				skipValue = (nodeFlags & XmlNodeFlags.SkipValue) != 0;
				hasContent = (nodeFlags & XmlNodeFlags.HasContent) != 0;
				this.readState = readState;
				this.attributeTextNode = attributeTextNode;
				exitScope = nodeType == XmlNodeType.EndElement;
				this.depthDelta = depthDelta;
				isEmptyElement = false;
				quoteChar = '"';
				qnameType = QNameType.Normal;
			}

			public bool IsLocalName(string localName)
			{
				if (qnameType == QNameType.Normal)
				{
					return LocalName == localName;
				}
				return Namespace.Prefix == localName;
			}

			public bool IsLocalName(XmlDictionaryString localName)
			{
				if (qnameType == QNameType.Normal)
				{
					return LocalName == localName;
				}
				return Namespace.Prefix == localName;
			}

			public bool IsNamespaceUri(string ns)
			{
				if (qnameType == QNameType.Normal)
				{
					return Namespace.IsUri(ns);
				}
				return ns == "http://www.w3.org/2000/xmlns/";
			}

			public bool IsNamespaceUri(XmlDictionaryString ns)
			{
				if (qnameType == QNameType.Normal)
				{
					return Namespace.IsUri(ns);
				}
				return ns.Value == "http://www.w3.org/2000/xmlns/";
			}

			public bool IsLocalNameAndNamespaceUri(string localName, string ns)
			{
				if (qnameType == QNameType.Normal)
				{
					if (LocalName == localName)
					{
						return Namespace.IsUri(ns);
					}
					return false;
				}
				if (Namespace.Prefix == localName)
				{
					return ns == "http://www.w3.org/2000/xmlns/";
				}
				return false;
			}

			public bool IsLocalNameAndNamespaceUri(XmlDictionaryString localName, XmlDictionaryString ns)
			{
				if (qnameType == QNameType.Normal)
				{
					if (LocalName == localName)
					{
						return Namespace.IsUri(ns);
					}
					return false;
				}
				if (Namespace.Prefix == localName)
				{
					return ns.Value == "http://www.w3.org/2000/xmlns/";
				}
				return false;
			}

			public bool IsPrefixAndLocalName(string prefix, string localName)
			{
				if (qnameType == QNameType.Normal)
				{
					if (Prefix == prefix)
					{
						return LocalName == localName;
					}
					return false;
				}
				if (prefix == "xmlns")
				{
					return Namespace.Prefix == localName;
				}
				return false;
			}

			public bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName)
			{
				if (qnameType == QNameType.Normal)
				{
					return LocalName.TryGetDictionaryString(out localName);
				}
				localName = null;
				return false;
			}

			public bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString ns)
			{
				if (qnameType == QNameType.Normal)
				{
					return Namespace.Uri.TryGetDictionaryString(out ns);
				}
				ns = null;
				return false;
			}

			public bool TryGetValueAsDictionaryString(out XmlDictionaryString value)
			{
				if (qnameType == QNameType.Normal)
				{
					return Value.TryGetDictionaryString(out value);
				}
				value = null;
				return false;
			}
		}

		protected class XmlElementNode : XmlNode
		{
			private XmlEndElementNode endElementNode;

			private int bufferOffset;

			public int NameOffset;

			public int NameLength;

			public XmlEndElementNode EndElement => endElementNode;

			public int BufferOffset
			{
				get
				{
					return bufferOffset;
				}
				set
				{
					bufferOffset = value;
				}
			}

			public XmlElementNode(XmlBufferReader bufferReader)
				: this(new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader))
			{
			}

			private XmlElementNode(PrefixHandle prefix, StringHandle localName, ValueHandle value)
				: base(XmlNodeType.Element, prefix, localName, value, (XmlNodeFlags)33, ReadState.Interactive, null, -1)
			{
				endElementNode = new XmlEndElementNode(prefix, localName, value);
			}
		}

		protected class XmlAttributeNode : XmlNode
		{
			public XmlAttributeNode(XmlBufferReader bufferReader)
				: this(new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader))
			{
			}

			private XmlAttributeNode(PrefixHandle prefix, StringHandle localName, ValueHandle value)
				: base(XmlNodeType.Attribute, prefix, localName, value, (XmlNodeFlags)15, ReadState.Interactive, new XmlAttributeTextNode(prefix, localName, value), 0)
			{
			}
		}

		protected class XmlEndElementNode : XmlNode
		{
			public XmlEndElementNode(PrefixHandle prefix, StringHandle localName, ValueHandle value)
				: base(XmlNodeType.EndElement, prefix, localName, value, XmlNodeFlags.HasContent, ReadState.Interactive, null, -1)
			{
			}
		}

		protected class XmlTextNode : XmlNode
		{
			protected XmlTextNode(XmlNodeType nodeType, PrefixHandle prefix, StringHandle localName, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, XmlAttributeTextNode attributeTextNode, int depthDelta)
				: base(nodeType, prefix, localName, value, nodeFlags, readState, attributeTextNode, depthDelta)
			{
			}
		}

		protected class XmlAtomicTextNode : XmlTextNode
		{
			public XmlAtomicTextNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.Text, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)60, ReadState.Interactive, null, 0)
			{
			}
		}

		protected class XmlComplexTextNode : XmlTextNode
		{
			public XmlComplexTextNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.Text, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)36, ReadState.Interactive, null, 0)
			{
			}
		}

		protected class XmlWhitespaceTextNode : XmlTextNode
		{
			public XmlWhitespaceTextNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.Whitespace, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.HasValue, ReadState.Interactive, null, 0)
			{
			}
		}

		protected class XmlCDataNode : XmlTextNode
		{
			public XmlCDataNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.CDATA, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), (XmlNodeFlags)36, ReadState.Interactive, null, 0)
			{
			}
		}

		protected class XmlAttributeTextNode : XmlTextNode
		{
			public XmlAttributeTextNode(PrefixHandle prefix, StringHandle localName, ValueHandle value)
				: base(XmlNodeType.Text, prefix, localName, value, (XmlNodeFlags)47, ReadState.Interactive, null, 1)
			{
			}
		}

		protected class XmlInitialNode : XmlNode
		{
			public XmlInitialNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.Initial, null, 0)
			{
			}
		}

		protected class XmlDeclarationNode : XmlNode
		{
			public XmlDeclarationNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.XmlDeclaration, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.CanGetAttribute, ReadState.Interactive, null, 0)
			{
			}
		}

		protected class XmlCommentNode : XmlNode
		{
			public XmlCommentNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.Comment, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.HasValue, ReadState.Interactive, null, 0)
			{
			}
		}

		protected class XmlEndOfFileNode : XmlNode
		{
			public XmlEndOfFileNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.EndOfFile, null, 0)
			{
			}
		}

		protected class XmlClosedNode : XmlNode
		{
			public XmlClosedNode(XmlBufferReader bufferReader)
				: base(XmlNodeType.None, new PrefixHandle(bufferReader), new StringHandle(bufferReader), new ValueHandle(bufferReader), XmlNodeFlags.None, ReadState.Closed, null, 0)
			{
			}
		}

		private class AttributeSorter : IComparer
		{
			private object[] indeces;

			private XmlAttributeNode[] attributeNodes;

			private int attributeCount;

			private int attributeIndex1;

			private int attributeIndex2;

			public bool Sort(XmlAttributeNode[] attributeNodes, int attributeCount)
			{
				attributeIndex1 = -1;
				attributeIndex2 = -1;
				this.attributeNodes = attributeNodes;
				this.attributeCount = attributeCount;
				bool result = Sort();
				this.attributeNodes = null;
				this.attributeCount = 0;
				return result;
			}

			public void GetIndeces(out int attributeIndex1, out int attributeIndex2)
			{
				attributeIndex1 = this.attributeIndex1;
				attributeIndex2 = this.attributeIndex2;
			}

			public void Close()
			{
				if (indeces != null && indeces.Length > 32)
				{
					indeces = null;
				}
			}

			private bool Sort()
			{
				if (indeces != null && indeces.Length == attributeCount && IsSorted())
				{
					return true;
				}
				object[] array = new object[attributeCount];
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = i;
				}
				indeces = array;
				Array.Sort(indeces, 0, attributeCount, this);
				return IsSorted();
			}

			private bool IsSorted()
			{
				for (int i = 0; i < indeces.Length - 1; i++)
				{
					if (Compare(indeces[i], indeces[i + 1]) >= 0)
					{
						attributeIndex1 = (int)indeces[i];
						attributeIndex2 = (int)indeces[i + 1];
						return false;
					}
				}
				return true;
			}

			public int Compare(object obj1, object obj2)
			{
				int num = (int)obj1;
				int num2 = (int)obj2;
				XmlAttributeNode xmlAttributeNode = attributeNodes[num];
				XmlAttributeNode xmlAttributeNode2 = attributeNodes[num2];
				int num3 = CompareQNameType(xmlAttributeNode.QNameType, xmlAttributeNode2.QNameType);
				if (num3 == 0)
				{
					if (xmlAttributeNode.QNameType == QNameType.Normal)
					{
						num3 = xmlAttributeNode.LocalName.CompareTo(xmlAttributeNode2.LocalName);
						if (num3 == 0)
						{
							num3 = xmlAttributeNode.Namespace.Uri.CompareTo(xmlAttributeNode2.Namespace.Uri);
						}
					}
					else
					{
						num3 = xmlAttributeNode.Namespace.Prefix.CompareTo(xmlAttributeNode2.Namespace.Prefix);
					}
				}
				return num3;
			}

			public int CompareQNameType(QNameType type1, QNameType type2)
			{
				return type1 - type2;
			}
		}

		private class NamespaceManager
		{
			private class XmlAttribute
			{
				private XmlSpace space;

				private string lang;

				private int depth;

				public int Depth
				{
					get
					{
						return depth;
					}
					set
					{
						depth = value;
					}
				}

				public string XmlLang
				{
					get
					{
						return lang;

BepInEx/core/System.Runtime.Serialization.Formatters.Soap.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
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.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Metadata;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Threading;
using System.Xml;

[assembly: AssemblyDefaultAlias("System.Runtime.Serialization.Formatters.Soap.dll")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: AssemblyDelaySign(true)]
[assembly: CLSCompliant(true)]
[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: ComVisible(true)]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: AssemblyTitle("System.Runtime.Serialization.Formatters.Soap.dll")]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyDescription("System.Runtime.Serialization.Formatters.Soap.dll")]
[assembly: AssemblyVersion("4.0.0.0")]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal sealed class Locale
{
	private Locale()
	{
	}

	public static string GetText(string msg)
	{
		return msg;
	}

	public static string GetText(string fmt, params object[] args)
	{
		return string.Format(fmt, args);
	}
}
namespace System
{
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoTODOAttribute : Attribute
	{
		private string comment;

		public string Comment => comment;

		public MonoTODOAttribute()
		{
		}

		public MonoTODOAttribute(string comment)
		{
			this.comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoDocumentationNoteAttribute : MonoTODOAttribute
	{
		public MonoDocumentationNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoExtensionAttribute : MonoTODOAttribute
	{
		public MonoExtensionAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoInternalNoteAttribute : MonoTODOAttribute
	{
		public MonoInternalNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoLimitationAttribute : MonoTODOAttribute
	{
		public MonoLimitationAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoNotSupportedAttribute : MonoTODOAttribute
	{
		public MonoNotSupportedAttribute(string comment)
			: base(comment)
		{
		}
	}
}
namespace System.Runtime.Serialization.Formatters.Soap
{
	internal enum RemMessageType
	{
		MethodCall,
		MethodResponse,
		ServerFault,
		NotRecognize
	}
	public sealed class SoapFormatter : IRemotingFormatter, IFormatter
	{
		private SerializationBinder _binder;

		private StreamingContext _context;

		private ISurrogateSelector _selector;

		private FormatterAssemblyStyle _assemblyFormat = FormatterAssemblyStyle.Full;

		private FormatterTypeStyle _typeFormat;

		private ISoapMessage _topObject;

		private TypeFilterLevel _filterLevel = TypeFilterLevel.Low;

		public ISurrogateSelector SurrogateSelector
		{
			get
			{
				return _selector;
			}
			set
			{
				_selector = value;
			}
		}

		public SerializationBinder Binder
		{
			get
			{
				return _binder;
			}
			set
			{
				_binder = value;
			}
		}

		public StreamingContext Context
		{
			get
			{
				return _context;
			}
			set
			{
				_context = value;
			}
		}

		public ISoapMessage TopObject
		{
			get
			{
				return _topObject;
			}
			set
			{
				_topObject = value;
			}
		}

		[MonoTODO("Interpret this")]
		public TypeFilterLevel FilterLevel
		{
			get
			{
				return _filterLevel;
			}
			set
			{
				_filterLevel = value;
			}
		}

		public FormatterAssemblyStyle AssemblyFormat
		{
			get
			{
				return _assemblyFormat;
			}
			set
			{
				_assemblyFormat = value;
			}
		}

		public FormatterTypeStyle TypeFormat
		{
			get
			{
				return _typeFormat;
			}
			set
			{
				_typeFormat = value;
			}
		}

		public SoapFormatter()
		{
			_selector = null;
			_context = new StreamingContext(StreamingContextStates.All);
		}

		public SoapFormatter(ISurrogateSelector selector, StreamingContext context)
		{
			_selector = selector;
			_context = context;
		}

		public object Deserialize(Stream serializationStream)
		{
			return Deserialize(serializationStream, null);
		}

		public object Deserialize(Stream serializationStream, HeaderHandler handler)
		{
			return new SoapReader(_binder, _selector, _context).Deserialize(serializationStream, _topObject);
		}

		public void Serialize(Stream serializationStream, object graph)
		{
			Serialize(serializationStream, graph, null);
		}

		public void Serialize(Stream serializationStream, object graph, Header[] headers)
		{
			if (serializationStream == null)
			{
				throw new ArgumentNullException("serializationStream");
			}
			if (!serializationStream.CanWrite)
			{
				throw new SerializationException("Can't write in the serialization stream");
			}
			if (graph == null)
			{
				throw new ArgumentNullException("graph");
			}
			new SoapWriter(serializationStream, _selector, _context, _topObject).Serialize(graph, headers, _typeFormat, _assemblyFormat);
		}
	}
	internal sealed class SoapReader
	{
		private class TypeMetadata
		{
			public MemberInfo[] MemberInfos;

			public Hashtable Indices;
		}

		private SerializationBinder _binder;

		private SoapTypeMapper mapper;

		private ObjectManager objMgr;

		private StreamingContext _context;

		private long _nextAvailableId = long.MaxValue;

		private ISurrogateSelector _surrogateSelector;

		private XmlTextReader xmlReader;

		private Hashtable _fieldIndices;

		private long _topObjectId = 1L;

		private long NextAvailableId
		{
			get
			{
				_nextAvailableId--;
				return _nextAvailableId;
			}
		}

		public SoapTypeMapper Mapper => mapper;

		public XmlTextReader XmlReader => xmlReader;

		private object TopObject
		{
			get
			{
				objMgr.DoFixups();
				objMgr.RaiseDeserializationEvent();
				return objMgr.GetObject(_topObjectId);
			}
		}

		public SoapReader(SerializationBinder binder, ISurrogateSelector selector, StreamingContext context)
		{
			_binder = binder;
			objMgr = new ObjectManager(selector, context);
			_context = context;
			_surrogateSelector = selector;
			_fieldIndices = new Hashtable();
		}

		public object Deserialize(Stream inStream, ISoapMessage soapMessage)
		{
			CultureInfo currentCulture = CultureInfo.CurrentCulture;
			try
			{
				Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
				Deserialize_inner(inStream, soapMessage);
			}
			finally
			{
				Thread.CurrentThread.CurrentCulture = currentCulture;
			}
			return TopObject;
		}

		private void Deserialize_inner(Stream inStream, ISoapMessage soapMessage)
		{
			ArrayList arrayList = null;
			xmlReader = new XmlTextReader(inStream);
			xmlReader.WhitespaceHandling = WhitespaceHandling.None;
			mapper = new SoapTypeMapper(_binder);
			try
			{
				xmlReader.MoveToContent();
				xmlReader.ReadStartElement();
				xmlReader.MoveToContent();
				while (xmlReader.NodeType != XmlNodeType.Element || !(xmlReader.LocalName == "Body") || !(xmlReader.NamespaceURI == SoapTypeMapper.SoapEnvelopeNamespace))
				{
					if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Header" && xmlReader.NamespaceURI == SoapTypeMapper.SoapEnvelopeNamespace)
					{
						if (arrayList == null)
						{
							arrayList = new ArrayList();
						}
						DeserializeHeaders(arrayList);
					}
					else
					{
						xmlReader.Skip();
					}
					xmlReader.MoveToContent();
				}
				xmlReader.ReadStartElement();
				xmlReader.MoveToContent();
				if (soapMessage != null)
				{
					if (DeserializeMessage(soapMessage))
					{
						_topObjectId = NextAvailableId;
						RegisterObject(_topObjectId, soapMessage, null, 0L, null, null);
					}
					xmlReader.MoveToContent();
					if (arrayList != null)
					{
						soapMessage.Headers = (Header[])arrayList.ToArray(typeof(Header));
					}
				}
				while (xmlReader.NodeType != XmlNodeType.EndElement)
				{
					Deserialize();
				}
				xmlReader.ReadEndElement();
				xmlReader.MoveToContent();
				xmlReader.ReadEndElement();
			}
			finally
			{
				if (xmlReader != null)
				{
					xmlReader.Close();
				}
			}
		}

		private bool IsNull()
		{
			string text = xmlReader["null", "http://www.w3.org/2001/XMLSchema-instance"];
			if (text != null && !(text == string.Empty))
			{
				return true;
			}
			return false;
		}

		private long GetId()
		{
			string text = xmlReader["id"];
			if (text == null || text == string.Empty)
			{
				return 0L;
			}
			return Convert.ToInt64(text.Substring(4));
		}

		private long GetHref()
		{
			string text = xmlReader["href"];
			if (text == null || text == string.Empty)
			{
				return 0L;
			}
			return Convert.ToInt64(text.Substring(5));
		}

		private Type GetComponentType()
		{
			string text = xmlReader["type", "http://www.w3.org/2001/XMLSchema-instance"];
			if (text == null)
			{
				if (GetId() != 0L)
				{
					return typeof(string);
				}
				return null;
			}
			return GetTypeFromQName(text);
		}

		private bool DeserializeMessage(ISoapMessage message)
		{
			if (xmlReader.Name == SoapTypeMapper.SoapEnvelopePrefix + ":Fault")
			{
				Deserialize();
				return false;
			}
			string text = default(string);
			string text2 = default(string);
			SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlReader.NamespaceURI, ref text, ref text2);
			message.MethodName = xmlReader.LocalName;
			message.XmlNameSpace = xmlReader.NamespaceURI;
			ArrayList arrayList = new ArrayList();
			ArrayList arrayList2 = new ArrayList();
			long nextAvailableId = NextAvailableId;
			int[] array = new int[1];
			if (!xmlReader.IsEmptyElement)
			{
				int depth = xmlReader.Depth;
				xmlReader.Read();
				int num = 0;
				while (xmlReader.Depth > depth)
				{
					object obj = null;
					arrayList.Add(xmlReader.Name);
					Type componentType = null;
					if (message.ParamTypes != null)
					{
						if (num >= message.ParamTypes.Length)
						{
							throw new SerializationException("Not enough parameter types in SoapMessages");
						}
						componentType = message.ParamTypes[num];
					}
					array[0] = num;
					obj = DeserializeComponent(componentType, out var _, out var componentHref, nextAvailableId, null, array);
					array[0] = arrayList2.Add(obj);
					if (componentHref != 0L)
					{
						RecordFixup(nextAvailableId, componentHref, arrayList2.ToArray(), null, null, null, array);
					}
					num++;
				}
				xmlReader.ReadEndElement();
			}
			else
			{
				xmlReader.Read();
			}
			message.ParamNames = (string[])arrayList.ToArray(typeof(string));
			message.ParamValues = arrayList2.ToArray();
			RegisterObject(nextAvailableId, message.ParamValues, null, 0L, null, null);
			return true;
		}

		private void DeserializeHeaders(ArrayList headers)
		{
			xmlReader.ReadStartElement();
			xmlReader.MoveToContent();
			while (xmlReader.NodeType != XmlNodeType.EndElement)
			{
				if (xmlReader.NodeType != XmlNodeType.Element)
				{
					xmlReader.Skip();
					continue;
				}
				if (xmlReader.GetAttribute("root", SoapTypeMapper.SoapEncodingNamespace) == "1")
				{
					headers.Add(DeserializeHeader());
				}
				else
				{
					Deserialize();
				}
				xmlReader.MoveToContent();
			}
			xmlReader.ReadEndElement();
		}

		private Header DeserializeHeader()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			Header val = new Header(xmlReader.LocalName, (object)null);
			val.HeaderNamespace = xmlReader.NamespaceURI;
			val.MustUnderstand = xmlReader.GetAttribute("mustUnderstand", SoapTypeMapper.SoapEnvelopeNamespace) == "1";
			long nextAvailableId = NextAvailableId;
			FieldInfo field = typeof(Header).GetField("Value");
			long componentId;
			long componentHref;
			object obj = (val.Value = DeserializeComponent(null, out componentId, out componentHref, nextAvailableId, field, null));
			if (componentHref != 0L && obj == null)
			{
				RecordFixup(nextAvailableId, componentHref, val, null, null, field, null);
			}
			else if (obj != null && obj.GetType().IsValueType && componentId != 0L)
			{
				RecordFixup(nextAvailableId, componentId, val, null, null, field, null);
			}
			else if (componentId != 0L)
			{
				RegisterObject(componentId, obj, null, nextAvailableId, field, null);
			}
			RegisterObject(nextAvailableId, val, null, 0L, null, null);
			return val;
		}

		private object DeserializeArray(long id)
		{
			if (GetComponentType() == typeof(byte[]))
			{
				byte[] array = Convert.FromBase64String(xmlReader.ReadElementString());
				RegisterObject(id, array, null, 0L, null, null);
				return array;
			}
			string[] array2 = xmlReader["arrayType", SoapTypeMapper.SoapEncodingNamespace].Split(':');
			int num = array2[1].LastIndexOf('[');
			string xmlName = array2[1].Substring(0, num);
			string text = array2[1].Substring(num);
			string[] array3 = text.Substring(1, text.Length - 2).Trim().Split(',');
			int num2 = array3.Length;
			int[] array4 = new int[num2];
			for (int i = 0; i < num2; i++)
			{
				array4[i] = Convert.ToInt32(array3[i]);
			}
			int[] array5 = new int[num2];
			Array array6 = Array.CreateInstance(mapper.GetType(xmlName, xmlReader.LookupNamespace(array2[0])), array4);
			for (int j = 0; j < num2; j++)
			{
				array5[j] = array6.GetLowerBound(j);
			}
			int depth = xmlReader.Depth;
			xmlReader.Read();
			while (xmlReader.Depth > depth)
			{
				Type type = GetComponentType();
				if (type == null)
				{
					type = array6.GetType().GetElementType();
				}
				long componentId;
				long componentHref;
				object obj = DeserializeComponent(type, out componentId, out componentHref, id, null, array5);
				if (componentHref != 0L)
				{
					object @object = objMgr.GetObject(componentHref);
					if (@object != null)
					{
						array6.SetValue(@object, array5);
					}
					else
					{
						RecordFixup(id, componentHref, array6, null, null, null, array5);
					}
				}
				else if (obj != null && obj.GetType().IsValueType && componentId != 0L)
				{
					RecordFixup(id, componentId, array6, null, null, null, array5);
				}
				else if (componentId != 0L)
				{
					RegisterObject(componentId, obj, null, id, null, array5);
					array6.SetValue(obj, array5);
				}
				else
				{
					array6.SetValue(obj, array5);
				}
				for (int num3 = array6.Rank - 1; num3 >= 0; num3--)
				{
					array5[num3]++;
					if (array5[num3] <= array6.GetUpperBound(num3) || num3 <= 0)
					{
						break;
					}
					array5[num3] = array6.GetLowerBound(num3);
				}
			}
			RegisterObject(id, array6, null, 0L, null, null);
			xmlReader.ReadEndElement();
			return array6;
		}

		private object Deserialize()
		{
			object obj = null;
			Type type = mapper.GetType(xmlReader.LocalName, xmlReader.NamespaceURI);
			long id = GetId();
			id = ((id == 0L) ? 1 : id);
			if (type == typeof(Array))
			{
				return DeserializeArray(id);
			}
			return DeserializeObject(type, id, 0L, null, null);
		}

		private object DeserializeObject(Type type, long id, long parentId, MemberInfo parentMemberInfo, int[] indices)
		{
			SerializationInfo info = null;
			bool flag = false;
			if (type == typeof(string) || type == typeof(TimeSpan) || (mapper.IsInternalSoapType(type) && (indices != null || parentMemberInfo != null)))
			{
				object obj = mapper.ReadInternalSoapValue(this, type);
				if (id != 0L)
				{
					RegisterObject(id, obj, info, parentId, parentMemberInfo, indices);
				}
				return obj;
			}
			object uninitializedObject = FormatterServices.GetUninitializedObject(type);
			objMgr.RaiseOnDeserializingEvent(uninitializedObject);
			if (uninitializedObject is ISerializable)
			{
				flag = true;
			}
			if (_surrogateSelector != null && !flag)
			{
				ISurrogateSelector selector;
				ISerializationSurrogate surrogate = _surrogateSelector.GetSurrogate(type, _context, out selector);
				flag = flag || surrogate != null;
			}
			bool hasFixup;
			if (flag)
			{
				uninitializedObject = DeserializeISerializableObject(uninitializedObject, id, out info, out hasFixup);
			}
			else
			{
				uninitializedObject = DeserializeSimpleObject(uninitializedObject, id, out hasFixup);
				if (!hasFixup && uninitializedObject is IObjectReference)
				{
					uninitializedObject = ((IObjectReference)uninitializedObject).GetRealObject(_context);
				}
			}
			RegisterObject(id, uninitializedObject, info, parentId, parentMemberInfo, indices);
			xmlReader.ReadEndElement();
			return uninitializedObject;
		}

		private object DeserializeSimpleObject(object obj, long id, out bool hasFixup)
		{
			hasFixup = false;
			Type type = obj.GetType();
			TypeMetadata typeMetadata = GetTypeMetadata(type);
			object[] array = new object[typeMetadata.MemberInfos.Length];
			xmlReader.Read();
			xmlReader.MoveToContent();
			while (xmlReader.NodeType != XmlNodeType.EndElement)
			{
				if (xmlReader.NodeType != XmlNodeType.Element)
				{
					xmlReader.Skip();
					continue;
				}
				int num = (int)(typeMetadata.Indices[xmlReader.LocalName] ?? throw new SerializationException("Field \"" + xmlReader.LocalName + "\" not found in class " + type.FullName));
				FieldInfo fieldInfo = typeMetadata.MemberInfos[num] as FieldInfo;
				long componentId;
				long componentHref;
				object obj2 = (array[num] = DeserializeComponent(fieldInfo.FieldType, out componentId, out componentHref, id, fieldInfo, null));
				if (componentHref != 0L && obj2 == null)
				{
					RecordFixup(id, componentHref, obj, null, null, fieldInfo, null);
					hasFixup = true;
				}
				else if (obj2 != null && obj2.GetType().IsValueType && componentId != 0L)
				{
					RecordFixup(id, componentId, obj, null, null, fieldInfo, null);
					hasFixup = true;
				}
				else if (componentId != 0L)
				{
					RegisterObject(componentId, obj2, null, id, fieldInfo, null);
				}
			}
			FormatterServices.PopulateObjectMembers(obj, typeMetadata.MemberInfos, array);
			return obj;
		}

		private object DeserializeISerializableObject(object obj, long id, out SerializationInfo info, out bool hasFixup)
		{
			info = new SerializationInfo(obj.GetType(), new FormatterConverter());
			hasFixup = false;
			int depth = xmlReader.Depth;
			xmlReader.Read();
			while (xmlReader.Depth > depth)
			{
				Type componentType = GetComponentType();
				string text = XmlConvert.DecodeName(xmlReader.LocalName);
				long componentId;
				long componentHref;
				object obj2 = DeserializeComponent(componentType, out componentId, out componentHref, id, null, null);
				if (componentHref != 0L && obj2 == null)
				{
					RecordFixup(id, componentHref, obj, info, text, null, null);
					hasFixup = true;
					continue;
				}
				if (componentId != 0L && obj2.GetType().IsValueType)
				{
					RecordFixup(id, componentId, obj, info, text, null, null);
					hasFixup = true;
					continue;
				}
				if (componentId != 0L)
				{
					RegisterObject(componentId, obj2, null, id, null, null);
				}
				info.AddValue(text, obj2, (componentType != null) ? componentType : typeof(object));
			}
			return obj;
		}

		private object DeserializeComponent(Type componentType, out long componentId, out long componentHref, long parentId, MemberInfo parentMemberInfo, int[] indices)
		{
			componentId = 0L;
			componentHref = 0L;
			if (IsNull())
			{
				xmlReader.Read();
				return null;
			}
			Type componentType2 = GetComponentType();
			if (componentType2 != null)
			{
				componentType = componentType2;
			}
			if (xmlReader.HasAttributes)
			{
				componentId = GetId();
				componentHref = GetHref();
			}
			if (componentId != 0L)
			{
				string text = xmlReader.ReadElementString();
				objMgr.RegisterObject(text, componentId);
				return text;
			}
			if (componentHref != 0L)
			{
				xmlReader.Read();
				return objMgr.GetObject(componentHref);
			}
			if (componentType == null)
			{
				return xmlReader.ReadElementString();
			}
			componentId = NextAvailableId;
			return DeserializeObject(componentType, componentId, parentId, parentMemberInfo, indices);
		}

		public void RecordFixup(long parentObjectId, long childObjectId, object parentObject, SerializationInfo info, string fieldName, MemberInfo memberInfo, int[] indices)
		{
			if (info != null)
			{
				objMgr.RecordDelayedFixup(parentObjectId, fieldName, childObjectId);
			}
			else if (parentObject is Array)
			{
				if (indices.Length == 1)
				{
					objMgr.RecordArrayElementFixup(parentObjectId, indices[0], childObjectId);
				}
				else
				{
					objMgr.RecordArrayElementFixup(parentObjectId, (int[])indices.Clone(), childObjectId);
				}
			}
			else
			{
				objMgr.RecordFixup(parentObjectId, memberInfo, childObjectId);
			}
		}

		private void RegisterObject(long objectId, object objectInstance, SerializationInfo info, long parentObjectId, MemberInfo parentObjectMember, int[] indices)
		{
			if (parentObjectId == 0L)
			{
				indices = null;
			}
			if (!objectInstance.GetType().IsValueType || parentObjectId == 0L)
			{
				if (objMgr.GetObject(objectId) != objectInstance)
				{
					objMgr.RegisterObject(objectInstance, objectId, info, 0L, null, null);
				}
				return;
			}
			if (objMgr.GetObject(objectId) != null)
			{
				throw new SerializationException("Object already registered");
			}
			if (indices != null)
			{
				indices = (int[])indices.Clone();
			}
			objMgr.RegisterObject(objectInstance, objectId, info, parentObjectId, parentObjectMember, indices);
		}

		private TypeMetadata GetTypeMetadata(Type type)
		{
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			if (_fieldIndices[type] is TypeMetadata result)
			{
				return result;
			}
			TypeMetadata typeMetadata = new TypeMetadata();
			typeMetadata.MemberInfos = FormatterServices.GetSerializableMembers(type, _context);
			typeMetadata.Indices = new Hashtable();
			for (int i = 0; i < typeMetadata.MemberInfos.Length; i++)
			{
				SoapFieldAttribute val = (SoapFieldAttribute)InternalRemotingServices.GetCachedSoapAttribute((object)typeMetadata.MemberInfos[i]);
				typeMetadata.Indices[XmlConvert.EncodeLocalName(val.XmlElementName)] = i;
			}
			_fieldIndices[type] = typeMetadata;
			return typeMetadata;
		}

		public Type GetTypeFromQName(string qname)
		{
			string[] array = qname.Split(':');
			string xmlNamespace = xmlReader.LookupNamespace(array[0]);
			return mapper.GetType(array[1], xmlNamespace);
		}
	}
	internal class Element
	{
		private string _prefix;

		private string _localName;

		private string _namespaceURI;

		private MethodInfo _parseMethod;

		public string Prefix => _prefix;

		public string LocalName => _localName;

		public string NamespaceURI => _namespaceURI;

		public MethodInfo ParseMethod
		{
			get
			{
				return _parseMethod;
			}
			set
			{
				_parseMethod = value;
			}
		}

		public Element(string prefix, string localName, string namespaceURI)
		{
			_prefix = prefix;
			_localName = localName;
			_namespaceURI = namespaceURI;
		}

		public Element(string localName, string namespaceURI)
			: this(null, localName, namespaceURI)
		{
		}

		public override bool Equals(object obj)
		{
			Element element = obj as Element;
			if (!(_localName == XmlConvert.DecodeName(element._localName)) || !(_namespaceURI == XmlConvert.DecodeName(element._namespaceURI)))
			{
				return false;
			}
			return true;
		}

		public override int GetHashCode()
		{
			return $"{XmlConvert.DecodeName(_localName)} {XmlConvert.DecodeName(_namespaceURI)}".GetHashCode();
		}

		public override string ToString()
		{
			return $"Element.Prefix = {Prefix}, Element.LocalName = {LocalName}, Element.NamespaceURI = {NamespaceURI}";
		}
	}
	internal class SoapTypeMapper
	{
		private static Hashtable xmlNodeToTypeTable;

		private static Hashtable typeToXmlNodeTable;

		public static readonly string SoapEncodingNamespace;

		public static readonly string SoapEncodingPrefix;

		public static readonly string SoapEnvelopeNamespace;

		public static readonly string SoapEnvelopePrefix;

		private XmlTextWriter _xmlWriter;

		private long _prefixNumber;

		private Hashtable namespaceToPrefixTable = new Hashtable();

		private SerializationBinder _binder;

		private static ArrayList _canBeValueTypeList;

		private FormatterAssemblyStyle _assemblyFormat = FormatterAssemblyStyle.Full;

		private Element elementString;

		public SoapTypeMapper(SerializationBinder binder)
		{
			_binder = binder;
		}

		public SoapTypeMapper(XmlTextWriter xmlWriter, FormatterAssemblyStyle assemblyFormat, FormatterTypeStyle typeFormat)
		{
			_xmlWriter = xmlWriter;
			_assemblyFormat = assemblyFormat;
			_prefixNumber = 1L;
			if (typeFormat == FormatterTypeStyle.XsdString)
			{
				elementString = new Element("xsd", "string", "http://www.w3.org/2001/XMLSchema");
			}
			else
			{
				elementString = new Element(SoapEncodingPrefix, "string", SoapEncodingNamespace);
			}
		}

		static SoapTypeMapper()
		{
			xmlNodeToTypeTable = new Hashtable();
			typeToXmlNodeTable = new Hashtable();
			SoapEncodingNamespace = "http://schemas.xmlsoap.org/soap/encoding/";
			SoapEncodingPrefix = "SOAP-ENC";
			SoapEnvelopeNamespace = "http://schemas.xmlsoap.org/soap/envelope/";
			SoapEnvelopePrefix = "SOAP-ENV";
			_canBeValueTypeList = new ArrayList();
			_canBeValueTypeList.Add(typeof(DateTime).ToString());
			_canBeValueTypeList.Add(typeof(TimeSpan).ToString());
			_canBeValueTypeList.Add(typeof(string).ToString());
			_canBeValueTypeList.Add(typeof(decimal).ToString());
			_canBeValueTypeList.Sort();
			InitMappingTables();
		}

		private static string GetKey(string localName, string namespaceUri)
		{
			return localName + " " + namespaceUri;
		}

		public Type GetType(string xmlName, string xmlNamespace)
		{
			Type type = null;
			string text = XmlConvert.DecodeName(xmlName);
			string arg = XmlConvert.DecodeName(xmlNamespace);
			string text2 = default(string);
			string text3 = default(string);
			SoapServices.DecodeXmlNamespaceForClrTypeNamespace(xmlNamespace, ref text2, ref text3);
			string text4 = ((text2 == null || text2 == string.Empty) ? text : (text2 + Type.Delimiter + text));
			if (text3 != null && text3 != string.Empty && _binder != null)
			{
				type = _binder.BindToType(text3, text4);
			}
			if (type == null)
			{
				string text5 = (string)xmlNodeToTypeTable[GetKey(xmlName, xmlNamespace)];
				if (text5 != null)
				{
					type = Type.GetType(text5);
				}
				else
				{
					type = Type.GetType(text4);
					if (type == null)
					{
						if (text3 == null || text3 == string.Empty)
						{
							throw new SerializationException($"Parse Error, no assembly associated with XML key {text} {arg}");
						}
						type = FormatterServices.GetTypeFromAssembly(Assembly.Load(text3), text4);
					}
				}
				if (type == null)
				{
					throw new SerializationException();
				}
			}
			return type;
		}

		public Element GetXmlElement(string typeFullName, string assemblyName)
		{
			string text = string.Empty;
			string text2 = typeFullName;
			if (_assemblyFormat == FormatterAssemblyStyle.Simple)
			{
				assemblyName = assemblyName.Split(',')[0];
			}
			string key = typeFullName + ", " + assemblyName;
			Element element = (Element)typeToXmlNodeTable[key];
			if (element == null)
			{
				int num = typeFullName.LastIndexOf('.');
				if (num != -1)
				{
					text = typeFullName.Substring(0, num);
					text2 = typeFullName.Substring(text.Length + 1);
				}
				string text3 = SoapServices.CodeXmlNamespaceForClrTypeNamespace(text, (!assemblyName.StartsWith("mscorlib")) ? assemblyName : string.Empty);
				string text4 = (string)namespaceToPrefixTable[text3];
				if (text4 == null || text4 == string.Empty)
				{
					text4 = "a" + _prefixNumber++;
					namespaceToPrefixTable[text3] = text4;
				}
				int num2 = text2.IndexOf("[");
				if (num2 != -1)
				{
					text2 = XmlConvert.EncodeName(text2.Substring(0, num2)) + text2.Substring(num2);
				}
				else
				{
					int num3 = text2.IndexOf("&");
					text2 = ((num3 == -1) ? XmlConvert.EncodeName(text2) : (XmlConvert.EncodeName(text2.Substring(0, num3)) + text2.Substring(num3)));
				}
				element = new Element(text4, text2, text3);
			}
			return element;
		}

		public Element GetXmlElement(Type type)
		{
			if (type == typeof(string))
			{
				return elementString;
			}
			Element element = (Element)typeToXmlNodeTable[type.AssemblyQualifiedName];
			if (element == null)
			{
				element = GetXmlElement(type.FullName, type.Assembly.FullName);
			}
			else if (_xmlWriter != null)
			{
				element = new Element((element.Prefix == null) ? _xmlWriter.LookupPrefix(element.NamespaceURI) : element.Prefix, element.LocalName, element.NamespaceURI);
			}
			if (element == null)
			{
				throw new SerializationException("Oooops");
			}
			return element;
		}

		private static void RegisterType(Type type, string name, string namspace)
		{
			RegisterType(type, name, namspace, reverseMap: true);
		}

		private static Element RegisterType(Type type, string name, string namspace, bool reverseMap)
		{
			Element element = new Element(name, namspace);
			xmlNodeToTypeTable.Add(GetKey(name, namspace), type.AssemblyQualifiedName);
			if (reverseMap)
			{
				typeToXmlNodeTable.Add(type.AssemblyQualifiedName, element);
			}
			return element;
		}

		private static void RegisterType(Type type)
		{
			string name = (string)type.GetProperty("XsdType", BindingFlags.Static | BindingFlags.Public).GetValue(null, null);
			Element element = RegisterType(type, name, "http://www.w3.org/2001/XMLSchema", reverseMap: true);
			element.ParseMethod = type.GetMethod("Parse", BindingFlags.Static | BindingFlags.Public);
			if (element.ParseMethod == null)
			{
				throw new InvalidOperationException("Parse method not found in class " + type);
			}
		}

		private static void InitMappingTables()
		{
			RegisterType(typeof(Array), "Array", SoapEncodingNamespace);
			RegisterType(typeof(string), "string", "http://www.w3.org/2001/XMLSchema", reverseMap: false);
			RegisterType(typeof(string), "string", SoapEncodingNamespace, reverseMap: false);
			RegisterType(typeof(bool), "boolean", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(sbyte), "byte", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(byte), "unsignedByte", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(long), "long", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(ulong), "unsignedLong", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(int), "int", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(uint), "unsignedInt", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(float), "float", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(double), "double", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(decimal), "decimal", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(short), "short", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(ushort), "unsignedShort", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(object), "anyType", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(DateTime), "dateTime", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(TimeSpan), "duration", "http://www.w3.org/2001/XMLSchema");
			RegisterType(typeof(SoapFault), "Fault", SoapEnvelopeNamespace);
			RegisterType(typeof(byte[]), "base64", SoapEncodingNamespace);
			RegisterType(typeof(MethodSignature), "methodSignature", SoapEncodingNamespace);
			RegisterType(typeof(SoapAnyUri));
			RegisterType(typeof(SoapEntity));
			RegisterType(typeof(SoapMonth));
			RegisterType(typeof(SoapNonNegativeInteger));
			RegisterType(typeof(SoapToken));
			RegisterType(typeof(SoapBase64Binary));
			RegisterType(typeof(SoapHexBinary));
			RegisterType(typeof(SoapMonthDay));
			RegisterType(typeof(SoapNonPositiveInteger));
			RegisterType(typeof(SoapYear));
			RegisterType(typeof(SoapDate));
			RegisterType(typeof(SoapId));
			RegisterType(typeof(SoapName));
			RegisterType(typeof(SoapNormalizedString));
			RegisterType(typeof(SoapYearMonth));
			RegisterType(typeof(SoapIdref));
			RegisterType(typeof(SoapNcName));
			RegisterType(typeof(SoapNotation));
			RegisterType(typeof(SoapDay));
			RegisterType(typeof(SoapIdrefs));
			RegisterType(typeof(SoapNegativeInteger));
			RegisterType(typeof(SoapPositiveInteger));
			RegisterType(typeof(SoapInteger));
			RegisterType(typeof(SoapNmtoken));
			RegisterType(typeof(SoapQName));
			RegisterType(typeof(SoapEntities));
			RegisterType(typeof(SoapLanguage));
			RegisterType(typeof(SoapNmtokens));
			RegisterType(typeof(SoapTime));
		}

		public static string GetXsdValue(object value)
		{
			if (value is DateTime)
			{
				return SoapDateTime.ToString((DateTime)value);
			}
			if (value is decimal num)
			{
				return num.ToString(CultureInfo.InvariantCulture);
			}
			if (value is double num2)
			{
				return num2.ToString("G17", CultureInfo.InvariantCulture);
			}
			if (value is float num3)
			{
				return num3.ToString("G9", CultureInfo.InvariantCulture);
			}
			if (value is TimeSpan)
			{
				return SoapDuration.ToString((TimeSpan)value);
			}
			if (value is bool)
			{
				if (!(bool)value)
				{
					return "false";
				}
				return "true";
			}
			if (value is MethodSignature)
			{
				return null;
			}
			return value.ToString();
		}

		public static object ParseXsdValue(string value, Type type)
		{
			if (type == typeof(DateTime))
			{
				return SoapDateTime.Parse(value);
			}
			if (type == typeof(decimal))
			{
				return decimal.Parse(value, CultureInfo.InvariantCulture);
			}
			if (type == typeof(double))
			{
				return double.Parse(value, CultureInfo.InvariantCulture);
			}
			if (type == typeof(float))
			{
				return float.Parse(value, CultureInfo.InvariantCulture);
			}
			if (type == typeof(TimeSpan))
			{
				return SoapDuration.Parse(value);
			}
			if (type.IsEnum)
			{
				return Enum.Parse(type, value);
			}
			return Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
		}

		public static bool CanBeValue(Type type)
		{
			if (type.IsPrimitive)
			{
				return true;
			}
			if (type.IsEnum)
			{
				return true;
			}
			if (_canBeValueTypeList.BinarySearch(type.ToString()) >= 0)
			{
				return true;
			}
			return false;
		}

		public bool IsInternalSoapType(Type type)
		{
			if (CanBeValue(type))
			{
				return true;
			}
			if (typeof(ISoapXsd).IsAssignableFrom(type))
			{
				return true;
			}
			if (type == typeof(MethodSignature))
			{
				return true;
			}
			return false;
		}

		public object ReadInternalSoapValue(SoapReader reader, Type type)
		{
			if (CanBeValue(type))
			{
				return ParseXsdValue(reader.XmlReader.ReadElementString(), type);
			}
			if (type == typeof(MethodSignature))
			{
				return MethodSignature.ReadXmlValue(reader);
			}
			string text = reader.XmlReader.ReadElementString();
			Element xmlElement = GetXmlElement(type);
			if (xmlElement.ParseMethod != null)
			{
				return xmlElement.ParseMethod.Invoke(null, new object[1] { text });
			}
			throw new SerializationException("Can't parse type " + type);
		}

		public string GetInternalSoapValue(SoapWriter writer, object value)
		{
			if (CanBeValue(value.GetType()))
			{
				return GetXsdValue(value);
			}
			if (value is MethodSignature)
			{
				return ((MethodSignature)value).GetXmlValue(writer);
			}
			return value.ToString();
		}
	}
	internal class MethodSignature
	{
		private Type[] types;

		public MethodSignature(Type[] types)
		{
			this.types = types;
		}

		public static object ReadXmlValue(SoapReader reader)
		{
			reader.XmlReader.MoveToElement();
			if (reader.XmlReader.IsEmptyElement)
			{
				reader.XmlReader.Skip();
				return new Type[0];
			}
			reader.XmlReader.ReadStartElement();
			string text = reader.XmlReader.ReadString();
			while (reader.XmlReader.NodeType != XmlNodeType.EndElement)
			{
				reader.XmlReader.Skip();
			}
			ArrayList arrayList = new ArrayList();
			string[] array = text.Split(' ');
			foreach (string text2 in array)
			{
				if (text2.Length != 0)
				{
					arrayList.Add(reader.GetTypeFromQName(text2));
				}
			}
			reader.XmlReader.ReadEndElement();
			return (Type[])arrayList.ToArray(typeof(Type));
		}

		public string GetXmlValue(SoapWriter writer)
		{
			StringBuilder stringBuilder = new StringBuilder();
			Type[] array = types;
			foreach (Type type in array)
			{
				Element xmlElement = writer.Mapper.GetXmlElement(type);
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Append(' ');
				}
				string namespacePrefix = writer.GetNamespacePrefix(xmlElement);
				stringBuilder.Append(namespacePrefix).Append(':').Append(xmlElement.LocalName);
			}
			return stringBuilder.ToString();
		}
	}
	internal class SoapWriter : IComparer
	{
		private struct EnqueuedObject
		{
			public long _id;

			public object _object;

			public long Id => _id;

			public object Object => _object;

			public EnqueuedObject(object currentObject, long id)
			{
				_id = id;
				_object = currentObject;
			}
		}

		private XmlTextWriter _xmlWriter;

		private Queue _objectQueue = new Queue();

		private Hashtable _objectToIdTable = new Hashtable();

		private ISurrogateSelector _surrogateSelector;

		private SoapTypeMapper _mapper;

		private StreamingContext _context;

		private ObjectIDGenerator idGen = new ObjectIDGenerator();

		private FormatterAssemblyStyle _assemblyFormat = FormatterAssemblyStyle.Full;

		private FormatterTypeStyle _typeFormat;

		private static string defaultMessageNamespace;

		private SerializationObjectManager _manager;

		public SoapTypeMapper Mapper => _mapper;

		public XmlTextWriter XmlWriter => _xmlWriter;

		internal FormatterAssemblyStyle AssemblyFormat
		{
			get
			{
				return _assemblyFormat;
			}
			set
			{
				_assemblyFormat = value;
			}
		}

		internal FormatterTypeStyle TypeFormat
		{
			get
			{
				return _typeFormat;
			}
			set
			{
				_typeFormat = value;
			}
		}

		~SoapWriter()
		{
		}

		internal SoapWriter(Stream outStream, ISurrogateSelector selector, StreamingContext context, ISoapMessage soapMessage)
		{
			_xmlWriter = new XmlTextWriter(outStream, null);
			_xmlWriter.Formatting = Formatting.Indented;
			_surrogateSelector = selector;
			_context = context;
			_manager = new SerializationObjectManager(_context);
		}

		static SoapWriter()
		{
			defaultMessageNamespace = typeof(SoapWriter).Assembly.GetName().FullName;
		}

		private void Id(long id)
		{
			_xmlWriter.WriteAttributeString(null, "id", null, "ref-" + id);
		}

		private void Href(long href)
		{
			_xmlWriter.WriteAttributeString(null, "href", null, "#ref-" + href);
		}

		private void Null()
		{
			_xmlWriter.WriteAttributeString("xsi", "null", "http://www.w3.org/2001/XMLSchema-instance", "1");
		}

		private bool IsEncodingNeeded(object componentObject, Type componentType)
		{
			if (componentObject == null)
			{
				return false;
			}
			if (_typeFormat == FormatterTypeStyle.TypesAlways)
			{
				return true;
			}
			if (componentType == null)
			{
				componentType = componentObject.GetType();
				if (componentType.IsPrimitive || componentType == typeof(string))
				{
					return false;
				}
				return true;
			}
			if (componentType == typeof(object) || componentType != componentObject.GetType())
			{
				return true;
			}
			return false;
		}

		internal void Serialize(object objGraph, Header[] headers, FormatterTypeStyle typeFormat, FormatterAssemblyStyle assemblyFormat)
		{
			CultureInfo currentCulture = CultureInfo.CurrentCulture;
			try
			{
				Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
				Serialize_inner(objGraph, headers, typeFormat, assemblyFormat);
			}
			finally
			{
				Thread.CurrentThread.CurrentCulture = currentCulture;
			}
			_manager.RaiseOnSerializedEvent();
		}

		private void Serialize_inner(object objGraph, Header[] headers, FormatterTypeStyle typeFormat, FormatterAssemblyStyle assemblyFormat)
		{
			_typeFormat = typeFormat;
			_assemblyFormat = assemblyFormat;
			_mapper = new SoapTypeMapper(_xmlWriter, assemblyFormat, typeFormat);
			_xmlWriter.WriteStartElement(SoapTypeMapper.SoapEnvelopePrefix, "Envelope", SoapTypeMapper.SoapEnvelopeNamespace);
			_xmlWriter.WriteAttributeString("xmlns", "xsi", "http://www.w3.org/2000/xmlns/", "http://www.w3.org/2001/XMLSchema-instance");
			_xmlWriter.WriteAttributeString("xmlns", "xsd", "http://www.w3.org/2000/xmlns/", "http://www.w3.org/2001/XMLSchema");
			_xmlWriter.WriteAttributeString("xmlns", SoapTypeMapper.SoapEncodingPrefix, "http://www.w3.org/2000/xmlns/", SoapTypeMapper.SoapEncodingNamespace);
			_xmlWriter.WriteAttributeString("xmlns", SoapTypeMapper.SoapEnvelopePrefix, "http://www.w3.org/2000/xmlns/", SoapTypeMapper.SoapEnvelopeNamespace);
			_xmlWriter.WriteAttributeString("xmlns", "clr", "http://www.w3.org/2000/xmlns/", SoapServices.XmlNsForClrType);
			_xmlWriter.WriteAttributeString(SoapTypeMapper.SoapEnvelopePrefix, "encodingStyle", SoapTypeMapper.SoapEnvelopeNamespace, "http://schemas.xmlsoap.org/soap/encoding/");
			ISoapMessage val = (ISoapMessage)((objGraph is ISoapMessage) ? objGraph : null);
			if (val != null)
			{
				headers = val.Headers;
			}
			if (headers != null && headers.Length != 0)
			{
				_xmlWriter.WriteStartElement(SoapTypeMapper.SoapEnvelopePrefix, "Header", SoapTypeMapper.SoapEnvelopeNamespace);
				Header[] array = headers;
				foreach (Header header in array)
				{
					SerializeHeader(header);
				}
				WriteObjectQueue();
				_xmlWriter.WriteEndElement();
			}
			_xmlWriter.WriteStartElement(SoapTypeMapper.SoapEnvelopePrefix, "Body", SoapTypeMapper.SoapEnvelopeNamespace);
			bool firstTime = false;
			if (val != null)
			{
				SerializeMessage(val);
			}
			else
			{
				_objectQueue.Enqueue(new EnqueuedObject(objGraph, idGen.GetId(objGraph, out firstTime)));
			}
			WriteObjectQueue();
			_xmlWriter.WriteFullEndElement();
			_xmlWriter.WriteFullEndElement();
			_xmlWriter.Flush();
		}

		private void WriteObjectQueue()
		{
			while (_objectQueue.Count > 0)
			{
				EnqueuedObject enqueuedObject = (EnqueuedObject)_objectQueue.Dequeue();
				object @object = enqueuedObject.Object;
				Type type = @object.GetType();
				if (!type.IsValueType)
				{
					_objectToIdTable[@object] = enqueuedObject.Id;
				}
				if (type.IsArray)
				{
					SerializeArray((Array)@object, enqueuedObject.Id);
				}
				else
				{
					SerializeObject(@object, enqueuedObject.Id);
				}
			}
		}

		private void SerializeMessage(ISoapMessage message)
		{
			string ns = ((message.XmlNameSpace != null) ? message.XmlNameSpace : defaultMessageNamespace);
			_xmlWriter.WriteStartElement("i2", message.MethodName, ns);
			Id(idGen.GetId(message, out var _));
			string[] paramNames = message.ParamNames;
			object[] paramValues = message.ParamValues;
			int num = ((paramNames != null) ? paramNames.Length : 0);
			for (int i = 0; i < num; i++)
			{
				_xmlWriter.WriteStartElement(paramNames[i]);
				SerializeComponent(paramValues[i], specifyEncoding: true);
				_xmlWriter.WriteEndElement();
			}
			_xmlWriter.WriteFullEndElement();
		}

		private void SerializeHeader(Header header)
		{
			string ns = ((header.HeaderNamespace != null) ? header.HeaderNamespace : "http://schemas.microsoft.com/clr/soap");
			_xmlWriter.WriteStartElement("h4", header.Name, ns);
			if (header.MustUnderstand)
			{
				_xmlWriter.WriteAttributeString("mustUnderstand", SoapTypeMapper.SoapEnvelopeNamespace, "1");
			}
			_xmlWriter.WriteAttributeString("root", SoapTypeMapper.SoapEncodingNamespace, "1");
			if (header.Name == "__MethodSignature")
			{
				if (!(header.Value is Type[] types))
				{
					throw new SerializationException("Invalid method signature.");
				}
				SerializeComponent(new MethodSignature(types), specifyEncoding: true);
			}
			else
			{
				SerializeComponent(header.Value, specifyEncoding: true);
			}
			_xmlWriter.WriteEndElement();
		}

		private void SerializeObject(object currentObject, long currentObjectId)
		{
			bool flag = false;
			ISerializationSurrogate serializationSurrogate = null;
			if (_surrogateSelector != null)
			{
				serializationSurrogate = _surrogateSelector.GetSurrogate(currentObject.GetType(), _context, out ISurrogateSelector _);
			}
			if (currentObject is ISerializable || serializationSurrogate != null)
			{
				flag = true;
			}
			_manager.RegisterObject(currentObject);
			if (flag)
			{
				SerializeISerializableObject(currentObject, currentObjectId, serializationSurrogate);
				return;
			}
			if (!currentObject.GetType().IsSerializable)
			{
				throw new SerializationException($"Type {currentObject.GetType()} in assembly {currentObject.GetType().Assembly.FullName} is not marked as serializable.");
			}
			SerializeSimpleObject(currentObject, currentObjectId);
		}

		public int Compare(object x, object y)
		{
			MemberInfo obj = x as MemberInfo;
			MemberInfo memberInfo = y as MemberInfo;
			return string.Compare(obj.Name, memberInfo.Name);
		}

		private void SerializeSimpleObject(object currentObject, long currentObjectId)
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Expected O, but got Unknown
			Type type = currentObject.GetType();
			if (currentObjectId > 0)
			{
				Element xmlElement = _mapper.GetXmlElement(type);
				_xmlWriter.WriteStartElement(xmlElement.Prefix, xmlElement.LocalName, xmlElement.NamespaceURI);
				Id(currentObjectId);
			}
			if (type == typeof(TimeSpan))
			{
				_xmlWriter.WriteString(SoapTypeMapper.GetXsdValue(currentObject));
			}
			else if (type == typeof(string))
			{
				_xmlWriter.WriteString(currentObject.ToString());
			}
			else
			{
				MemberInfo[] serializableMembers = FormatterServices.GetSerializableMembers(type, _context);
				object[] objectData = FormatterServices.GetObjectData(currentObject, serializableMembers);
				for (int i = 0; i < serializableMembers.Length; i++)
				{
					FieldInfo fieldInfo = (FieldInfo)serializableMembers[i];
					SoapFieldAttribute val = (SoapFieldAttribute)InternalRemotingServices.GetCachedSoapAttribute((object)fieldInfo);
					_xmlWriter.WriteStartElement(XmlConvert.EncodeLocalName(val.XmlElementName));
					SerializeComponent(objectData[i], IsEncodingNeeded(objectData[i], fieldInfo.FieldType));
					_xmlWriter.WriteEndElement();
				}
			}
			if (currentObjectId > 0)
			{
				_xmlWriter.WriteFullEndElement();
			}
		}

		private void SerializeISerializableObject(object currentObject, long currentObjectId, ISerializationSurrogate surrogate)
		{
			SerializationInfo serializationInfo = new SerializationInfo(currentObject.GetType(), new FormatterConverter());
			ISerializable serializable = currentObject as ISerializable;
			if (surrogate != null)
			{
				surrogate.GetObjectData(currentObject, serializationInfo, _context);
			}
			else
			{
				serializable.GetObjectData(serializationInfo, _context);
			}
			if (currentObjectId > 0)
			{
				Element xmlElement = _mapper.GetXmlElement(serializationInfo.FullTypeName, serializationInfo.AssemblyName);
				_xmlWriter.WriteStartElement(xmlElement.Prefix, xmlElement.LocalName, xmlElement.NamespaceURI);
				Id(currentObjectId);
			}
			SerializationInfoEnumerator enumerator = serializationInfo.GetEnumerator();
			while (enumerator.MoveNext())
			{
				SerializationEntry current = enumerator.Current;
				_xmlWriter.WriteStartElement(XmlConvert.EncodeLocalName(current.Name));
				SerializeComponent(current.Value, IsEncodingNeeded(current.Value, null));
				_xmlWriter.WriteEndElement();
			}
			if (currentObjectId > 0)
			{
				_xmlWriter.WriteFullEndElement();
			}
		}

		private void SerializeArray(Array currentArray, long currentArrayId)
		{
			Element xmlElement = _mapper.GetXmlElement(typeof(Array));
			Type elementType = currentArray.GetType().GetElementType();
			Element xmlElement2 = _mapper.GetXmlElement(elementType);
			_xmlWriter.WriteStartElement(xmlElement.Prefix, xmlElement.LocalName, xmlElement.NamespaceURI);
			if (currentArrayId > 0)
			{
				Id(currentArrayId);
			}
			if (elementType == typeof(byte))
			{
				EncodeType(currentArray.GetType());
				_xmlWriter.WriteString(Convert.ToBase64String((byte[])currentArray));
				_xmlWriter.WriteFullEndElement();
				return;
			}
			string namespacePrefix = GetNamespacePrefix(xmlElement2);
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendFormat("{0}:{1}[", namespacePrefix, xmlElement2.LocalName);
			for (int i = 0; i < currentArray.Rank; i++)
			{
				stringBuilder.AppendFormat("{0},", currentArray.GetUpperBound(i) + 1);
			}
			stringBuilder.Replace(',', ']', stringBuilder.Length - 1, 1);
			_xmlWriter.WriteAttributeString(SoapTypeMapper.SoapEncodingPrefix, "arrayType", SoapTypeMapper.SoapEncodingNamespace, stringBuilder.ToString());
			int num = 0;
			int num2 = 0;
			foreach (object item in currentArray)
			{
				if (item != null)
				{
					for (int j = num; j < num2; j++)
					{
						_xmlWriter.WriteStartElement("item");
						Null();
						_xmlWriter.WriteEndElement();
					}
					num = num2 + 1;
					_xmlWriter.WriteStartElement("item");
					SerializeComponent(item, IsEncodingNeeded(item, elementType));
					_xmlWriter.WriteEndElement();
				}
				num2++;
			}
			_xmlWriter.WriteFullEndElement();
		}

		private void SerializeComponent(object obj, bool specifyEncoding)
		{
			if (_typeFormat == FormatterTypeStyle.TypesAlways)
			{
				specifyEncoding = true;
			}
			if (obj == null)
			{
				Null();
				return;
			}
			Type type = obj.GetType();
			bool flag = _mapper.IsInternalSoapType(type);
			long num = 0L;
			if ((num = idGen.HasId(obj, out var firstTime)) != 0L)
			{
				Href(idGen.GetId(obj, out firstTime));
				return;
			}
			if (type == typeof(string) && _typeFormat != FormatterTypeStyle.XsdString)
			{
				num = idGen.GetId(obj, out firstTime);
				Id(num);
			}
			if (!flag && !type.IsValueType)
			{
				long id = idGen.GetId(obj, out firstTime);
				Href(id);
				_objectQueue.Enqueue(new EnqueuedObject(obj, id));
				return;
			}
			if (specifyEncoding)
			{
				EncodeType(type);
			}
			if (!flag && type.IsValueType)
			{
				SerializeObject(obj, 0L);
			}
			else
			{
				_xmlWriter.WriteString(_mapper.GetInternalSoapValue(this, obj));
			}
		}

		private void EncodeType(Type type)
		{
			if (type == null)
			{
				throw new SerializationException("Oooops");
			}
			Element xmlElement = _mapper.GetXmlElement(type);
			string namespacePrefix = GetNamespacePrefix(xmlElement);
			_xmlWriter.WriteAttributeString("xsi", "type", "http://www.w3.org/2001/XMLSchema-instance", namespacePrefix + ":" + xmlElement.LocalName);
		}

		public string GetNamespacePrefix(Element xmlType)
		{
			string text = _xmlWriter.LookupPrefix(xmlType.NamespaceURI);
			if (text == null || text == string.Empty)
			{
				_xmlWriter.WriteAttributeString("xmlns", xmlType.Prefix, "http://www.w3.org/2000/xmlns/", xmlType.NamespaceURI);
				return xmlType.Prefix;
			}
			return text;
		}
	}
}

BepInEx/core/System.Security.AccessControl.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using FxResources.System.Security.AccessControl;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyDefaultAlias("System.Security.AccessControl")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("NotSupported", "True")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("System.Security.AccessControl")]
[assembly: AssemblyFileVersion("4.700.19.56404")]
[assembly: AssemblyInformationalVersion("3.1.0+0f7f38c4fd323b26da10cce95f857f77f0f09b48")]
[assembly: AssemblyProduct("Microsoft® .NET Core")]
[assembly: AssemblyTitle("System.Security.AccessControl")]
[assembly: CLSCompliant(true)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.1.3.0")]
[module: UnverifiableCode]
namespace FxResources.System.Security.AccessControl
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string AccessControl_AclTooLong => GetResourceString("AccessControl_AclTooLong");

		internal static string AccessControl_InvalidAccessRuleType => GetResourceString("AccessControl_InvalidAccessRuleType");

		internal static string AccessControl_InvalidAuditRuleType => GetResourceString("AccessControl_InvalidAuditRuleType");

		internal static string AccessControl_InvalidOwner => GetResourceString("AccessControl_InvalidOwner");

		internal static string AccessControl_InvalidGroup => GetResourceString("AccessControl_InvalidGroup");

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

		internal static string AccessControl_InvalidSecurityDescriptorRevision => GetResourceString("AccessControl_InvalidSecurityDescriptorRevision");

		internal static string AccessControl_InvalidSecurityDescriptorSelfRelativeForm => GetResourceString("AccessControl_InvalidSecurityDescriptorSelfRelativeForm");

		internal static string AccessControl_InvalidSidInSDDLString => GetResourceString("AccessControl_InvalidSidInSDDLString");

		internal static string AccessControl_MustSpecifyContainerAcl => GetResourceString("AccessControl_MustSpecifyContainerAcl");

		internal static string AccessControl_MustSpecifyDirectoryObjectAcl => GetResourceString("AccessControl_MustSpecifyDirectoryObjectAcl");

		internal static string AccessControl_MustSpecifyLeafObjectAcl => GetResourceString("AccessControl_MustSpecifyLeafObjectAcl");

		internal static string AccessControl_MustSpecifyNonDirectoryObjectAcl => GetResourceString("AccessControl_MustSpecifyNonDirectoryObjectAcl");

		internal static string AccessControl_NoAssociatedSecurity => GetResourceString("AccessControl_NoAssociatedSecurity");

		internal static string AccessControl_UnexpectedError => GetResourceString("AccessControl_UnexpectedError");

		internal static string Arg_EnumAtLeastOneFlag => GetResourceString("Arg_EnumAtLeastOneFlag");

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

		internal static string Arg_InvalidOperationException => GetResourceString("Arg_InvalidOperationException");

		internal static string Arg_MustBeIdentityReferenceType => GetResourceString("Arg_MustBeIdentityReferenceType");

		internal static string Argument_ArgumentZero => GetResourceString("Argument_ArgumentZero");

		internal static string Argument_InvalidAnyFlag => GetResourceString("Argument_InvalidAnyFlag");

		internal static string Argument_InvalidEnumValue => GetResourceString("Argument_InvalidEnumValue");

		internal static string Argument_InvalidName => GetResourceString("Argument_InvalidName");

		internal static string Argument_InvalidPrivilegeName => GetResourceString("Argument_InvalidPrivilegeName");

		internal static string Argument_InvalidSafeHandle => GetResourceString("Argument_InvalidSafeHandle");

		internal static string ArgumentException_InvalidAceBinaryForm => GetResourceString("ArgumentException_InvalidAceBinaryForm");

		internal static string ArgumentException_InvalidAclBinaryForm => GetResourceString("ArgumentException_InvalidAclBinaryForm");

		internal static string ArgumentException_InvalidSDSddlForm => GetResourceString("ArgumentException_InvalidSDSddlForm");

		internal static string ArgumentOutOfRange_ArrayLength => GetResourceString("ArgumentOutOfRange_ArrayLength");

		internal static string ArgumentOutOfRange_ArrayLengthMultiple => GetResourceString("ArgumentOutOfRange_ArrayLengthMultiple");

		internal static string ArgumentOutOfRange_ArrayTooSmall => GetResourceString("ArgumentOutOfRange_ArrayTooSmall");

		internal static string ArgumentOutOfRange_Enum => GetResourceString("ArgumentOutOfRange_Enum");

		internal static string ArgumentOutOfRange_InvalidUserDefinedAceType => GetResourceString("ArgumentOutOfRange_InvalidUserDefinedAceType");

		internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum");

		internal static string InvalidOperation_ModificationOfNonCanonicalAcl => GetResourceString("InvalidOperation_ModificationOfNonCanonicalAcl");

		internal static string InvalidOperation_MustBeSameThread => GetResourceString("InvalidOperation_MustBeSameThread");

		internal static string InvalidOperation_MustLockForReadOrWrite => GetResourceString("InvalidOperation_MustLockForReadOrWrite");

		internal static string InvalidOperation_MustLockForWrite => GetResourceString("InvalidOperation_MustLockForWrite");

		internal static string InvalidOperation_MustRevertPrivilege => GetResourceString("InvalidOperation_MustRevertPrivilege");

		internal static string InvalidOperation_NoSecurityDescriptor => GetResourceString("InvalidOperation_NoSecurityDescriptor");

		internal static string InvalidOperation_OnlyValidForDS => GetResourceString("InvalidOperation_OnlyValidForDS");

		internal static string InvalidOperation_DisconnectedPipe => GetResourceString("InvalidOperation_DisconnectedPipe");

		internal static string NotSupported_SetMethod => GetResourceString("NotSupported_SetMethod");

		internal static string PrivilegeNotHeld_Default => GetResourceString("PrivilegeNotHeld_Default");

		internal static string PrivilegeNotHeld_Named => GetResourceString("PrivilegeNotHeld_Named");

		internal static string Rank_MultiDimNotSupported => GetResourceString("Rank_MultiDimNotSupported");

		internal static string PlatformNotSupported_AccessControl => GetResourceString("PlatformNotSupported_AccessControl");

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

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

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Security.AccessControl
{
	[Flags]
	public enum AccessControlActions
	{
		None = 0,
		View = 1,
		Change = 2
	}
	public enum AccessControlModification
	{
		Add,
		Set,
		Reset,
		Remove,
		RemoveAll,
		RemoveSpecific
	}
	[Flags]
	public enum AccessControlSections
	{
		None = 0,
		Audit = 1,
		Access = 2,
		Owner = 4,
		Group = 8,
		All = 0xF
	}
	public enum AccessControlType
	{
		Allow,
		Deny
	}
	public abstract class AccessRule : AuthorizationRule
	{
		public AccessControlType AccessControlType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected AccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public class AccessRule<T> : AccessRule where T : struct
	{
		public T Rights
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public AccessRule(IdentityReference identity, T rights, AccessControlType type)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public AccessRule(IdentityReference identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public AccessRule(string identity, T rights, AccessControlType type)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public AccessRule(string identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class AceEnumerator : IEnumerator
	{
		public GenericAce Current
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		object IEnumerator.Current
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		internal AceEnumerator()
		{
		}

		public bool MoveNext()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void Reset()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	[Flags]
	public enum AceFlags : byte
	{
		None = 0,
		ObjectInherit = 1,
		ContainerInherit = 2,
		NoPropagateInherit = 4,
		InheritOnly = 8,
		InheritanceFlags = 0xF,
		Inherited = 0x10,
		SuccessfulAccess = 0x40,
		FailedAccess = 0x80,
		AuditFlags = 0xC0
	}
	public enum AceQualifier
	{
		AccessAllowed,
		AccessDenied,
		SystemAudit,
		SystemAlarm
	}
	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,
		MaxDefinedAceType = 16,
		SystemAlarmCallbackObject = 16
	}
	[Flags]
	public enum AuditFlags
	{
		None = 0,
		Success = 1,
		Failure = 2
	}
	public abstract class AuditRule : AuthorizationRule
	{
		public AuditFlags AuditFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected AuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags auditFlags)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public class AuditRule<T> : AuditRule where T : struct
	{
		public T Rights
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public AuditRule(IdentityReference identity, T rights, AuditFlags flags)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public AuditRule(IdentityReference identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public AuditRule(string identity, T rights, AuditFlags flags)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public AuditRule(string identity, T rights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class AuthorizationRule
	{
		protected internal int AccessMask
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public IdentityReference IdentityReference
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public InheritanceFlags InheritanceFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsInherited
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public PropagationFlags PropagationFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected internal AuthorizationRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class AuthorizationRuleCollection : ReadOnlyCollectionBase
	{
		public AuthorizationRule this[int index]
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public AuthorizationRuleCollection()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddRule(AuthorizationRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void CopyTo(AuthorizationRule[] rules, int index)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class CommonAce : QualifiedAce
	{
		public override int BinaryLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public CommonAce(AceFlags flags, AceQualifier qualifier, int accessMask, SecurityIdentifier sid, bool isCallback, byte[] opaque)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public static int MaxOpaqueLength(bool isCallback)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class CommonAcl : GenericAcl
	{
		public sealed override int BinaryLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public sealed override int Count
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsCanonical
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsContainer
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsDS
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public sealed override GenericAce this[int index]
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public sealed override byte Revision
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		internal CommonAcl()
		{
		}

		public sealed override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void Purge(SecurityIdentifier sid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void RemoveInheritedAces()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class CommonObjectSecurity : ObjectSecurity
	{
		protected CommonObjectSecurity(bool isContainer)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void AddAccessRule(AccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void AddAuditRule(AuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public AuthorizationRuleCollection GetAccessRules(bool includeExplicit, bool includeInherited, Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public AuthorizationRuleCollection GetAuditRules(bool includeExplicit, bool includeInherited, Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected override bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected override bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected bool RemoveAccessRule(AccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void RemoveAccessRuleAll(AccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void RemoveAccessRuleSpecific(AccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected bool RemoveAuditRule(AuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void RemoveAuditRuleAll(AuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void RemoveAuditRuleSpecific(AuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void ResetAccessRule(AccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void SetAccessRule(AccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void SetAuditRule(AuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class CommonSecurityDescriptor : GenericSecurityDescriptor
	{
		public override ControlFlags ControlFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public DiscretionaryAcl DiscretionaryAcl
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override SecurityIdentifier Group
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsContainer
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsDiscretionaryAclCanonical
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsDS
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsSystemAclCanonical
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override SecurityIdentifier Owner
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public SystemAcl SystemAcl
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public CommonSecurityDescriptor(bool isContainer, bool isDS, byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public CommonSecurityDescriptor(bool isContainer, bool isDS, ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, SystemAcl systemAcl, DiscretionaryAcl discretionaryAcl)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public CommonSecurityDescriptor(bool isContainer, bool isDS, RawSecurityDescriptor rawSecurityDescriptor)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public CommonSecurityDescriptor(bool isContainer, bool isDS, string sddlForm)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddDiscretionaryAcl(byte revision, int trusted)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddSystemAcl(byte revision, int trusted)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void PurgeAccessControl(SecurityIdentifier sid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void PurgeAudit(SecurityIdentifier sid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetDiscretionaryAclProtection(bool isProtected, bool preserveInheritance)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetSystemAclProtection(bool isProtected, bool preserveInheritance)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class CompoundAce : KnownAce
	{
		public override int BinaryLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public CompoundAceType CompoundAceType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public CompoundAce(AceFlags flags, int accessMask, CompoundAceType compoundAceType, SecurityIdentifier sid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public enum CompoundAceType
	{
		Impersonation = 1
	}
	[Flags]
	public enum ControlFlags
	{
		None = 0,
		OwnerDefaulted = 1,
		GroupDefaulted = 2,
		DiscretionaryAclPresent = 4,
		DiscretionaryAclDefaulted = 8,
		SystemAclPresent = 0x10,
		SystemAclDefaulted = 0x20,
		DiscretionaryAclUntrusted = 0x40,
		ServerSecurity = 0x80,
		DiscretionaryAclAutoInheritRequired = 0x100,
		SystemAclAutoInheritRequired = 0x200,
		DiscretionaryAclAutoInherited = 0x400,
		SystemAclAutoInherited = 0x800,
		DiscretionaryAclProtected = 0x1000,
		SystemAclProtected = 0x2000,
		RMControlValid = 0x4000,
		SelfRelative = 0x8000
	}
	public sealed class CustomAce : GenericAce
	{
		public static readonly int MaxOpaqueLength;

		public override int BinaryLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public int OpaqueLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public CustomAce(AceType type, AceFlags flags, byte[] opaque)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public byte[] GetOpaque()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetOpaque(byte[] opaque)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class DiscretionaryAcl : CommonAcl
	{
		public DiscretionaryAcl(bool isContainer, bool isDS, byte revision, int capacity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public DiscretionaryAcl(bool isContainer, bool isDS, int capacity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public DiscretionaryAcl(bool isContainer, bool isDS, RawAcl rawAcl)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public bool RemoveAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void RemoveAccessSpecific(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetAccess(AccessControlType accessType, SecurityIdentifier sid, ObjectAccessRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class GenericAce
	{
		public AceFlags AceFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public AceType AceType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public AuditFlags AuditFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public abstract int BinaryLength { get; }

		public InheritanceFlags InheritanceFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsInherited
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public PropagationFlags PropagationFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		internal GenericAce()
		{
		}

		public GenericAce Copy()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public static GenericAce CreateFromBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public sealed override bool Equals(object o)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public abstract void GetBinaryForm(byte[] binaryForm, int offset);

		public sealed override int GetHashCode()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public static bool operator ==(GenericAce left, GenericAce right)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public static bool operator !=(GenericAce left, GenericAce right)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class GenericAcl : ICollection, IEnumerable
	{
		public static readonly byte AclRevision;

		public static readonly byte AclRevisionDS;

		public static readonly int MaxBinaryLength;

		public abstract int BinaryLength { get; }

		public abstract int Count { get; }

		public bool IsSynchronized
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public abstract GenericAce this[int index] { get; set; }

		public abstract byte Revision { get; }

		public virtual object SyncRoot
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected GenericAcl()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void CopyTo(GenericAce[] array, int index)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public abstract void GetBinaryForm(byte[] binaryForm, int offset);

		public AceEnumerator GetEnumerator()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		void ICollection.CopyTo(Array array, int index)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class GenericSecurityDescriptor
	{
		public int BinaryLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public abstract ControlFlags ControlFlags { get; }

		public abstract SecurityIdentifier Group { get; set; }

		public abstract SecurityIdentifier Owner { get; set; }

		public static byte Revision
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		internal GenericSecurityDescriptor()
		{
		}

		public void GetBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public string GetSddlForm(AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public static bool IsSddlConversionSupported()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	[Flags]
	public enum InheritanceFlags
	{
		None = 0,
		ContainerInherit = 1,
		ObjectInherit = 2
	}
	public abstract class KnownAce : GenericAce
	{
		public int AccessMask
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public SecurityIdentifier SecurityIdentifier
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		internal KnownAce()
		{
		}
	}
	public abstract class NativeObjectSecurity : CommonObjectSecurity
	{
		protected internal delegate Exception ExceptionFromErrorCode(int errorCode, string name, SafeHandle handle, object context);

		protected NativeObjectSecurity(bool isContainer, ResourceType resourceType)
			: base(isContainer: false)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections)
			: base(isContainer: false)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle handle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
			: base(isContainer: false)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
			: base(isContainer: false)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections)
			: base(isContainer: false)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected NativeObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
			: base(isContainer: false)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected sealed override void Persist(SafeHandle handle, AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void Persist(SafeHandle handle, AccessControlSections includeSections, object exceptionContext)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected sealed override void Persist(string name, AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void Persist(string name, AccessControlSections includeSections, object exceptionContext)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class ObjectAccessRule : AccessRule
	{
		public Guid InheritedObjectType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public ObjectAceFlags ObjectFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public Guid ObjectType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected ObjectAccessRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AccessControlType type)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class ObjectAce : QualifiedAce
	{
		public override int BinaryLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public Guid InheritedObjectAceType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public ObjectAceFlags ObjectAceFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public Guid ObjectAceType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public ObjectAce(AceFlags aceFlags, AceQualifier qualifier, int accessMask, SecurityIdentifier sid, ObjectAceFlags flags, Guid type, Guid inheritedType, bool isCallback, byte[] opaque)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public static int MaxOpaqueLength(bool isCallback)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	[Flags]
	public enum ObjectAceFlags
	{
		None = 0,
		ObjectAceTypePresent = 1,
		InheritedObjectAceTypePresent = 2
	}
	public abstract class ObjectAuditRule : AuditRule
	{
		public Guid InheritedObjectType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public ObjectAceFlags ObjectFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public Guid ObjectType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected ObjectAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AuditFlags auditFlags)
			: base(null, 0, isInherited: false, InheritanceFlags.None, PropagationFlags.None, AuditFlags.None)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class ObjectSecurity
	{
		public abstract Type AccessRightType { get; }

		protected bool AccessRulesModified
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public abstract Type AccessRuleType { get; }

		public bool AreAccessRulesCanonical
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool AreAccessRulesProtected
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool AreAuditRulesCanonical
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool AreAuditRulesProtected
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected bool AuditRulesModified
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public abstract Type AuditRuleType { get; }

		protected bool GroupModified
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected bool IsContainer
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected bool IsDS
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected bool OwnerModified
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected CommonSecurityDescriptor SecurityDescriptor
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected ObjectSecurity()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected ObjectSecurity(bool isContainer, bool isDS)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected ObjectSecurity(CommonSecurityDescriptor securityDescriptor)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public abstract AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type);

		public abstract AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags);

		public IdentityReference GetGroup(Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public IdentityReference GetOwner(Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public byte[] GetSecurityDescriptorBinaryForm()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public string GetSecurityDescriptorSddlForm(AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public static bool IsSddlConversionSupported()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected abstract bool ModifyAccess(AccessControlModification modification, AccessRule rule, out bool modified);

		public virtual bool ModifyAccessRule(AccessControlModification modification, AccessRule rule, out bool modified)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected abstract bool ModifyAudit(AccessControlModification modification, AuditRule rule, out bool modified);

		public virtual bool ModifyAuditRule(AccessControlModification modification, AuditRule rule, out bool modified)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected virtual void Persist(bool enableOwnershipPrivilege, string name, AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected virtual void Persist(SafeHandle handle, AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected virtual void Persist(string name, AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void PurgeAccessRules(IdentityReference identity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void PurgeAuditRules(IdentityReference identity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void ReadLock()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void ReadUnlock()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetAccessRuleProtection(bool isProtected, bool preserveInheritance)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetAuditRuleProtection(bool isProtected, bool preserveInheritance)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetGroup(IdentityReference identity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetOwner(IdentityReference identity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetSecurityDescriptorBinaryForm(byte[] binaryForm)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetSecurityDescriptorBinaryForm(byte[] binaryForm, AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetSecurityDescriptorSddlForm(string sddlForm)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetSecurityDescriptorSddlForm(string sddlForm, AccessControlSections includeSections)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void WriteLock()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected void WriteUnlock()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public abstract class ObjectSecurity<T> : NativeObjectSecurity where T : struct
	{
		public override Type AccessRightType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override Type AccessRuleType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override Type AuditRuleType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		protected ObjectSecurity(bool isContainer, ResourceType resourceType)
			: base(isContainer: false, ResourceType.Unknown)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle safeHandle, AccessControlSections includeSections)
			: base(isContainer: false, ResourceType.Unknown)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected ObjectSecurity(bool isContainer, ResourceType resourceType, SafeHandle safeHandle, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
			: base(isContainer: false, ResourceType.Unknown)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected ObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections)
			: base(isContainer: false, ResourceType.Unknown)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected ObjectSecurity(bool isContainer, ResourceType resourceType, string name, AccessControlSections includeSections, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext)
			: base(isContainer: false, ResourceType.Unknown)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void AddAccessRule(AccessRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void AddAuditRule(AuditRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected internal void Persist(SafeHandle handle)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		protected internal void Persist(string name)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual bool RemoveAccessRule(AccessRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void RemoveAccessRuleAll(AccessRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void RemoveAccessRuleSpecific(AccessRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual bool RemoveAuditRule(AuditRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void RemoveAuditRuleAll(AuditRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void RemoveAuditRuleSpecific(AuditRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void ResetAccessRule(AccessRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void SetAccessRule(AccessRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public virtual void SetAuditRule(AuditRule<T> rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class PrivilegeNotHeldException : UnauthorizedAccessException, ISerializable
	{
		public string PrivilegeName
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public PrivilegeNotHeldException()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public PrivilegeNotHeldException(string privilege)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public PrivilegeNotHeldException(string privilege, Exception inner)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public override void GetObjectData(SerializationInfo info, StreamingContext context)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	[Flags]
	public enum PropagationFlags
	{
		None = 0,
		NoPropagateInherit = 1,
		InheritOnly = 2
	}
	public abstract class QualifiedAce : KnownAce
	{
		public AceQualifier AceQualifier
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public bool IsCallback
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public int OpaqueLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		internal QualifiedAce()
		{
		}

		public byte[] GetOpaque()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetOpaque(byte[] opaque)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class RawAcl : GenericAcl
	{
		public override int BinaryLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override int Count
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override GenericAce this[int index]
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override byte Revision
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public RawAcl(byte revision, int capacity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public RawAcl(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public override void GetBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void InsertAce(int index, GenericAce ace)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void RemoveAce(int index)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public sealed class RawSecurityDescriptor : GenericSecurityDescriptor
	{
		public override ControlFlags ControlFlags
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public RawAcl DiscretionaryAcl
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override SecurityIdentifier Group
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public override SecurityIdentifier Owner
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public byte ResourceManagerControl
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public RawAcl SystemAcl
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
			}
		}

		public RawSecurityDescriptor(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public RawSecurityDescriptor(ControlFlags flags, SecurityIdentifier owner, SecurityIdentifier group, RawAcl systemAcl, RawAcl discretionaryAcl)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public RawSecurityDescriptor(string sddlForm)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetFlags(ControlFlags flags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
	public enum ResourceType
	{
		Unknown,
		FileObject,
		Service,
		Printer,
		RegistryKey,
		LMShare,
		KernelObject,
		WindowObject,
		DSObject,
		DSObjectAll,
		ProviderDefined,
		WmiGuidObject,
		RegistryWow6432Key
	}
	[Flags]
	public enum SecurityInfos
	{
		Owner = 1,
		Group = 2,
		DiscretionaryAcl = 4,
		SystemAcl = 8
	}
	public sealed class SystemAcl : CommonAcl
	{
		public SystemAcl(bool isContainer, bool isDS, byte revision, int capacity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public SystemAcl(bool isContainer, bool isDS, int capacity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public SystemAcl(bool isContainer, bool isDS, RawAcl rawAcl)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void AddAudit(SecurityIdentifier sid, ObjectAuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public bool RemoveAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public bool RemoveAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public bool RemoveAudit(SecurityIdentifier sid, ObjectAuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void RemoveAuditSpecific(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void RemoveAuditSpecific(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void RemoveAuditSpecific(SecurityIdentifier sid, ObjectAuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetAudit(AuditFlags auditFlags, SecurityIdentifier sid, int accessMask, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, ObjectAceFlags objectFlags, Guid objectType, Guid inheritedObjectType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}

		public void SetAudit(SecurityIdentifier sid, ObjectAuditRule rule)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_AccessControl);
		}
	}
}

BepInEx/core/System.Security.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.Asn1;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.Pkcs.Asn1;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography.Xml;
using System.Security.Permissions;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using Internal.Cryptography;
using Internal.Cryptography.Pal.AnyOS;
using Unity;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: CLSCompliant(true)]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyDescription("System.Security.dll")]
[assembly: AssemblyTitle("System.Security.dll")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyDefaultAlias("System.Security.dll")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class Interop
{
	internal class Kernel32
	{
		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 static extern int FormatMessage(int dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, [Out] StringBuilder lpBuffer, int nSize, IntPtr[] arguments);

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

		internal static string GetMessage(IntPtr moduleHandle, int errorCode)
		{
			StringBuilder stringBuilder = new StringBuilder(256);
			do
			{
				if (TryGetErrorMessage(moduleHandle, errorCode, stringBuilder, out var errorMsg))
				{
					return errorMsg;
				}
				stringBuilder.Capacity *= 4;
			}
			while (stringBuilder.Capacity < 66560);
			return $"Unknown error (0x{errorCode:x})";
		}

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

	internal class Crypt32
	{
		[Flags]
		internal enum CryptProtectDataFlags
		{
			CRYPTPROTECT_UI_FORBIDDEN = 1,
			CRYPTPROTECT_LOCAL_MACHINE = 4,
			CRYPTPROTECT_CRED_SYNC = 8,
			CRYPTPROTECT_AUDIT = 0x10,
			CRYPTPROTECT_NO_RECOVERY = 0x20,
			CRYPTPROTECT_VERIFY_PROTECTION = 0x40
		}

		internal struct DATA_BLOB
		{
			internal uint cbData;

			internal IntPtr pbData;

			internal DATA_BLOB(IntPtr handle, uint size)
			{
				cbData = size;
				pbData = handle;
			}
		}

		[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CryptProtectData([In] ref DATA_BLOB pDataIn, [In] string szDataDescr, [In] ref DATA_BLOB pOptionalEntropy, [In] IntPtr pvReserved, [In] IntPtr pPromptStruct, [In] CryptProtectDataFlags dwFlags, out DATA_BLOB pDataOut);

		[DllImport("crypt32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
		[return: MarshalAs(UnmanagedType.Bool)]
		internal static extern bool CryptUnprotectData([In] ref DATA_BLOB pDataIn, [In] IntPtr ppszDataDescr, [In] ref DATA_BLOB pOptionalEntropy, [In] IntPtr pvReserved, [In] IntPtr pPromptStruct, [In] CryptProtectDataFlags dwFlags, out DATA_BLOB pDataOut);
	}

	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_BAD_NETPATH = 53;

		internal const int ERROR_BAD_NET_NAME = 67;

		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_DIRECTORY = 267;

		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_NETWORK_UNREACHABLE = 1231;

		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 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";
	}
}
namespace System.Security.Permissions
{
	[Serializable]
	public sealed class DataProtectionPermission : CodeAccessPermission, IUnrestrictedPermission
	{
		private const int version = 1;

		private DataProtectionPermissionFlags _flags;

		public DataProtectionPermissionFlags Flags
		{
			get
			{
				return _flags;
			}
			set
			{
				if (((uint)value & 0xFFFFFFF0u) != 0)
				{
					throw new ArgumentException(string.Format(Locale.GetText("Invalid enum {0}"), value), "DataProtectionPermissionFlags");
				}
				_flags = value;
			}
		}

		public DataProtectionPermission(PermissionState state)
		{
			if (PermissionHelper.CheckPermissionState(state, allowUnrestricted: true) == PermissionState.Unrestricted)
			{
				_flags = DataProtectionPermissionFlags.AllFlags;
			}
		}

		public DataProtectionPermission(DataProtectionPermissionFlags flag)
		{
			Flags = flag;
		}

		public bool IsUnrestricted()
		{
			return _flags == DataProtectionPermissionFlags.AllFlags;
		}

		public override IPermission Copy()
		{
			return (IPermission)(object)new DataProtectionPermission(_flags);
		}

		public override IPermission Intersect(IPermission target)
		{
			DataProtectionPermission dataProtectionPermission = Cast(target);
			if (dataProtectionPermission == null)
			{
				return null;
			}
			if (IsUnrestricted() && dataProtectionPermission.IsUnrestricted())
			{
				return (IPermission)(object)new DataProtectionPermission(PermissionState.Unrestricted);
			}
			if (IsUnrestricted())
			{
				return ((CodeAccessPermission)dataProtectionPermission).Copy();
			}
			if (dataProtectionPermission.IsUnrestricted())
			{
				return ((CodeAccessPermission)this).Copy();
			}
			return (IPermission)(object)new DataProtectionPermission(_flags & dataProtectionPermission._flags);
		}

		public override IPermission Union(IPermission target)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected O, but got Unknown
			DataProtectionPermission dataProtectionPermission = Cast(target);
			if (dataProtectionPermission == null)
			{
				return ((CodeAccessPermission)this).Copy();
			}
			if (IsUnrestricted() || dataProtectionPermission.IsUnrestricted())
			{
				return (IPermission)new SecurityPermission(PermissionState.Unrestricted);
			}
			return (IPermission)(object)new DataProtectionPermission(_flags | dataProtectionPermission._flags);
		}

		public override bool IsSubsetOf(IPermission target)
		{
			DataProtectionPermission dataProtectionPermission = Cast(target);
			if (dataProtectionPermission == null)
			{
				return _flags == DataProtectionPermissionFlags.NoFlags;
			}
			if (dataProtectionPermission.IsUnrestricted())
			{
				return true;
			}
			if (IsUnrestricted())
			{
				return false;
			}
			return (_flags & ~dataProtectionPermission._flags) == 0;
		}

		public override void FromXml(SecurityElement securityElement)
		{
			PermissionHelper.CheckSecurityElement(securityElement, "securityElement", 1, 1);
			_flags = (DataProtectionPermissionFlags)Enum.Parse(typeof(DataProtectionPermissionFlags), securityElement.Attribute("Flags"));
		}

		public override SecurityElement ToXml()
		{
			SecurityElement securityElement = PermissionHelper.Element(typeof(DataProtectionPermission), 1);
			securityElement.AddAttribute("Flags", _flags.ToString());
			return securityElement;
		}

		private DataProtectionPermission Cast(IPermission target)
		{
			if (target == null)
			{
				return null;
			}
			DataProtectionPermission obj = target as DataProtectionPermission;
			if (obj == null)
			{
				PermissionHelper.ThrowInvalidPermission(target, typeof(DataProtectionPermission));
			}
			return obj;
		}
	}
	[Serializable]
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
	public sealed class DataProtectionPermissionAttribute : CodeAccessSecurityAttribute
	{
		private DataProtectionPermissionFlags _flags;

		public DataProtectionPermissionFlags Flags
		{
			get
			{
				return _flags;
			}
			set
			{
				if ((value & DataProtectionPermissionFlags.AllFlags) != value)
				{
					throw new ArgumentException(string.Format(Locale.GetText("Invalid flags {0}"), value), "DataProtectionPermissionFlags");
				}
				_flags = value;
			}
		}

		public bool ProtectData
		{
			get
			{
				return (_flags & DataProtectionPermissionFlags.ProtectData) != 0;
			}
			set
			{
				if (value)
				{
					_flags |= DataProtectionPermissionFlags.ProtectData;
				}
				else
				{
					_flags &= ~DataProtectionPermissionFlags.ProtectData;
				}
			}
		}

		public bool UnprotectData
		{
			get
			{
				return (_flags & DataProtectionPermissionFlags.UnprotectData) != 0;
			}
			set
			{
				if (value)
				{
					_flags |= DataProtectionPermissionFlags.UnprotectData;
				}
				else
				{
					_flags &= ~DataProtectionPermissionFlags.UnprotectData;
				}
			}
		}

		public bool ProtectMemory
		{
			get
			{
				return (_flags & DataProtectionPermissionFlags.ProtectMemory) != 0;
			}
			set
			{
				if (value)
				{
					_flags |= DataProtectionPermissionFlags.ProtectMemory;
				}
				else
				{
					_flags &= ~DataProtectionPermissionFlags.ProtectMemory;
				}
			}
		}

		public bool UnprotectMemory
		{
			get
			{
				return (_flags & DataProtectionPermissionFlags.UnprotectMemory) != 0;
			}
			set
			{
				if (value)
				{
					_flags |= DataProtectionPermissionFlags.UnprotectMemory;
				}
				else
				{
					_flags &= ~DataProtectionPermissionFlags.UnprotectMemory;
				}
			}
		}

		public DataProtectionPermissionAttribute(SecurityAction action)
			: base(action)
		{
		}

		public override IPermission CreatePermission()
		{
			DataProtectionPermission dataProtectionPermission = null;
			if (base.Unrestricted)
			{
				return (IPermission)(object)new DataProtectionPermission(PermissionState.Unrestricted);
			}
			return (IPermission)(object)new DataProtectionPermission(_flags);
		}
	}
	[Serializable]
	[Flags]
	public enum DataProtectionPermissionFlags
	{
		NoFlags = 0,
		ProtectData = 1,
		UnprotectData = 2,
		ProtectMemory = 4,
		UnprotectMemory = 8,
		AllFlags = 0xF
	}
	internal sealed class PermissionHelper
	{
		internal static SecurityElement Element(Type type, int version)
		{
			SecurityElement securityElement = new SecurityElement("IPermission");
			securityElement.AddAttribute("class", type.FullName + ", " + type.Assembly.ToString().Replace('"', '\''));
			securityElement.AddAttribute("version", version.ToString());
			return securityElement;
		}

		internal static PermissionState CheckPermissionState(PermissionState state, bool allowUnrestricted)
		{
			switch (state)
			{
			case PermissionState.Unrestricted:
				if (!allowUnrestricted)
				{
					throw new ArgumentException(Locale.GetText("Unrestricted isn't not allowed for identity permissions."), "state");
				}
				break;
			default:
				throw new ArgumentException(string.Format(Locale.GetText("Invalid enum {0}"), state), "state");
			case PermissionState.None:
				break;
			}
			return state;
		}

		internal static int CheckSecurityElement(SecurityElement se, string parameterName, int minimumVersion, int maximumVersion)
		{
			if (se == null)
			{
				throw new ArgumentNullException(parameterName);
			}
			if (se.Attribute("class") == null)
			{
				throw new ArgumentException(Locale.GetText("Missing 'class' attribute."), parameterName);
			}
			int num = minimumVersion;
			string text = se.Attribute("version");
			if (text != null)
			{
				try
				{
					num = int.Parse(text);
				}
				catch (Exception innerException)
				{
					throw new ArgumentException(string.Format(Locale.GetText("Couldn't parse version from '{0}'."), text), parameterName, innerException);
				}
			}
			if (num < minimumVersion || num > maximumVersion)
			{
				throw new ArgumentException(string.Format(Locale.GetText("Unknown version '{0}', expected versions between ['{1}','{2}']."), num, minimumVersion, maximumVersion), parameterName);
			}
			return num;
		}

		internal static bool IsUnrestricted(SecurityElement se)
		{
			string text = se.Attribute("Unrestricted");
			if (text == null)
			{
				return false;
			}
			return string.Compare(text, bool.TrueString, ignoreCase: true, CultureInfo.InvariantCulture) == 0;
		}

		internal static void ThrowInvalidPermission(IPermission target, Type expected)
		{
			throw new ArgumentException(string.Format(Locale.GetText("Invalid permission type '{0}', expected type '{1}'."), target.GetType(), expected), "target");
		}
	}
}
namespace System.Security.Cryptography
{
	public sealed class CryptographicAttributeObject
	{
		private readonly Oid _oid;

		public Oid Oid => new Oid(_oid);

		public AsnEncodedDataCollection Values { get; }

		public CryptographicAttributeObject(Oid oid)
			: this(oid, new AsnEncodedDataCollection())
		{
		}

		public CryptographicAttributeObject(Oid oid, AsnEncodedDataCollection values)
		{
			_oid = new Oid(oid);
			if (values == null)
			{
				Values = new AsnEncodedDataCollection();
				return;
			}
			AsnEncodedDataEnumerator enumerator = values.GetEnumerator();
			while (enumerator.MoveNext())
			{
				AsnEncodedData current = enumerator.Current;
				if (!string.Equals(current.Oid.Value, oid.Value, StringComparison.Ordinal))
				{
					throw new InvalidOperationException(SR.Format("AsnEncodedData element in the collection has wrong Oid value: expected = '{0}', actual = '{1}'.", (object)oid.Value, (object)current.Oid.Value));
				}
			}
			Values = values;
		}
	}
	public sealed class CryptographicAttributeObjectCollection : ICollection, IEnumerable
	{
		private readonly List<CryptographicAttributeObject> _list;

		public CryptographicAttributeObject this[int index] => _list[index];

		public int Count => _list.Count;

		public bool IsSynchronized => false;

		public object SyncRoot => this;

		public CryptographicAttributeObjectCollection()
		{
			_list = new List<CryptographicAttributeObject>();
		}

		public CryptographicAttributeObjectCollection(CryptographicAttributeObject attribute)
		{
			_list = new List<CryptographicAttributeObject>();
			_list.Add(attribute);
		}

		public int Add(AsnEncodedData asnEncodedData)
		{
			if (asnEncodedData == null)
			{
				throw new ArgumentNullException("asnEncodedData");
			}
			return Add(new CryptographicAttributeObject(asnEncodedData.Oid, new AsnEncodedDataCollection(asnEncodedData)));
		}

		public int Add(CryptographicAttributeObject attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			string value = attribute.Oid.Value;
			for (int i = 0; i < _list.Count; i++)
			{
				CryptographicAttributeObject cryptographicAttributeObject = _list[i];
				if (cryptographicAttributeObject.Values == attribute.Values)
				{
					throw new InvalidOperationException("Duplicate items are not allowed in the collection.");
				}
				string value2 = cryptographicAttributeObject.Oid.Value;
				if (string.Equals(value, value2, StringComparison.OrdinalIgnoreCase))
				{
					if (string.Equals(value, "1.2.840.113549.1.9.5", StringComparison.OrdinalIgnoreCase))
					{
						throw new CryptographicException("Cannot add multiple PKCS 9 signing time attributes.");
					}
					AsnEncodedDataEnumerator enumerator = attribute.Values.GetEnumerator();
					while (enumerator.MoveNext())
					{
						AsnEncodedData current = enumerator.Current;
						cryptographicAttributeObject.Values.Add(current);
					}
					return i;
				}
			}
			int count = _list.Count;
			_list.Add(attribute);
			return count;
		}

		internal void AddWithoutMerge(CryptographicAttributeObject attribute)
		{
			_list.Add(attribute);
		}

		public void Remove(CryptographicAttributeObject attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			_list.Remove(attribute);
		}

		public CryptographicAttributeObjectEnumerator GetEnumerator()
		{
			return new CryptographicAttributeObjectEnumerator(this);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return new CryptographicAttributeObjectEnumerator(this);
		}

		void ICollection.CopyTo(Array array, int index)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (array.Rank != 1)
			{
				throw new ArgumentException("Only single dimensional arrays are supported for the requested action.");
			}
			if (index < 0 || index >= array.Length)
			{
				throw new ArgumentOutOfRangeException("index", "Index was out of range. Must be non-negative and less than the size of the collection.");
			}
			if (index > array.Length - Count)
			{
				throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.");
			}
			for (int i = 0; i < Count; i++)
			{
				array.SetValue(this[i], index);
				index++;
			}
		}

		public void CopyTo(CryptographicAttributeObject[] array, int index)
		{
			if (array == null)
			{
				throw new ArgumentNullException("array");
			}
			if (index < 0 || index >= array.Length)
			{
				throw new ArgumentOutOfRangeException("index", "Index was out of range. Must be non-negative and less than the size of the collection.");
			}
			if (index > array.Length - Count)
			{
				throw new ArgumentException("Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.");
			}
			_list.CopyTo(array, index);
		}
	}
	public sealed class CryptographicAttributeObjectEnumerator : IEnumerator
	{
		private readonly CryptographicAttributeObjectCollection _attributes;

		private int _current;

		public CryptographicAttributeObject Current => _attributes[_current];

		object IEnumerator.Current => _attributes[_current];

		internal CryptographicAttributeObjectEnumerator(CryptographicAttributeObjectCollection attributes)
		{
			_attributes = attributes;
			_current = -1;
		}

		public bool MoveNext()
		{
			if (_current >= _attributes.Count - 1)
			{
				return false;
			}
			_current++;
			return true;
		}

		public void Reset()
		{
			_current = -1;
		}

		internal CryptographicAttributeObjectEnumerator()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	public enum DataProtectionScope
	{
		CurrentUser,
		LocalMachine
	}
	public static class ProtectedData
	{
		private static readonly byte[] s_nonEmpty = new byte[1];

		public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope)
		{
			if (userData == null)
			{
				throw new ArgumentNullException("userData");
			}
			return ProtectOrUnprotect(userData, optionalEntropy, scope, protect: true);
		}

		public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope)
		{
			if (encryptedData == null)
			{
				throw new ArgumentNullException("encryptedData");
			}
			return ProtectOrUnprotect(encryptedData, optionalEntropy, scope, protect: false);
		}

		private unsafe static byte[] ProtectOrUnprotect(byte[] inputData, byte[] optionalEntropy, DataProtectionScope scope, bool protect)
		{
			fixed (byte* ptr = ((inputData.Length == 0) ? s_nonEmpty : inputData))
			{
				fixed (byte* ptr2 = optionalEntropy)
				{
					global::Interop.Crypt32.DATA_BLOB pDataIn = new global::Interop.Crypt32.DATA_BLOB((IntPtr)ptr, (uint)inputData.Length);
					global::Interop.Crypt32.DATA_BLOB pOptionalEntropy = default(global::Interop.Crypt32.DATA_BLOB);
					if (optionalEntropy != null)
					{
						pOptionalEntropy = new global::Interop.Crypt32.DATA_BLOB((IntPtr)ptr2, (uint)optionalEntropy.Length);
					}
					global::Interop.Crypt32.CryptProtectDataFlags cryptProtectDataFlags = global::Interop.Crypt32.CryptProtectDataFlags.CRYPTPROTECT_UI_FORBIDDEN;
					if (scope == DataProtectionScope.LocalMachine)
					{
						cryptProtectDataFlags |= global::Interop.Crypt32.CryptProtectDataFlags.CRYPTPROTECT_LOCAL_MACHINE;
					}
					global::Interop.Crypt32.DATA_BLOB pDataOut = default(global::Interop.Crypt32.DATA_BLOB);
					try
					{
						if (!(protect ? global::Interop.Crypt32.CryptProtectData(ref pDataIn, null, ref pOptionalEntropy, IntPtr.Zero, IntPtr.Zero, cryptProtectDataFlags, out pDataOut) : global::Interop.Crypt32.CryptUnprotectData(ref pDataIn, IntPtr.Zero, ref pOptionalEntropy, IntPtr.Zero, IntPtr.Zero, cryptProtectDataFlags, out pDataOut)))
						{
							int lastWin32Error = Marshal.GetLastWin32Error();
							if (protect && ErrorMayBeCausedByUnloadedProfile(lastWin32Error))
							{
								throw new CryptographicException("The data protection operation was unsuccessful. This may have been caused by not having the user profile loaded for the current thread's user context, which may be the case when the thread is impersonating.");
							}
							throw lastWin32Error.ToCryptographicException();
						}
						if (pDataOut.pbData == IntPtr.Zero)
						{
							throw new OutOfMemoryException();
						}
						int cbData = (int)pDataOut.cbData;
						byte[] array = new byte[cbData];
						Marshal.Copy(pDataOut.pbData, array, 0, cbData);
						return array;
					}
					finally
					{
						if (pDataOut.pbData != IntPtr.Zero)
						{
							int cbData2 = (int)pDataOut.cbData;
							byte* ptr3 = (byte*)(void*)pDataOut.pbData;
							for (int i = 0; i < cbData2; i++)
							{
								ptr3[i] = 0;
							}
							Marshal.FreeHGlobal(pDataOut.pbData);
						}
					}
				}
			}
		}

		private static bool ErrorMayBeCausedByUnloadedProfile(int errorCode)
		{
			if (errorCode != -2147024894)
			{
				return errorCode == 2;
			}
			return true;
		}
	}
	public abstract class DataProtector
	{
		private string m_applicationName;

		private string m_primaryPurpose;

		private IEnumerable<string> m_specificPurposes;

		private volatile byte[] m_hashedPurpose;

		protected string ApplicationName => m_applicationName;

		protected virtual bool PrependHashedPurposeToPlaintext => true;

		protected string PrimaryPurpose => m_primaryPurpose;

		protected IEnumerable<string> SpecificPurposes => m_specificPurposes;

		protected DataProtector(string applicationName, string primaryPurpose, string[] specificPurposes)
		{
			if (string.IsNullOrWhiteSpace(applicationName))
			{
				throw new ArgumentException("Invalid application name and/or purpose", "applicationName");
			}
			if (string.IsNullOrWhiteSpace(primaryPurpose))
			{
				throw new ArgumentException("Invalid application name and/or purpose", "primaryPurpose");
			}
			if (specificPurposes != null)
			{
				for (int i = 0; i < specificPurposes.Length; i++)
				{
					if (string.IsNullOrWhiteSpace(specificPurposes[i]))
					{
						throw new ArgumentException("Invalid application name and/or purpose", "specificPurposes");
					}
				}
			}
			m_applicationName = applicationName;
			m_primaryPurpose = primaryPurpose;
			List<string> list = new List<string>();
			if (specificPurposes != null)
			{
				list.AddRange(specificPurposes);
			}
			m_specificPurposes = list;
		}

		protected virtual byte[] GetHashedPurpose()
		{
			if (m_hashedPurpose == null)
			{
				using HashAlgorithm hashAlgorithm = HashAlgorithm.Create("System.Security.Cryptography.Sha256Cng");
				using (BinaryWriter binaryWriter = new BinaryWriter(new CryptoStream(new MemoryStream(), hashAlgorithm, CryptoStreamMode.Write), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)))
				{
					binaryWriter.Write(ApplicationName);
					binaryWriter.Write(PrimaryPurpose);
					foreach (string specificPurpose in SpecificPurposes)
					{
						binaryWriter.Write(specificPurpose);
					}
				}
				m_hashedPurpose = hashAlgorithm.Hash;
			}
			return m_hashedPurpose;
		}

		public abstract bool IsReprotectRequired(byte[] encryptedData);

		public static DataProtector Create(string providerClass, string applicationName, string primaryPurpose, params string[] specificPurposes)
		{
			if (providerClass == null)
			{
				throw new ArgumentNullException("providerClass");
			}
			return (DataProtector)CryptoConfig.CreateFromName(providerClass, applicationName, primaryPurpose, specificPurposes);
		}

		public byte[] Protect(byte[] userData)
		{
			if (userData == null)
			{
				throw new ArgumentNullException("userData");
			}
			if (PrependHashedPurposeToPlaintext)
			{
				byte[] hashedPurpose = GetHashedPurpose();
				byte[] array = new byte[userData.Length + hashedPurpose.Length];
				Array.Copy(hashedPurpose, 0, array, 0, hashedPurpose.Length);
				Array.Copy(userData, 0, array, hashedPurpose.Length, userData.Length);
				userData = array;
			}
			return ProviderProtect(userData);
		}

		protected abstract byte[] ProviderProtect(byte[] userData);

		protected abstract byte[] ProviderUnprotect(byte[] encryptedData);

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public byte[] Unprotect(byte[] encryptedData)
		{
			if (encryptedData == null)
			{
				throw new ArgumentNullException("encryptedData");
			}
			if (PrependHashedPurposeToPlaintext)
			{
				byte[] array = ProviderUnprotect(encryptedData);
				byte[] hashedPurpose = GetHashedPurpose();
				bool flag = array.Length >= hashedPurpose.Length;
				for (int i = 0; i < hashedPurpose.Length; i++)
				{
					if (hashedPurpose[i] != array[i % array.Length])
					{
						flag = false;
					}
				}
				if (!flag)
				{
					throw new CryptographicException("Invalid data protection purpose");
				}
				byte[] array2 = new byte[array.Length - hashedPurpose.Length];
				Array.Copy(array, hashedPurpose.Length, array2, 0, array2.Length);
				return array2;
			}
			return ProviderUnprotect(encryptedData);
		}
	}
	public enum MemoryProtectionScope
	{
		SameProcess,
		CrossProcess,
		SameLogon
	}
	public sealed class ProtectedMemory
	{
		private enum MemoryProtectionImplementation
		{
			Unknown = 0,
			Win32RtlEncryptMemory = 1,
			Win32CryptoProtect = 2,
			Unsupported = int.MinValue
		}

		private const int BlockSize = 16;

		private static MemoryProtectionImplementation impl;

		private ProtectedMemory()
		{
		}

		[MonoTODO("only supported on Windows 2000 SP3 and later")]
		public static void Protect(byte[] userData, MemoryProtectionScope scope)
		{
			if (userData == null)
			{
				throw new ArgumentNullException("userData");
			}
			Check(userData.Length, scope);
			try
			{
				uint cbData = (uint)userData.Length;
				switch (impl)
				{
				case MemoryProtectionImplementation.Win32RtlEncryptMemory:
				{
					int num = RtlEncryptMemory(userData, cbData, (uint)scope);
					if (num < 0)
					{
						throw new CryptographicException(Locale.GetText("Error. NTSTATUS = {0}.", new object[1] { num }));
					}
					break;
				}
				case MemoryProtectionImplementation.Win32CryptoProtect:
					if (!CryptProtectMemory(userData, cbData, (uint)scope))
					{
						throw new CryptographicException(Marshal.GetLastWin32Error());
					}
					break;
				default:
					throw new PlatformNotSupportedException();
				}
			}
			catch
			{
				impl = MemoryProtectionImplementation.Unsupported;
				throw new PlatformNotSupportedException();
			}
		}

		[MonoTODO("only supported on Windows 2000 SP3 and later")]
		public static void Unprotect(byte[] encryptedData, MemoryProtectionScope scope)
		{
			if (encryptedData == null)
			{
				throw new ArgumentNullException("encryptedData");
			}
			Check(encryptedData.Length, scope);
			try
			{
				uint cbData = (uint)encryptedData.Length;
				switch (impl)
				{
				case MemoryProtectionImplementation.Win32RtlEncryptMemory:
				{
					int num = RtlDecryptMemory(encryptedData, cbData, (uint)scope);
					if (num < 0)
					{
						throw new CryptographicException(Locale.GetText("Error. NTSTATUS = {0}.", new object[1] { num }));
					}
					break;
				}
				case MemoryProtectionImplementation.Win32CryptoProtect:
					if (!CryptUnprotectMemory(encryptedData, cbData, (uint)scope))
					{
						throw new CryptographicException(Marshal.GetLastWin32Error());
					}
					break;
				default:
					throw new PlatformNotSupportedException();
				}
			}
			catch
			{
				impl = MemoryProtectionImplementation.Unsupported;
				throw new PlatformNotSupportedException();
			}
		}

		private static void Detect()
		{
			OperatingSystem oSVersion = Environment.OSVersion;
			if (oSVersion.Platform == PlatformID.Win32NT)
			{
				Version version = oSVersion.Version;
				if (version.Major < 5)
				{
					impl = MemoryProtectionImplementation.Unsupported;
				}
				else if (version.Major == 5)
				{
					if (version.Minor < 2)
					{
						impl = MemoryProtectionImplementation.Win32RtlEncryptMemory;
					}
					else
					{
						impl = MemoryProtectionImplementation.Win32CryptoProtect;
					}
				}
				else
				{
					impl = MemoryProtectionImplementation.Win32CryptoProtect;
				}
			}
			else
			{
				impl = MemoryProtectionImplementation.Unsupported;
			}
		}

		private static void Check(int size, MemoryProtectionScope scope)
		{
			if (size % 16 != 0)
			{
				throw new CryptographicException(Locale.GetText("Not a multiple of {0} bytes.", new object[1] { 16 }));
			}
			if (scope < MemoryProtectionScope.SameProcess || scope > MemoryProtectionScope.SameLogon)
			{
				throw new ArgumentException(Locale.GetText("Invalid enum value for '{0}'.", new object[1] { "MemoryProtectionScope" }), "scope");
			}
			switch (impl)
			{
			case MemoryProtectionImplementation.Unknown:
				Detect();
				break;
			case MemoryProtectionImplementation.Unsupported:
				throw new PlatformNotSupportedException();
			}
		}

		[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, EntryPoint = "SystemFunction040", SetLastError = true)]
		[SuppressUnmanagedCodeSecurity]
		private static extern int RtlEncryptMemory(byte[] pData, uint cbData, uint dwFlags);

		[DllImport("advapi32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, EntryPoint = "SystemFunction041", SetLastError = true)]
		[SuppressUnmanagedCodeSecurity]
		private static extern int RtlDecryptMemory(byte[] pData, uint cbData, uint dwFlags);

		[DllImport("crypt32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
		[SuppressUnmanagedCodeSecurity]
		private static extern bool CryptProtectMemory(byte[] pData, uint cbData, uint dwFlags);

		[DllImport("crypt32.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Auto, SetLastError = true)]
		[SuppressUnmanagedCodeSecurity]
		private static extern bool CryptUnprotectMemory(byte[] pData, uint cbData, uint dwFlags);
	}
}
namespace System.Security.Cryptography.Translation
{
	internal class SR
	{
		public const string Cryptography_DataProtector_InvalidAppNameOrPurpose = "Invalid application name and/or purpose";

		public const string Cryptography_DataProtector_InvalidPurpose = "Invalid data protection purpose";

		public const string ArgumentOutOfRange_Index = "Index was out of range.  Must be non-negative and less than the size of the collection.";

		public const string Arg_EmptyOrNullString = "String cannot be empty or null.";

		public const string Cryptography_Partial_Chain = "A certificate chain could not be built to a trusted root authority.";

		public const string Cryptography_Xml_BadWrappedKeySize = "Bad wrapped key size.";

		public const string Cryptography_Xml_CipherValueElementRequired = "A Cipher Data element should have either a CipherValue or a CipherReference element.";

		public const string Cryptography_Xml_CreateHashAlgorithmFailed = "Could not create hash algorithm object.";

		public const string Cryptography_Xml_CreateTransformFailed = "Could not create the XML transformation identified by the URI {0}.";

		public const string Cryptography_Xml_CreatedKeyFailed = "Failed to create signing key.";

		public const string Cryptography_Xml_DigestMethodRequired = "A DigestMethod must be specified on a Reference prior to generating XML.";

		public const string Cryptography_Xml_DigestValueRequired = "A Reference must contain a DigestValue.";

		public const string Cryptography_Xml_EnvelopedSignatureRequiresContext = "An XmlDocument context is required for enveloped transforms.";

		public const string Cryptography_Xml_InvalidElement = "Malformed element {0}.";

		public const string Cryptography_Xml_InvalidEncryptionProperty = "Malformed encryption property element.";

		public const string Cryptography_Xml_InvalidKeySize = "The key size should be a non negative integer.";

		public const string Cryptography_Xml_InvalidReference = "Malformed reference element.";

		public const string Cryptography_Xml_InvalidSignatureLength = "The length of the signature with a MAC should be less than the hash output length.";

		public const string Cryptography_Xml_InvalidSignatureLength2 = "The length in bits of the signature with a MAC should be a multiple of 8.";

		public const string Cryptography_Xml_InvalidX509IssuerSerialNumber = "X509 issuer serial number is invalid.";

		public const string Cryptography_Xml_KeyInfoRequired = "A KeyInfo element is required to check the signature.";

		public const string Cryptography_Xml_KW_BadKeySize = "The length of the encrypted data in Key Wrap is either 32, 40 or 48 bytes.";

		public const string Cryptography_Xml_LoadKeyFailed = "Signing key is not loaded.";

		public const string Cryptography_Xml_MissingAlgorithm = "Symmetric algorithm is not specified.";

		public const string Cryptography_Xml_MissingCipherData = "Cipher data is not specified.";

		public const string Cryptography_Xml_MissingDecryptionKey = "Unable to retrieve the decryption key.";

		public const string Cryptography_Xml_MissingEncryptionKey = "Unable to retrieve the encryption key.";

		public const string Cryptography_Xml_NotSupportedCryptographicTransform = "The specified cryptographic transform is not supported.";

		public const string Cryptography_Xml_ReferenceElementRequired = "At least one Reference element is required.";

		public const string Cryptography_Xml_ReferenceTypeRequired = "The Reference type must be set in an EncryptedReference object.";

		public const string Cryptography_Xml_SelfReferenceRequiresContext = "An XmlDocument context is required to resolve the Reference Uri {0}.";

		public const string Cryptography_Xml_SignatureDescriptionNotCreated = "SignatureDescription could not be created for the signature algorithm supplied.";

		public const string Cryptography_Xml_SignatureMethodKeyMismatch = "The key does not fit the SignatureMethod.";

		public const string Cryptography_Xml_SignatureMethodRequired = "A signature method is required.";

		public const string Cryptography_Xml_SignatureValueRequired = "Signature requires a SignatureValue.";

		public const string Cryptography_Xml_SignedInfoRequired = "Signature requires a SignedInfo.";

		public const string Cryptography_Xml_TransformIncorrectInputType = "The input type was invalid for this transform.";

		public const string Cryptography_Xml_IncorrectObjectType = "Type of input object is invalid.";

		public const string Cryptography_Xml_UnknownTransform = "Unknown transform has been encountered.";

		public const string Cryptography_Xml_UriNotResolved = "Unable to resolve Uri {0}.";

		public const string Cryptography_Xml_UriNotSupported = " The specified Uri is not supported.";

		public const string Cryptography_Xml_UriRequired = "A Uri attribute is required for a CipherReference element.";

		public const string Cryptography_Xml_XrmlMissingContext = "Null Context property encountered.";

		public const string Cryptography_Xml_XrmlMissingIRelDecryptor = "IRelDecryptor is required.";

		public const string Cryptography_Xml_XrmlMissingIssuer = "Issuer node is required.";

		public const string Cryptography_Xml_XrmlMissingLicence = "License node is required.";

		public const string Cryptography_Xml_XrmlUnableToDecryptGrant = "Unable to decrypt grant content.";

		public const string NotSupported_KeyAlgorithm = "The certificate key algorithm is not supported.";

		public const string Log_ActualHashValue = "Actual hash value: {0}";

		public const string Log_BeginCanonicalization = "Beginning canonicalization using \"{0}\" ({1}).";

		public const string Log_BeginSignatureComputation = "Beginning signature computation.";

		public const string Log_BeginSignatureVerification = "Beginning signature verification.";

		public const string Log_BuildX509Chain = "Building and verifying the X509 chain for certificate {0}.";

		public const string Log_CanonicalizationSettings = "Canonicalization transform is using resolver {0} and base URI \"{1}\".";

		public const string Log_CanonicalizedOutput = "Output of canonicalization transform: {0}";

		public const string Log_CertificateChain = "Certificate chain:";

		public const string Log_CheckSignatureFormat = "Checking signature format using format validator \"[{0}] {1}.{2}\".";

		public const string Log_CheckSignedInfo = "Checking signature on SignedInfo with id \"{0}\".";

		public const string Log_FormatValidationSuccessful = "Signature format validation was successful.";

		public const string Log_FormatValidationNotSuccessful = "Signature format validation failed.";

		public const string Log_KeyUsages = "Found key usages \"{0}\" in extension {1} on certificate {2}.";

		public const string Log_NoNamespacesPropagated = "No namespaces are being propagated.";

		public const string Log_PropagatingNamespace = "Propagating namespace {0}=\"{1}\".";

		public const string Log_RawSignatureValue = "Raw signature: {0}";

		public const string Log_ReferenceHash = "Reference {0} hashed with \"{1}\" ({2}) has hash value {3}, expected hash value {4}.";

		public const string Log_RevocationMode = "Revocation mode for chain building: {0}.";

		public const string Log_RevocationFlag = "Revocation flag for chain building: {0}.";

		public const string Log_SigningAsymmetric = "Calculating signature with key {0} using signature description {1}, hash algorithm {2}, and asymmetric signature formatter {3}.";

		public const string Log_SigningHmac = "Calculating signature using keyed hash algorithm {0}.";

		public const string Log_SigningReference = "Hashing reference {0}, Uri \"{1}\", Id \"{2}\", Type \"{3}\" with hash algorithm \"{4}\" ({5}).";

		public const string Log_TransformedReferenceContents = "Transformed reference contents: {0}";

		public const string Log_UnsafeCanonicalizationMethod = "Canonicalization method \"{0}\" is not on the safe list. Safe canonicalization methods are: {1}.";

		public const string Log_UrlTimeout = "URL retrieval timeout for chain building: {0}.";

		public const string Log_VerificationFailed = "Verification failed checking {0}.";

		public const string Log_VerificationFailed_References = "references";

		public const string Log_VerificationFailed_SignedInfo = "SignedInfo";

		public const string Log_VerificationFailed_X509Chain = "X509 chain verification";

		public const string Log_VerificationFailed_X509KeyUsage = "X509 key usage verification";

		public const string Log_VerificationFlag = "Verification flags for chain building: {0}.";

		public const string Log_VerificationTime = "Verification time for chain building: {0}.";

		public const string Log_VerificationWithKeySuccessful = "Verification with key {0} was successful.";

		public const string Log_VerificationWithKeyNotSuccessful = "Verification with key {0} was not successful.";

		public const string Log_VerifyReference = "Processing reference {0}, Uri \"{1}\", Id \"{2}\", Type \"{3}\".";

		public const string Log_VerifySignedInfoAsymmetric = "Verifying SignedInfo using key {0}, signature description {1}, hash algorithm {2}, and asymmetric signature deformatter {3}.";

		public const string Log_VerifySignedInfoHmac = "Verifying SignedInfo using keyed hash algorithm {0}.";

		public const string Log_X509ChainError = "Error building X509 chain: {0}: {1}.";

		public const string Log_XmlContext = "Using context: {0}";

		public const string Log_SignedXmlRecursionLimit = "Signed xml recursion limit hit while trying to decrypt the key. Reference {0} hashed with \"{1}\" and ({2}).";

		public const string Log_UnsafeTransformMethod = "Transform method \"{0}\" is not on the safe list. Safe transform methods are: {1}.";

		public const string Arg_RankMultiDimNotSupported = "Only single dimensional arrays are supported for the requested action.";

		public const string Argument_InvalidOffLen = "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.";

		public const string Argument_InvalidOidValue = "The OID value was invalid.";

		public const string Cryptography_Asn_EnumeratedValueRequiresNonFlagsEnum = "ASN.1 Enumerated values only apply to enum types without the [Flags] attribute.";

		public const string Cryptography_Asn_NamedBitListRequiresFlagsEnum = "Named bit list operations require an enum with the [Flags] attribute.";

		public const string Cryptography_Asn_NamedBitListValueTooBig = "The encoded named bit list value is larger than the value size of the '{0}' enum.";

		public const string Cryptography_Asn_UniversalValueIsFixed = "Tags with TagClass Universal must have the appropriate TagValue value for the data type being read or written.";

		public const string Cryptography_Asn_UnusedBitCountRange = "Unused bit count must be between 0 and 7, inclusive.";

		public const string Cryptography_AsnSerializer_AmbiguousFieldType = "Field '{0}' of type '{1}' has ambiguous type '{2}', an attribute derived from AsnTypeAttribute is required.";

		public const string Cryptography_AsnSerializer_Choice_AllowNullNonNullable = "[Choice].AllowNull=true is not valid because type '{0}' cannot have a null value.";

		public const string Cryptography_AsnSerializer_Choice_ConflictingTagMapping = "The tag ({0} {1}) for field '{2}' on type '{3}' already is associated in this context with field '{4}' on type '{5}'.";

		public const string Cryptography_AsnSerializer_Choice_DefaultValueDisallowed = "Field '{0}' on [Choice] type '{1}' has a default value, which is not permitted.";

		public const string Cryptography_AsnSerializer_Choice_NoChoiceWasMade = "An instance of [Choice] type '{0}' has no non-null fields.";

		public const string Cryptography_AsnSerializer_Choice_NonNullableField = "Field '{0}' on [Choice] type '{1}' can not be assigned a null value.";

		public const string Cryptography_AsnSerializer_Choice_TooManyValues = "Fields '{0}' and '{1}' on type '{2}' are both non-null when only one value is permitted.";

		public const string Cryptography_AsnSerializer_Choice_TypeCycle = "Field '{0}' on [Choice] type '{1}' has introduced a type chain cycle.";

		public const string Cryptography_AsnSerializer_MultipleAsnTypeAttributes = "Field '{0}' on type '{1}' has multiple attributes deriving from '{2}' when at most one is permitted.";

		public const string Cryptography_AsnSerializer_NoJaggedArrays = "Type '{0}' cannot be serialized or deserialized because it is an array of arrays.";

		public const string Cryptography_AsnSerializer_NoMultiDimensionalArrays = "Type '{0}' cannot be serialized or deserialized because it is a multi-dimensional array.";

		public const string Cryptography_AsnSerializer_NoOpenTypes = "Type '{0}' cannot be serialized or deserialized because it is not sealed or has unbound generic parameters.";

		public const string Cryptography_AsnSerializer_Optional_NonNullableField = "Field '{0}' on type '{1}' is declared [OptionalValue], but it can not be assigned a null value.";

		public const string Cryptography_AsnSerializer_PopulateFriendlyNameOnString = "Field '{0}' on type '{1}' has [ObjectIdentifier].PopulateFriendlyName set to true, which is not applicable to a string.  Change the field to '{2}' or set PopulateFriendlyName to false.";

		public const string Cryptography_AsnSerializer_SetValueException = "Unable to set field {0} on type {1}.";

		public const string Cryptography_AsnSerializer_SpecificTagChoice = "Field '{0}' on type '{1}' has specified an implicit tag value via [ExpectedTag] for [Choice] type '{2}'. ExplicitTag must be true, or the [ExpectedTag] attribute removed.";

		public const string Cryptography_AsnSerializer_UnexpectedTypeForAttribute = "Field '{0}' of type '{1}' has an effective type of '{2}' when one of ({3}) was expected.";

		public const string Cryptography_AsnSerializer_UtcTimeTwoDigitYearMaxTooSmall = "Field '{0}' on type '{1}' has a [UtcTime] TwoDigitYearMax value ({2}) smaller than the minimum (99).";

		public const string Cryptography_AsnSerializer_UnhandledType = "Could not determine how to serialize or deserialize type '{0}'.";

		public const string Cryptography_AsnWriter_EncodeUnbalancedStack = "Encode cannot be called while a Sequence or SetOf is still open.";

		public const string Cryptography_AsnWriter_PopWrongTag = "Cannot pop the requested tag as it is not currently in progress.";

		public const string Cryptography_BadHashValue = "The hash value is not correct.";

		public const string Cryptography_BadSignature = "Invalid signature.";

		public const string Cryptography_Cms_CannotDetermineSignatureAlgorithm = "Could not determine signature algorithm for the signer certificate.";

		public const string Cryptography_Cms_IncompleteCertChain = "The certificate chain is incomplete, the self-signed root authority could not be determined.";

		public const string Cryptography_Cms_Invalid_Originator_Identifier_Choice = "Invalid originator identifier choice {0} found in decoded CMS.";

		public const string Cryptography_Cms_Invalid_Subject_Identifier_Type = "The subject identifier type {0} is not valid.";

		public const string Cryptography_Cms_InvalidMessageType = "Invalid cryptographic message type.";

		public const string Cryptography_Cms_InvalidSignerHashForSignatureAlg = "SignerInfo digest algorithm '{0}' is not valid for signature algorithm '{1}'.";

		public const string Cryptography_Cms_Key_Agree_Date_Not_Available = "The Date property is not available for none KID key agree recipient.";

		public const string Cryptography_Cms_MessageNotEncrypted = "The CMS message is not encrypted.";

		public const string Cryptography_Cms_MessageNotSigned = "The CMS message is not signed.";

		public const string Cryptography_Cms_MissingAuthenticatedAttribute = "The cryptographic message does not contain an expected authenticated attribute.";

		public const string Cryptography_Cms_NoCounterCounterSigner = "Only one level of counter-signatures are supported on this platform.";

		public const string Cryptography_Cms_NoRecipients = "The recipients collection is empty. You must specify at least one recipient. This platform does not implement the certificate picker UI.";

		public const string Cryptography_Cms_NoSignerCert = "No signer certificate was provided. This platform does not implement the certificate picker UI.";

		public const string Cryptography_Cms_NoSignerAtIndex = "The signed cryptographic message does not have a signer for the specified signer index.";

		public const string Cryptography_Cms_RecipientNotFound = "The enveloped-data message does not contain the specified recipient.";

		public const string Cryptography_Cms_RecipientType_NotSupported = "The recipient type '{0}' is not supported for encryption or decryption on this platform.";

		public const string Cryptography_Cms_Sign_Empty_Content = "Cannot create CMS signature for empty content.";

		public const string Cryptography_Cms_SignerNotFound = "Cannot find the original signer.";

		public const string Cryptography_Cms_Signing_RequiresPrivateKey = "A certificate with a private key is required.";

		public const string Cryptography_Cms_TrustFailure = "Certificate trust could not be established. The first reported error is: {0}";

		public const string Cryptography_Cms_UnknownAlgorithm = "Unknown algorithm '{0}'.";

		public const string Cryptography_Cms_UnknownKeySpec = "Unable to determine the type of key handle from this keyspec {0}.";

		public const string Cryptography_Cms_WrongKeyUsage = "The certificate is not valid for the requested usage.";

		public const string Cryptography_Pkcs_InvalidSignatureParameters = "Invalid signature paramters.";

		public const string Cryptography_Pkcs9_AttributeMismatch = "The parameter should be a PKCS 9 attribute.";

		public const string Cryptography_Pkcs9_MultipleSigningTimeNotAllowed = "Cannot add multiple PKCS 9 signing time attributes.";

		public const string Cryptography_Pkcs_PssParametersMissing = "PSS parameters were not present.";

		public const string Cryptography_Pkcs_PssParametersHashMismatch = "This platform requires that the PSS hash algorithm ({0}) match the data digest algorithm ({1}).";

		public const string Cryptography_Pkcs_PssParametersMgfHashMismatch = "This platform does not support the MGF hash algorithm ({0}) being different from the signature hash algorithm ({1}).";

		public const string Cryptography_Pkcs_PssParametersMgfNotSupported = "Mask generation function '{0}' is not supported by this platform.";

		public const string Cryptography_Pkcs_PssParametersSaltMismatch = "PSS salt size {0} is not supported by this platform with hash algorithm {1}.";

		public const string Cryptography_TimestampReq_BadNonce = "The response from the timestamping server did not match the request nonce.";

		public const string Cryptography_TimestampReq_BadResponse = "The response from the timestamping server was not understood.";

		public const string Cryptography_TimestampReq_Failure = "The timestamping server did not grant the request. The request status is '{0}' with failure info '{1}'.";

		public const string Cryptography_TimestampReq_NoCertFound = "The timestamping request required the TSA certificate in the response, but it was not found.";

		public const string Cryptography_TimestampReq_UnexpectedCertFound = "The timestamping request required the TSA certificate not be included in the response, but certificates were present.";

		public const string InvalidOperation_DuplicateItemNotAllowed = "Duplicate items are not allowed in the collection.";

		public const string InvalidOperation_WrongOidInAsnCollection = "AsnEncodedData element in the collection has wrong Oid value: expected = '{0}', actual = '{1}'.";

		public const string PlatformNotSupported_CryptographyPkcs = "System.Security.Cryptography.Pkcs is only supported on Windows platforms.";

		public const string Cryptography_Der_Invalid_Encoding = "ASN1 corrupted data.";

		public const string Cryptography_Invalid_IA5String = "The string contains a character not in the 7 bit ASCII character set.";

		public const string Cryptography_UnknownHashAlgorithm = "'{0}' is not a known hash algorithm.";

		public const string Cryptography_WriteEncodedValue_OneValueAtATime = "The input to WriteEncodedValue must represent a single encoded value with no trailing data.";
	}
}
namespace System.Security.Cryptography.X509Certificates
{
	public static class X509Certificate2UI
	{
		[MonoTODO]
		public static void DisplayCertificate(X509Certificate2 certificate)
		{
			DisplayCertificate(certificate, IntPtr.Zero);
		}

		[MonoTODO]
		[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
		public static void DisplayCertificate(X509Certificate2 certificate, IntPtr hwndParent)
		{
			if (certificate == null)
			{
				throw new ArgumentNullException("certificate");
			}
			certificate.GetRawCertData();
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag)
		{
			return SelectFromCollection(certificates, title, message, selectionFlag, IntPtr.Zero);
		}

		[MonoTODO]
		[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
		public static X509Certificate2Collection SelectFromCollection(X509Certificate2Collection certificates, string title, string message, X509SelectionFlag selectionFlag, IntPtr hwndParent)
		{
			if (certificates == null)
			{
				throw new ArgumentNullException("certificates");
			}
			if (selectionFlag < X509SelectionFlag.SingleSelection || selectionFlag > X509SelectionFlag.MultiSelection)
			{
				throw new ArgumentException("selectionFlag");
			}
			throw new NotImplementedException();
		}
	}
	public enum X509SelectionFlag
	{
		SingleSelection,
		MultiSelection
	}
}
namespace System.Security.Cryptography.Xml
{
	public struct X509IssuerSerial
	{
		public string IssuerName { get; set; }

		public string SerialNumber { get; set; }

		internal X509IssuerSerial(string issuerName, string serialNumber)
		{
			this = default(X509IssuerSerial);
			IssuerName = issuerName;
			SerialNumber = serialNumber;
		}
	}
	internal abstract class AncestralNamespaceContextManager
	{
		internal ArrayList _ancestorStack = new ArrayList();

		internal NamespaceFrame GetScopeAt(int i)
		{
			return (NamespaceFrame)_ancestorStack[i];
		}

		internal NamespaceFrame GetCurrentScope()
		{
			return GetScopeAt(_ancestorStack.Count - 1);
		}

		protected XmlAttribute GetNearestRenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth)
		{
			XmlAttribute xmlAttribute = null;
			depth = -1;
			for (int num = _ancestorStack.Count - 1; num >= 0; num--)
			{
				if ((xmlAttribute = GetScopeAt(num).GetRendered(nsPrefix)) != null)
				{
					depth = num;
					return xmlAttribute;
				}
			}
			return null;
		}

		protected XmlAttribute GetNearestUnrenderedNamespaceWithMatchingPrefix(string nsPrefix, out int depth)
		{
			XmlAttribute xmlAttribute = null;
			depth = -1;
			for (int num = _ancestorStack.Count - 1; num >= 0; num--)
			{
				if ((xmlAttribute = GetScopeAt(num).GetUnrendered(nsPrefix)) != null)
				{
					depth = num;
					return xmlAttribute;
				}
			}
			return null;
		}

		internal void EnterElementContext()
		{
			_ancestorStack.Add(new NamespaceFrame());
		}

		internal void ExitElementContext()
		{
			_ancestorStack.RemoveAt(_ancestorStack.Count - 1);
		}

		internal abstract void TrackNamespaceNode(XmlAttribute attr, SortedList nsListToRender, Hashtable nsLocallyDeclared);

		internal abstract void TrackXmlNamespaceNode(XmlAttribute attr, SortedList nsListToRender, SortedList attrListToRender, Hashtable nsLocallyDeclared);

		internal abstract void GetNamespacesToRender(XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared);

		internal void LoadUnrenderedNamespaces(Hashtable nsLocallyDeclared)
		{
			object[] array = new object[nsLocallyDeclared.Count];
			nsLocallyDeclared.Values.CopyTo(array, 0);
			object[] array2 = array;
			foreach (object obj in array2)
			{
				AddUnrendered((XmlAttribute)obj);
			}
		}

		internal void LoadRenderedNamespaces(SortedList nsRenderedList)
		{
			foreach (object key in nsRenderedList.GetKeyList())
			{
				AddRendered((XmlAttribute)key);
			}
		}

		internal void AddRendered(XmlAttribute attr)
		{
			GetCurrentScope().AddRendered(attr);
		}

		internal void AddUnrendered(XmlAttribute attr)
		{
			GetCurrentScope().AddUnrendered(attr);
		}
	}
	internal class AttributeSortOrder : IComparer
	{
		internal AttributeSortOrder()
		{
		}

		public int Compare(object a, object b)
		{
			XmlNode xmlNode = a as XmlNode;
			XmlNode xmlNode2 = b as XmlNode;
			if (xmlNode == null || xmlNode2 == null)
			{
				throw new ArgumentException();
			}
			int num = string.CompareOrdinal(xmlNode.NamespaceURI, xmlNode2.NamespaceURI);
			if (num != 0)
			{
				return num;
			}
			return string.CompareOrdinal(xmlNode.LocalName, xmlNode2.LocalName);
		}
	}
	internal class C14NAncestralNamespaceContextManager : AncestralNamespaceContextManager
	{
		internal C14NAncestralNamespaceContextManager()
		{
		}

		private void GetNamespaceToRender(string nsPrefix, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared)
		{
			foreach (XmlAttribute key in nsListToRender.GetKeyList())
			{
				if (Utils.HasNamespacePrefix(key, nsPrefix))
				{
					return;
				}
			}
			foreach (XmlAttribute key2 in attrListToRender.GetKeyList())
			{
				if (key2.LocalName.Equals(nsPrefix))
				{
					return;
				}
			}
			XmlAttribute xmlAttribute = (XmlAttribute)nsLocallyDeclared[nsPrefix];
			int depth;
			XmlAttribute nearestRenderedNamespaceWithMatchingPrefix = GetNearestRenderedNamespaceWithMatchingPrefix(nsPrefix, out depth);
			if (xmlAttribute != null)
			{
				if (Utils.IsNonRedundantNamespaceDecl(xmlAttribute, nearestRenderedNamespaceWithMatchingPrefix))
				{
					nsLocallyDeclared.Remove(nsPrefix);
					if (Utils.IsXmlNamespaceNode(xmlAttribute))
					{
						attrListToRender.Add(xmlAttribute, null);
					}
					else
					{
						nsListToRender.Add(xmlAttribute, null);
					}
				}
				return;
			}
			int depth2;
			XmlAttribute nearestUnrenderedNamespaceWithMatchingPrefix = GetNearestUnrenderedNamespaceWithMatchingPrefix(nsPrefix, out depth2);
			if (nearestUnrenderedNamespaceWithMatchingPrefix != null && depth2 > depth && Utils.IsNonRedundantNamespaceDecl(nearestUnrenderedNamespaceWithMatchingPrefix, nearestRenderedNamespaceWithMatchingPrefix))
			{
				if (Utils.IsXmlNamespaceNode(nearestUnrenderedNamespaceWithMatchingPrefix))
				{
					attrListToRender.Add(nearestUnrenderedNamespaceWithMatchingPrefix, null);
				}
				else
				{
					nsListToRender.Add(nearestUnrenderedNamespaceWithMatchingPrefix, null);
				}
			}
		}

		internal override void GetNamespacesToRender(XmlElement element, SortedList attrListToRender, SortedList nsListToRender, Hashtable nsLocallyDeclared)
		{
			XmlAttribute xmlAttribute = null;
			object[] array = new object[nsLocallyDeclared.Count];
			nsLocallyDeclared.Values.CopyTo(array, 0);
			object[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				xmlAttribute = (XmlAttribute)array2[i];
				int depth;
				XmlAttribute nearestRenderedNamespaceWithMatchingPrefix = GetNearestRenderedNamespaceWithMatchingPrefix(Utils.GetNamespacePrefix(xmlAttribute), out depth);
				if (Utils.IsNonRedundantNamespaceDecl(xmlAttribute, nearestRenderedNamespaceWithMatchingPrefix))
				{
					nsLocallyDeclared.Remove(Utils.GetNamespacePrefix(xmlAttribute));
					if (Utils.IsXmlNamespaceNode(xmlAttribute))
					{
						attrListToRender.Add(xmlAttribute, null);
					}
					else
					{
						nsListToRender.Add(xmlAttribute, null);
					}
				}
			}
			for (int num = _ancestorStack.Count - 1; num >= 0; num--)
			{
				foreach (XmlAttribute value in GetScopeAt(num).GetUnrendered().Values)
				{
					if (value != null)
					{
						GetNamespaceToRender(Utils.GetNamespacePrefix(value), attrListToRender, nsListToRender, nsLocallyDeclared);
					}
				}
			}
		}

		internal override void TrackNamespaceNode(XmlAttribute attr, SortedList nsListToRender, Hashtable nsLocallyDeclared)
		{
			nsLocallyDeclared.Add(Utils.GetNamespacePrefix(attr), attr);
		}

		internal override void TrackXmlNamespaceNode(XmlAttribute attr, SortedList nsListToRender, SortedList attrListToRender, Hashtable nsLocallyDeclared)
		{
			nsLocallyDeclared.Add(Utils.GetNamespacePrefix(attr), attr);
		}
	}
	internal class CanonicalXml
	{
		private CanonicalXmlDocument _c14nDoc;

		private C14NAncestralNamespaceContextManager _ancMgr;

		internal CanonicalXml(Stream inputStream, bool includeComments, XmlResolver resolver, string strBaseUri)
		{
			if (inputStream == null)
			{
				throw new ArgumentNullException("inputStream");
			}
			_c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: true, includeComments);
			_c14nDoc.XmlResolver = resolver;
			_c14nDoc.Load(Utils.PreProcessStreamInput(inputStream, resolver, strBaseUri));
			_ancMgr = new C14NAncestralNamespaceContextManager();
		}

		internal CanonicalXml(XmlDocument document, XmlResolver resolver)
			: this(document, resolver, includeComments: false)
		{
		}

		internal CanonicalXml(XmlDocument document, XmlResolver resolver, bool includeComments)
		{
			if (document == null)
			{
				throw new ArgumentNullException("document");
			}
			_c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: true, includeComments);
			_c14nDoc.XmlResolver = resolver;
			_c14nDoc.Load(new XmlNodeReader(document));
			_ancMgr = new C14NAncestralNamespaceContextManager();
		}

		internal CanonicalXml(XmlNodeList nodeList, XmlResolver resolver, bool includeComments)
		{
			if (nodeList == null)
			{
				throw new ArgumentNullException("nodeList");
			}
			XmlDocument ownerDocument = Utils.GetOwnerDocument(nodeList);
			if (ownerDocument == null)
			{
				throw new ArgumentException("nodeList");
			}
			_c14nDoc = new CanonicalXmlDocument(defaultNodeSetInclusionState: false, includeComments);
			_c14nDoc.XmlResolver = resolver;
			_c14nDoc.Load(new XmlNodeReader(ownerDocument));
			_ancMgr = new C14NAncestralNamespaceContextManager();
			MarkInclusionStateForNodes(nodeList, ownerDocument, _c14nDoc);
		}

		private static void MarkNodeAsIncluded(XmlNode node)
		{
			if (node is ICanonicalizableNode)
			{
				((ICanonicalizableNode)node).IsInNodeSet = true;
			}
		}

		private static void MarkInclusionStateForNodes(XmlNodeList nodeList, XmlDocument inputRoot, XmlDocument root)
		{
			CanonicalXmlNodeList canonicalXmlNodeList = new CanonicalXmlNodeList();
			CanonicalXmlNodeList canonicalXmlNodeList2 = new CanonicalXmlNodeList();
			canonicalXmlNodeList.Add(inputRoot);
			canonicalXmlNodeList2.Add(root);
			int num = 0;
			do
			{
				XmlNode xmlNode = canonicalXmlNodeList[num];
				XmlNode? xmlNode2 = canonicalXmlNodeList2[num];
				XmlNodeList childNodes = xmlNode.ChildNodes;
				XmlNodeList childNodes2 = xmlNode2.ChildNodes;
				for (int i = 0; i < childNodes.Count; i++)
				{
					canonicalXmlNodeList.Add(childNodes[i]);
					canonicalXmlNodeList2.Add(childNodes2[i]);
					if (Utils.NodeInList(childNodes[i], nodeList))
					{
						MarkNodeAsIncluded(childNodes2[i]);
					}
					XmlAttributeCollection attributes = childNodes[i].Attributes;
					if (attributes == null)
					{
						continue;
					}
					for (int j = 0; j < attributes.Count; j++)
					{
						if (Utils.NodeInList(attributes[j], nodeList))
						{
							MarkNodeAsIncluded(childNodes2[i].Attributes.Item(j));
						}
					}
				}
				num++;
			}
			while (num < canonicalXmlNodeList.Count);
		}

		internal byte[] GetBytes()
		{
			StringBuilder stringBuilder = new StringBuilder();
			_c14nDoc.Write(stringBuilder, DocPosition.BeforeRootElement, _ancMgr);
			return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(stringBuilder.ToString());
		}

		internal byte[] GetDigestedBytes(HashAlgorithm hash)
		{
			_c14nDoc.WriteHash(hash, DocPosition.BeforeRootElement, _ancMgr);
			hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0);
			byte[] result = (byte[])hash.Hash.Clone();
			hash.Initialize();
			return result;
		}
	}
	internal class CanonicalXmlAttribute : XmlAttribute, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlAttribute(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState)
			: base(prefix, localName, namespaceURI, doc)
		{
			IsInNodeSet = defaultNodeSetInclusionState;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			strBuilder.Append(" " + Name + "=\"");
			strBuilder.Append(Utils.EscapeAttributeValue(Value));
			strBuilder.Append("\"");
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
			byte[] bytes = uTF8Encoding.GetBytes(" " + Name + "=\"");
			hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
			bytes = uTF8Encoding.GetBytes(Utils.EscapeAttributeValue(Value));
			hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
			bytes = uTF8Encoding.GetBytes("\"");
			hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
		}
	}
	internal class CanonicalXmlCDataSection : XmlCDataSection, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlCDataSection(string data, XmlDocument doc, bool defaultNodeSetInclusionState)
			: base(data, doc)
		{
			_isInNodeSet = defaultNodeSetInclusionState;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet)
			{
				strBuilder.Append(Utils.EscapeCData(Data));
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet)
			{
				byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Utils.EscapeCData(Data));
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
			}
		}
	}
	internal class CanonicalXmlComment : XmlComment, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		private bool _includeComments;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public bool IncludeComments => _includeComments;

		public CanonicalXmlComment(string comment, XmlDocument doc, bool defaultNodeSetInclusionState, bool includeComments)
			: base(comment, doc)
		{
			_isInNodeSet = defaultNodeSetInclusionState;
			_includeComments = includeComments;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet && IncludeComments)
			{
				if (docPos == DocPosition.AfterRootElement)
				{
					strBuilder.Append('\n');
				}
				strBuilder.Append("<!--");
				strBuilder.Append(Value);
				strBuilder.Append("-->");
				if (docPos == DocPosition.BeforeRootElement)
				{
					strBuilder.Append('\n');
				}
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet && IncludeComments)
			{
				UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
				byte[] bytes = uTF8Encoding.GetBytes("(char) 10");
				if (docPos == DocPosition.AfterRootElement)
				{
					hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				}
				bytes = uTF8Encoding.GetBytes("<!--");
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				bytes = uTF8Encoding.GetBytes(Value);
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				bytes = uTF8Encoding.GetBytes("-->");
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				if (docPos == DocPosition.BeforeRootElement)
				{
					bytes = uTF8Encoding.GetBytes("(char) 10");
					hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				}
			}
		}
	}
	internal class CanonicalXmlDocument : XmlDocument, ICanonicalizableNode
	{
		private bool _defaultNodeSetInclusionState;

		private bool _includeComments;

		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlDocument(bool defaultNodeSetInclusionState, bool includeComments)
		{
			base.PreserveWhitespace = true;
			_includeComments = includeComments;
			_isInNodeSet = (_defaultNodeSetInclusionState = defaultNodeSetInclusionState);
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			docPos = DocPosition.BeforeRootElement;
			foreach (XmlNode childNode in ChildNodes)
			{
				if (childNode.NodeType == XmlNodeType.Element)
				{
					CanonicalizationDispatcher.Write(childNode, strBuilder, DocPosition.InRootElement, anc);
					docPos = DocPosition.AfterRootElement;
				}
				else
				{
					CanonicalizationDispatcher.Write(childNode, strBuilder, docPos, anc);
				}
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			docPos = DocPosition.BeforeRootElement;
			foreach (XmlNode childNode in ChildNodes)
			{
				if (childNode.NodeType == XmlNodeType.Element)
				{
					CanonicalizationDispatcher.WriteHash(childNode, hash, DocPosition.InRootElement, anc);
					docPos = DocPosition.AfterRootElement;
				}
				else
				{
					CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc);
				}
			}
		}

		public override XmlElement CreateElement(string prefix, string localName, string namespaceURI)
		{
			return new CanonicalXmlElement(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState);
		}

		public override XmlAttribute CreateAttribute(string prefix, string localName, string namespaceURI)
		{
			return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState);
		}

		protected override XmlAttribute CreateDefaultAttribute(string prefix, string localName, string namespaceURI)
		{
			return new CanonicalXmlAttribute(prefix, localName, namespaceURI, this, _defaultNodeSetInclusionState);
		}

		public override XmlText CreateTextNode(string text)
		{
			return new CanonicalXmlText(text, this, _defaultNodeSetInclusionState);
		}

		public override XmlWhitespace CreateWhitespace(string prefix)
		{
			return new CanonicalXmlWhitespace(prefix, this, _defaultNodeSetInclusionState);
		}

		public override XmlSignificantWhitespace CreateSignificantWhitespace(string text)
		{
			return new CanonicalXmlSignificantWhitespace(text, this, _defaultNodeSetInclusionState);
		}

		public override XmlProcessingInstruction CreateProcessingInstruction(string target, string data)
		{
			return new CanonicalXmlProcessingInstruction(target, data, this, _defaultNodeSetInclusionState);
		}

		public override XmlComment CreateComment(string data)
		{
			return new CanonicalXmlComment(data, this, _defaultNodeSetInclusionState, _includeComments);
		}

		public override XmlEntityReference CreateEntityReference(string name)
		{
			return new CanonicalXmlEntityReference(name, this, _defaultNodeSetInclusionState);
		}

		public override XmlCDataSection CreateCDataSection(string data)
		{
			return new CanonicalXmlCDataSection(data, this, _defaultNodeSetInclusionState);
		}
	}
	internal class CanonicalXmlElement : XmlElement, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlElement(string prefix, string localName, string namespaceURI, XmlDocument doc, bool defaultNodeSetInclusionState)
			: base(prefix, localName, namespaceURI, doc)
		{
			_isInNodeSet = defaultNodeSetInclusionState;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			Hashtable nsLocallyDeclared = new Hashtable();
			SortedList sortedList = new SortedList(new NamespaceSortOrder());
			SortedList sortedList2 = new SortedList(new AttributeSortOrder());
			XmlAttributeCollection attributes = Attributes;
			if (attributes != null)
			{
				foreach (XmlAttribute item in attributes)
				{
					if (((CanonicalXmlAttribute)item).IsInNodeSet || Utils.IsNamespaceNode(item) || Utils.IsXmlNamespaceNode(item))
					{
						if (Utils.IsNamespaceNode(item))
						{
							anc.TrackNamespaceNode(item, sortedList, nsLocallyDeclared);
						}
						else if (Utils.IsXmlNamespaceNode(item))
						{
							anc.TrackXmlNamespaceNode(item, sortedList, sortedList2, nsLocallyDeclared);
						}
						else if (IsInNodeSet)
						{
							sortedList2.Add(item, null);
						}
					}
				}
			}
			if (!Utils.IsCommittedNamespace(this, Prefix, NamespaceURI))
			{
				string name = ((Prefix.Length > 0) ? ("xmlns:" + Prefix) : "xmlns");
				XmlAttribute xmlAttribute2 = OwnerDocument.CreateAttribute(name);
				xmlAttribute2.Value = NamespaceURI;
				anc.TrackNamespaceNode(xmlAttribute2, sortedList, nsLocallyDeclared);
			}
			if (IsInNodeSet)
			{
				anc.GetNamespacesToRender(this, sortedList2, sortedList, nsLocallyDeclared);
				strBuilder.Append("<" + Name);
				foreach (object key in sortedList.GetKeyList())
				{
					(key as CanonicalXmlAttribute).Write(strBuilder, docPos, anc);
				}
				foreach (object key2 in sortedList2.GetKeyList())
				{
					(key2 as CanonicalXmlAttribute).Write(strBuilder, docPos, anc);
				}
				strBuilder.Append(">");
			}
			anc.EnterElementContext();
			anc.LoadUnrenderedNamespaces(nsLocallyDeclared);
			anc.LoadRenderedNamespaces(sortedList);
			foreach (XmlNode childNode in ChildNodes)
			{
				CanonicalizationDispatcher.Write(childNode, strBuilder, docPos, anc);
			}
			anc.ExitElementContext();
			if (IsInNodeSet)
			{
				strBuilder.Append("</" + Name + ">");
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			Hashtable nsLocallyDeclared = new Hashtable();
			SortedList sortedList = new SortedList(new NamespaceSortOrder());
			SortedList sortedList2 = new SortedList(new AttributeSortOrder());
			UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
			XmlAttributeCollection attributes = Attributes;
			if (attributes != null)
			{
				foreach (XmlAttribute item in attributes)
				{
					if (((CanonicalXmlAttribute)item).IsInNodeSet || Utils.IsNamespaceNode(item) || Utils.IsXmlNamespaceNode(item))
					{
						if (Utils.IsNamespaceNode(item))
						{
							anc.TrackNamespaceNode(item, sortedList, nsLocallyDeclared);
						}
						else if (Utils.IsXmlNamespaceNode(item))
						{
							anc.TrackXmlNamespaceNode(item, sortedList, sortedList2, nsLocallyDeclared);
						}
						else if (IsInNodeSet)
						{
							sortedList2.Add(item, null);
						}
					}
				}
			}
			if (!Utils.IsCommittedNamespace(this, Prefix, NamespaceURI))
			{
				string name = ((Prefix.Length > 0) ? ("xmlns:" + Prefix) : "xmlns");
				XmlAttribute xmlAttribute2 = OwnerDocument.CreateAttribute(name);
				xmlAttribute2.Value = NamespaceURI;
				anc.TrackNamespaceNode(xmlAttribute2, sortedList, nsLocallyDeclared);
			}
			if (IsInNodeSet)
			{
				anc.GetNamespacesToRender(this, sortedList2, sortedList, nsLocallyDeclared);
				byte[] bytes = uTF8Encoding.GetBytes("<" + Name);
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				foreach (object key in sortedList.GetKeyList())
				{
					(key as CanonicalXmlAttribute).WriteHash(hash, docPos, anc);
				}
				foreach (object key2 in sortedList2.GetKeyList())
				{
					(key2 as CanonicalXmlAttribute).WriteHash(hash, docPos, anc);
				}
				bytes = uTF8Encoding.GetBytes(">");
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
			}
			anc.EnterElementContext();
			anc.LoadUnrenderedNamespaces(nsLocallyDeclared);
			anc.LoadRenderedNamespaces(sortedList);
			foreach (XmlNode childNode in ChildNodes)
			{
				CanonicalizationDispatcher.WriteHash(childNode, hash, docPos, anc);
			}
			anc.ExitElementContext();
			if (IsInNodeSet)
			{
				byte[] bytes = uTF8Encoding.GetBytes("</" + Name + ">");
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
			}
		}
	}
	internal class CanonicalXmlEntityReference : XmlEntityReference, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlEntityReference(string name, XmlDocument doc, bool defaultNodeSetInclusionState)
			: base(name, doc)
		{
			_isInNodeSet = defaultNodeSetInclusionState;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet)
			{
				CanonicalizationDispatcher.WriteGenericNode(this, strBuilder, docPos, anc);
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet)
			{
				CanonicalizationDispatcher.WriteHashGenericNode(this, hash, docPos, anc);
			}
		}
	}
	internal class CanonicalXmlNodeList : XmlNodeList, IList, ICollection, IEnumerable
	{
		private ArrayList _nodeArray;

		public override int Count => _nodeArray.Count;

		public bool IsFixedSize => _nodeArray.IsFixedSize;

		public bool IsReadOnly => _nodeArray.IsReadOnly;

		object IList.this[int index]
		{
			get
			{
				return _nodeArray[index];
			}
			set
			{
				if (!(value is XmlNode))
				{
					throw new ArgumentException("Type of input object is invalid.", "value");
				}
				_nodeArray[index] = value;
			}
		}

		public object SyncRoot => _nodeArray.SyncRoot;

		public bool IsSynchronized => _nodeArray.IsSynchronized;

		internal CanonicalXmlNodeList()
		{
			_nodeArray = new ArrayList();
		}

		public override XmlNode Item(int index)
		{
			return (XmlNode)_nodeArray[index];
		}

		public override IEnumerator GetEnumerator()
		{
			return _nodeArray.GetEnumerator();
		}

		public int Add(object value)
		{
			if (!(value is XmlNode))
			{
				throw new ArgumentException("Type of input object is invalid.", "node");
			}
			return _nodeArray.Add(value);
		}

		public void Clear()
		{
			_nodeArray.Clear();
		}

		public bool Contains(object value)
		{
			return _nodeArray.Contains(value);
		}

		public int IndexOf(object value)
		{
			return _nodeArray.IndexOf(value);
		}

		public void Insert(int index, object value)
		{
			if (!(value is XmlNode))
			{
				throw new ArgumentException("Type of input object is invalid.", "value");
			}
			_nodeArray.Insert(index, value);
		}

		public void Remove(object value)
		{
			_nodeArray.Remove(value);
		}

		public void RemoveAt(int index)
		{
			_nodeArray.RemoveAt(index);
		}

		public void CopyTo(Array array, int index)
		{
			_nodeArray.CopyTo(array, index);
		}
	}
	internal class CanonicalXmlProcessingInstruction : XmlProcessingInstruction, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlProcessingInstruction(string target, string data, XmlDocument doc, bool defaultNodeSetInclusionState)
			: base(target, data, doc)
		{
			_isInNodeSet = defaultNodeSetInclusionState;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet)
			{
				if (docPos == DocPosition.AfterRootElement)
				{
					strBuilder.Append('\n');
				}
				strBuilder.Append("<?");
				strBuilder.Append(Name);
				if (Value != null && Value.Length > 0)
				{
					strBuilder.Append(" " + Value);
				}
				strBuilder.Append("?>");
				if (docPos == DocPosition.BeforeRootElement)
				{
					strBuilder.Append('\n');
				}
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet)
			{
				UTF8Encoding uTF8Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
				byte[] bytes;
				if (docPos == DocPosition.AfterRootElement)
				{
					bytes = uTF8Encoding.GetBytes("(char) 10");
					hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				}
				bytes = uTF8Encoding.GetBytes("<?");
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				bytes = uTF8Encoding.GetBytes(Name);
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				if (Value != null && Value.Length > 0)
				{
					bytes = uTF8Encoding.GetBytes(" " + Value);
					hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				}
				bytes = uTF8Encoding.GetBytes("?>");
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				if (docPos == DocPosition.BeforeRootElement)
				{
					bytes = uTF8Encoding.GetBytes("(char) 10");
					hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
				}
			}
		}
	}
	internal class CanonicalXmlSignificantWhitespace : XmlSignificantWhitespace, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlSignificantWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState)
			: base(strData, doc)
		{
			_isInNodeSet = defaultNodeSetInclusionState;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet && docPos == DocPosition.InRootElement)
			{
				strBuilder.Append(Utils.EscapeWhitespaceData(Value));
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet && docPos == DocPosition.InRootElement)
			{
				byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Utils.EscapeWhitespaceData(Value));
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
			}
		}
	}
	internal class CanonicalXmlText : XmlText, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlText(string strData, XmlDocument doc, bool defaultNodeSetInclusionState)
			: base(strData, doc)
		{
			_isInNodeSet = defaultNodeSetInclusionState;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet)
			{
				strBuilder.Append(Utils.EscapeTextData(Value));
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet)
			{
				byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Utils.EscapeTextData(Value));
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
			}
		}
	}
	internal class CanonicalXmlWhitespace : XmlWhitespace, ICanonicalizableNode
	{
		private bool _isInNodeSet;

		public bool IsInNodeSet
		{
			get
			{
				return _isInNodeSet;
			}
			set
			{
				_isInNodeSet = value;
			}
		}

		public CanonicalXmlWhitespace(string strData, XmlDocument doc, bool defaultNodeSetInclusionState)
			: base(strData, doc)
		{
			_isInNodeSet = defaultNodeSetInclusionState;
		}

		public void Write(StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet && docPos == DocPosition.InRootElement)
			{
				strBuilder.Append(Utils.EscapeWhitespaceData(Value));
			}
		}

		public void WriteHash(HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (IsInNodeSet && docPos == DocPosition.InRootElement)
			{
				byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Utils.EscapeWhitespaceData(Value));
				hash.TransformBlock(bytes, 0, bytes.Length, bytes, 0);
			}
		}
	}
	internal class CanonicalizationDispatcher
	{
		private CanonicalizationDispatcher()
		{
		}

		public static void Write(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (node is ICanonicalizableNode)
			{
				((ICanonicalizableNode)node).Write(strBuilder, docPos, anc);
			}
			else
			{
				WriteGenericNode(node, strBuilder, docPos, anc);
			}
		}

		public static void WriteGenericNode(XmlNode node, StringBuilder strBuilder, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (node == null)
			{
				throw new ArgumentNullException("node");
			}
			foreach (XmlNode childNode in node.ChildNodes)
			{
				Write(childNode, strBuilder, docPos, anc);
			}
		}

		public static void WriteHash(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (node is ICanonicalizableNode)
			{
				((ICanonicalizableNode)node).WriteHash(hash, docPos, anc);
			}
			else
			{
				WriteHashGenericNode(node, hash, docPos, anc);
			}
		}

		public static void WriteHashGenericNode(XmlNode node, HashAlgorithm hash, DocPosition docPos, AncestralNamespaceContextManager anc)
		{
			if (node == null)
			{
				throw new ArgumentNullException("node");
			}
			foreach (XmlNode childNode in node.ChildNodes)
			{
				WriteHash(childNode, hash, docPos, anc);
			}
		}
	}
	internal enum CertUsageType
	{
		Verification,
		Decryption
	}
	public sealed class CipherData
	{
		private XmlElement _cachedXml;

		private CipherReference _cipherReference;

		private byte[] _cipherValue;

		private bool CacheValid => _cachedXml != null;

		public CipherReference CipherReference
		{
			get
			{
				return _cipherReference;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				if (CipherValue != null)
				{
					throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element.");
				}
				_cipherReference = value;
				_cachedXml = null;
			}
		}

		public byte[] CipherValue
		{
			get
			{
				return _cipherValue;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				if (CipherReference != null)
				{
					throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element.");
				}
				_cipherValue = (byte[])value.Clone();
				_cachedXml = null;
			}
		}

		public CipherData()
		{
		}

		public CipherData(byte[] cipherValue)
		{
			CipherValue = cipherValue;
		}

		public CipherData(CipherReference cipherReference)
		{
			CipherReference = cipherReference;
		}

		public XmlElement GetXml()
		{
			if (CacheValid)
			{
				return _cachedXml;
			}
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.PreserveWhitespace = true;
			return GetXml(xmlDocument);
		}

		internal XmlElement GetXml(XmlDocument document)
		{
			XmlElement xmlElement = document.CreateElement("CipherData", "http://www.w3.org/2001/04/xmlenc#");
			if (CipherValue != null)
			{
				XmlElement xmlElement2 = document.CreateElement("CipherValue", "http://www.w3.org/2001/04/xmlenc#");
				xmlElement2.AppendChild(document.CreateTextNode(Convert.ToBase64String(CipherValue)));
				xmlElement.AppendChild(xmlElement2);
			}
			else
			{
				if (CipherReference == null)
				{
					throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element.");
				}
				xmlElement.AppendChild(CipherReference.GetXml(document));
			}
			return xmlElement;
		}

		public void LoadXml(XmlElement value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable);
			xmlNamespaceManager.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#");
			XmlNode xmlNode = value.SelectSingleNode("enc:CipherValue", xmlNamespaceManager);
			XmlNode xmlNode2 = value.SelectSingleNode("enc:CipherReference", xmlNamespaceManager);
			if (xmlNode != null)
			{
				if (xmlNode2 != null)
				{
					throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element.");
				}
				_cipherValue = Convert.FromBase64String(Utils.DiscardWhiteSpaces(xmlNode.InnerText));
			}
			else
			{
				if (xmlNode2 == null)
				{
					throw new CryptographicException("A Cipher Data element should have either a CipherValue or a CipherReference element.");
				}
				_cipherReference = new CipherReference();
				_cipherReference.LoadXml((XmlElement)xmlNode2);
			}
			_cachedXml = value;
		}
	}
	public sealed class CipherReference : EncryptedReference
	{
		private byte[] _cipherValue;

		internal byte[] CipherValue
		{
			get
			{
				if (!base.CacheValid)
				{
					return null;
				}
				return _cipherValue;
			}
			set
			{
				_cipherValue = value;
			}
		}

		public CipherReference()
		{
			base.ReferenceType = "CipherReference";
		}

		public CipherReference(string uri)
			: base(uri)
		{
			base.ReferenceType = "CipherReference";
		}

		public CipherReference(string uri, TransformChain transformChain)
			: base(uri, transformChain)
		{
			base.ReferenceType = "CipherReference";
		}

		public override XmlElement GetXml()
		{
			if (base.CacheValid)
			{
				return _cachedXml;
			}
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.PreserveWhitespace = true;
			return GetXml(xmlDocument);
		}

		internal new XmlElement GetXml(XmlDocument document)
		{
			if (base.ReferenceType == null)
			{
				throw new CryptographicException("The Reference type must be set in an EncryptedReference object.");
			}
			XmlElement xmlElement = document.CreateElement(base.ReferenceType, "http://www.w3.org/2001/04/xmlenc#");
			if (!string.IsNullOrEmpty(base.Uri))
			{
				xmlElement.SetAttribute("URI", base.Uri);
			}
			if (base.TransformChain.Count > 0)
			{
				xmlElement.AppendChild(base.TransformChain.GetXml(document, "http://www.w3.org/2001/04/xmlenc#"));
			}
			return xmlElement;
		}

		public override void LoadXml(XmlElement value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			base.ReferenceType = value.LocalName;
			string attribute = Utils.GetAttribute(value, "URI", "http://www.w3.org/2001/04/xmlenc#");
			base.Uri = attribute ?? throw new CryptographicException("A Uri attribute is required for a CipherReference element.");
			XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(value.OwnerDocument.NameTable);
			xmlNamespaceManager.AddNamespace("enc", "http://www.w3.org/2001/04/xmlenc#");
			XmlNode xmlNode = value.SelectSingleNode("enc:Transforms", xmlNamespaceManager);
			if (xmlNode != null)
			{
				base.TransformChain.LoadXml(xmlNode as XmlElement);
			}
			_cachedXml = value;
		}
	}
	internal static class CryptoHelpers
	{
		private static readonly char[] _invalidChars = new char[5] { ',', '`', '[', '*', '&' };

		public static object CreateFromKnownName(string name)
		{
			return name switch
			{
				"http://www.w3.org/TR/2001/REC-xml-c14n-20010315" => new XmlDsigC14NTransform(), 
				"http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments" => new XmlDsigC14NWithCommentsTransform(), 
				"http://www.w3.org/2001/10/xml-exc-c14n#" => new XmlDsigExcC14NTransform(), 
				"http://www.w3.org/2001/10/xml-exc-c14n#WithComments" => new XmlDsigExcC14NWithCommentsTransform(), 
				"http://www.w3.org/2000/09/xmldsig#base64" => new XmlDsigBase64Transform(), 
				"http://www.w3.org/TR/1999/REC-xpath-19991116" => new XmlDsigXPathTransform(), 
				"http://www.w3.org/TR/1999/REC-xslt-19991116" => new XmlDsigXsltTransform(), 
				"http://www.w3.org/2000/09/xmldsig#enveloped-signature" => new XmlDsigEnvelopedSignatureTransform(), 
				"http://www.w3.org/2002/07/decrypt#XML" => new XmlDecryptionTransform(), 
				"urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform" => new XmlLicenseTransform(), 
				"http://www.w3.org/2000/09/xmldsig# X509Data" => new KeyInfoX509Data(), 
				"http://www.w3.org/2000/09/xmldsig# KeyName" => new KeyInfoName(), 
				"http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue" => new DSAKeyValue(), 
				"http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue" => new RSAKeyValue(), 
				"http://www.w3.org/2000/09/xmldsig# RetrievalMethod" => new KeyInfoRetrievalMethod(), 
				"http://www.w3.org/2001/04/xmlenc# EncryptedKey" => new KeyInfoEncryptedKey(), 
				"http://www.w3.org/2000/09/xmldsig#dsa-sha1" => new DSASignatureDescription(), 
				"System.Security.Cryptography.DSASignatureDescription" => new DSASignatureDescription(), 
				"http://www.w3.org/2000/09/xmldsig#rsa-sha1" => new RSAPKCS1SHA1SignatureDescription(), 
				"System.Security.Cryptography.RSASignatureDescription" => new RSAPKCS1SHA1SignatureDescription(), 
				"http://www.w3.org/2001/04/xmldsig-more#rsa-sha256" => new RSAPKCS1SHA256SignatureDescription(), 
				"http://www.w3.org/2001/04/xmldsig-more#rsa-sha384" => new RSAPKCS1SHA384SignatureDescription(), 
				"http://www.w3.org/2001/04/xmldsig-more#rsa-sha512" => new RSAPKCS1SHA512SignatureDescription(), 
				"http://www.w3.org/2000/09/xmldsig#sha1" => SHA1.Create(), 
				"MD5" => MD5.Create(), 
				"http://www.w3.org/2001/04/xmldsig-more#hmac-md5" => new HMACMD5(), 
				"http://www.w3.org/2001/04/xmlenc#tripledes-cbc" => TripleDES.Create(), 
				_ => null, 
			};
		}

		public static T CreateFromName<T>(string name) where T : class
		{
			if (name == null || name.IndexOfAny(_invalidChars) >= 0)
			{
				return null;
			}
			try
			{
				return (CreateFromKnownName(name) ?? CryptoConfig.CreateFromName(name)) as T;
			}
			catch (Exception)
			{
				return null;
			}
		}
	}
	[Serializable]
	public class CryptoSignedXmlRecursionException : XmlException
	{
		public CryptoSignedXmlRecursionException()
		{
		}

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

		public CryptoSignedXmlRecursionException(string message, Exception inner)
			: base(message, inner)
		{
		}

		protected CryptoSignedXmlRecursionException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	public class DSAKeyValue : KeyInfoClause
	{
		private DSA _key;

		private const string KeyValueElementName = "KeyValue";

		private const string DSAKeyValueElementName = "DSAKeyValue";

		private const string PElementName = "P";

		private const string QElementName = "Q";

		private const string GElementName = "G";

		private const string JElementName = "J";

		private const string YElementName = "Y";

		private const string SeedElementName = "Seed";

		private const string PgenCounterElementName = "PgenCounter";

		public DSA Key
		{
			get
			{
				return _key;
			}
			set
			{
				_key = value;
			}
		}

		public DSAKeyValue()
		{
			_key = DSA.Create();
		}

		public DSAKeyValue(DSA key)
		{
			_key = key;
		}

		public override XmlElement GetXml()
		{
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.PreserveWhitespace = true;
			return GetXml(xmlDocument);
		}

		internal override XmlElement GetXml(XmlDocument xmlDocument)
		{
			DSAParameters dSAParameters = _key.ExportParameters(includePrivateParameters: false);
			XmlElement xmlElement = xmlDocument.CreateElement("KeyValue", "http://www.w3.org/2000/09/xmldsig#");
			XmlElement xmlElement2 = xmlDocument.CreateElement("DSAKeyValue", "http://www.w3.org/2000/09/xmldsig#");
			XmlElement xmlElement3 = xmlDocument.CreateElement("P", "http://www.w3.org/2000/09/xmldsig#");
			xmlElement3.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.P)));
			xmlElement2.AppendChild(xmlElement3);
			XmlElement xmlElement4 = xmlDocument.CreateElement("Q", "http://www.w3.org/2000/09/xmldsig#");
			xmlElement4.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Q)));
			xmlElement2.AppendChild(xmlElement4);
			XmlElement xmlElement5 = xmlDocument.CreateElement("G", "http://www.w3.org/2000/09/xmldsig#");
			xmlElement5.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.G)));
			xmlElement2.AppendChild(xmlElement5);
			XmlElement xmlElement6 = xmlDocument.CreateElement("Y", "http://www.w3.org/2000/09/xmldsig#");
			xmlElement6.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Y)));
			xmlElement2.AppendChild(xmlElement6);
			if (dSAParameters.J != null)
			{
				XmlElement xmlElement7 = xmlDocument.CreateElement("J", "http://www.w3.org/2000/09/xmldsig#");
				xmlElement7.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.J)));
				xmlElement2.AppendChild(xmlElement7);
			}
			if (dSAParameters.Seed != null)
			{
				XmlElement xmlElement8 = xmlDocument.CreateElement("Seed", "http://www.w3.org/2000/09/xmldsig#");
				xmlElement8.AppendChild(xmlDocument.CreateTextNode(Convert.ToBase64String(dSAParameters.Seed)));
				xmlElement2.AppendChild(xmlElement8);
				XmlElement xmlElement

BepInEx/core/System.Security.Principal.Windows.dll

Decompiled 2 weeks 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.Runtime.Serialization;
using System.Security;
using System.Security.Claims;
using System.Security.Permissions;
using FxResources.System.Security.Principal.Windows;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyDefaultAlias("System.Security.Principal.Windows")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("NotSupported", "True")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("System.Security.Principal.Windows")]
[assembly: AssemblyFileVersion("4.700.19.56404")]
[assembly: AssemblyInformationalVersion("3.1.0+0f7f38c4fd323b26da10cce95f857f77f0f09b48")]
[assembly: AssemblyProduct("Microsoft® .NET Core")]
[assembly: AssemblyTitle("System.Security.Principal.Windows")]
[assembly: CLSCompliant(true)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.1.3.0")]
[module: UnverifiableCode]
namespace FxResources.System.Security.Principal.Windows
{
	internal static class SR
	{
	}
}
namespace Microsoft.Win32.SafeHandles
{
	public sealed class SafeAccessTokenHandle : SafeHandle
	{
		public static SafeAccessTokenHandle InvalidHandle
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public override bool IsInvalid
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public SafeAccessTokenHandle(IntPtr handle)
			: base((IntPtr)0, ownsHandle: false)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		protected override bool ReleaseHandle()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}
	}
}
namespace System
{
	internal static class SR
	{
		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string Arg_EmptyCollection => GetResourceString("Arg_EmptyCollection");

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

		internal static string Argument_ImpersonateUser => GetResourceString("Argument_ImpersonateUser");

		internal static string Argument_ImproperType => GetResourceString("Argument_ImproperType");

		internal static string Argument_InvalidImpersonationToken => GetResourceString("Argument_InvalidImpersonationToken");

		internal static string Argument_InvalidValue => GetResourceString("Argument_InvalidValue");

		internal static string Argument_TokenZero => GetResourceString("Argument_TokenZero");

		internal static string ArgumentOutOfRange_ArrayTooSmall => GetResourceString("ArgumentOutOfRange_ArrayTooSmall");

		internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum");

		internal static string Argument_StringZeroLength => GetResourceString("Argument_StringZeroLength");

		internal static string IdentityReference_AccountNameTooLong => GetResourceString("IdentityReference_AccountNameTooLong");

		internal static string IdentityReference_CannotCreateLogonIdsSid => GetResourceString("IdentityReference_CannotCreateLogonIdsSid");

		internal static string IdentityReference_DomainNameTooLong => GetResourceString("IdentityReference_DomainNameTooLong");

		internal static string IdentityReference_DomainSidRequired => GetResourceString("IdentityReference_DomainSidRequired");

		internal static string IdentityReference_IdentifierAuthorityTooLarge => GetResourceString("IdentityReference_IdentifierAuthorityTooLarge");

		internal static string IdentityReference_IdentityNotMapped => GetResourceString("IdentityReference_IdentityNotMapped");

		internal static string IdentityReference_InvalidNumberOfSubauthorities => GetResourceString("IdentityReference_InvalidNumberOfSubauthorities");

		internal static string IdentityReference_InvalidSidRevision => GetResourceString("IdentityReference_InvalidSidRevision");

		internal static string IdentityReference_MustBeIdentityReference => GetResourceString("IdentityReference_MustBeIdentityReference");

		internal static string IdentityReference_NotAWindowsDomain => GetResourceString("IdentityReference_NotAWindowsDomain");

		internal static string PlatformNotSupported_Principal => GetResourceString("PlatformNotSupported_Principal");

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

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

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Security.Principal
{
	public sealed class IdentityNotMappedException : SystemException
	{
		public IdentityReferenceCollection UnmappedIdentities
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public IdentityNotMappedException()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public IdentityNotMappedException(string message)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public IdentityNotMappedException(string message, Exception inner)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}
	}
	public abstract class IdentityReference
	{
		public abstract string Value { get; }

		internal IdentityReference()
		{
		}

		public abstract override bool Equals(object o);

		public abstract override int GetHashCode();

		public abstract bool IsValidTargetType(Type targetType);

		public static bool operator ==(IdentityReference left, IdentityReference right)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static bool operator !=(IdentityReference left, IdentityReference right)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public abstract override string ToString();

		public abstract IdentityReference Translate(Type targetType);
	}
	public class IdentityReferenceCollection : ICollection<IdentityReference>, IEnumerable<IdentityReference>, IEnumerable
	{
		public int Count
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public IdentityReference this[int index]
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
			set
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		bool ICollection<IdentityReference>.IsReadOnly
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public IdentityReferenceCollection()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public IdentityReferenceCollection(int capacity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public void Add(IdentityReference identity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public void Clear()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public bool Contains(IdentityReference identity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public void CopyTo(IdentityReference[] array, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public IEnumerator<IdentityReference> GetEnumerator()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public bool Remove(IdentityReference identity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public IdentityReferenceCollection Translate(Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public IdentityReferenceCollection Translate(Type targetType, bool forceSuccess)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}
	}
	public sealed class NTAccount : IdentityReference
	{
		public override string Value
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public NTAccount(string name)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public NTAccount(string domainName, string accountName)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override bool Equals(object o)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override int GetHashCode()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override bool IsValidTargetType(Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static bool operator ==(NTAccount left, NTAccount right)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static bool operator !=(NTAccount left, NTAccount right)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override string ToString()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override IdentityReference Translate(Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}
	}
	public sealed class SecurityIdentifier : IdentityReference, IComparable<SecurityIdentifier>
	{
		public static readonly int MaxBinaryLength;

		public static readonly int MinBinaryLength;

		public SecurityIdentifier AccountDomainSid
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public int BinaryLength
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public override string Value
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public SecurityIdentifier(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public SecurityIdentifier(IntPtr binaryForm)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public SecurityIdentifier(WellKnownSidType sidType, SecurityIdentifier domainSid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public SecurityIdentifier(string sddlForm)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public int CompareTo(SecurityIdentifier sid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override bool Equals(object o)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public bool Equals(SecurityIdentifier sid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public void GetBinaryForm(byte[] binaryForm, int offset)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override int GetHashCode()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public bool IsAccountSid()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public bool IsEqualDomainSid(SecurityIdentifier sid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override bool IsValidTargetType(Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public bool IsWellKnown(WellKnownSidType type)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static bool operator ==(SecurityIdentifier left, SecurityIdentifier right)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static bool operator !=(SecurityIdentifier left, SecurityIdentifier right)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override string ToString()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override IdentityReference Translate(Type targetType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}
	}
	[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
	}
	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,
		[EditorBrowsable(EditorBrowsableState.Never)]
		[Obsolete("This member has been depcreated and is only maintained for backwards compatability. WellKnownSidType values greater than MaxDefined may be defined in future releases.")]
		MaxDefined = 60,
		WinBuiltinTerminalServerLicenseServersSid = 60,
		WinBuiltinDCOMUsersSid = 61,
		WinBuiltinIUsersSid = 62,
		WinIUserSid = 63,
		WinBuiltinCryptoOperatorsSid = 64,
		WinUntrustedLabelSid = 65,
		WinLowLabelSid = 66,
		WinMediumLabelSid = 67,
		WinHighLabelSid = 68,
		WinSystemLabelSid = 69,
		WinWriteRestrictedCodeSid = 70,
		WinCreatorOwnerRightsSid = 71,
		WinCacheablePrincipalsGroupSid = 72,
		WinNonCacheablePrincipalsGroupSid = 73,
		WinEnterpriseReadonlyControllersSid = 74,
		WinAccountReadonlyControllersSid = 75,
		WinBuiltinEventLogReadersGroup = 76,
		WinNewEnterpriseReadonlyControllersSid = 77,
		WinBuiltinCertSvcDComAccessGroup = 78,
		WinMediumPlusLabelSid = 79,
		WinLocalLogonSid = 80,
		WinConsoleLogonSid = 81,
		WinThisOrganizationCertificateSid = 82,
		WinApplicationPackageAuthoritySid = 83,
		WinBuiltinAnyPackageSid = 84,
		WinCapabilityInternetClientSid = 85,
		WinCapabilityInternetClientServerSid = 86,
		WinCapabilityPrivateNetworkClientServerSid = 87,
		WinCapabilityPicturesLibrarySid = 88,
		WinCapabilityVideosLibrarySid = 89,
		WinCapabilityMusicLibrarySid = 90,
		WinCapabilityDocumentsLibrarySid = 91,
		WinCapabilitySharedUserCertificatesSid = 92,
		WinCapabilityEnterpriseAuthenticationSid = 93,
		WinCapabilityRemovableStorageSid = 94
	}
	[ComVisible(true)]
	public enum WindowsAccountType
	{
		Normal,
		Guest,
		System,
		Anonymous
	}
	public enum WindowsBuiltInRole
	{
		Administrator = 544,
		User,
		Guest,
		PowerUser,
		AccountOperator,
		SystemOperator,
		PrintOperator,
		BackupOperator,
		Replicator
	}
	public class WindowsIdentity : ClaimsIdentity, IDisposable, IDeserializationCallback, ISerializable
	{
		public new const string DefaultIssuer = "AD AUTHORITY";

		public SafeAccessTokenHandle AccessToken
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public sealed override string AuthenticationType
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public override IEnumerable<Claim> Claims
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public virtual IEnumerable<Claim> DeviceClaims
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public IdentityReferenceCollection Groups
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public TokenImpersonationLevel ImpersonationLevel
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public virtual bool IsAnonymous
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public override bool IsAuthenticated
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public virtual bool IsGuest
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public virtual bool IsSystem
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public override string Name
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public SecurityIdentifier Owner
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public virtual IntPtr Token
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public SecurityIdentifier User
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public virtual IEnumerable<Claim> UserClaims
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public WindowsIdentity(IntPtr userToken)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public WindowsIdentity(IntPtr userToken, string type)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public WindowsIdentity(IntPtr userToken, string type, WindowsAccountType acctType, bool isAuthenticated)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public WindowsIdentity(SerializationInfo info, StreamingContext context)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		protected WindowsIdentity(WindowsIdentity identity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public WindowsIdentity(string sUserPrincipalName)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override ClaimsIdentity Clone()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public void Dispose()
		{
		}

		protected virtual void Dispose(bool disposing)
		{
		}

		public static WindowsIdentity GetAnonymous()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static WindowsIdentity GetCurrent()
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static WindowsIdentity GetCurrent(bool ifImpersonating)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		void IDeserializationCallback.OnDeserialization(object sender)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}
	}
	public class WindowsPrincipal : ClaimsPrincipal
	{
		public virtual IEnumerable<Claim> DeviceClaims
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public override IIdentity Identity
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public virtual IEnumerable<Claim> UserClaims
		{
			get
			{
				throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
			}
		}

		public WindowsPrincipal(WindowsIdentity ntIdentity)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public virtual bool IsInRole(int rid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public virtual bool IsInRole(SecurityIdentifier sid)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public virtual bool IsInRole(WindowsBuiltInRole role)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}

		public override bool IsInRole(string role)
		{
			throw new PlatformNotSupportedException(System.SR.PlatformNotSupported_Principal);
		}
	}
}

BepInEx/core/System.ServiceModel.Internals.dll

Decompiled 2 weeks ago
#define DEBUG
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.Diagnostics;
using System.Runtime.Interop;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Principal;
using System.ServiceModel.Internals;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.XPath;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: Guid("a9b8c4b5-b4a9-4800-8268-e8ec3b93d9ac")]
[assembly: InternalsVisibleTo("System.Activities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.Activities.Statements, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.Activities.Extended, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.Runtime.DurableInstancing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.Runtime.Serialization.Xaml, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.Runtime.Xaml, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.ServiceModel.Activation, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.ServiceMoniker40, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.ServiceModel.Activities, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.Channels, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.LocalChannel, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.Discovery, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.Routing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.Web, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("Microsoft.ServiceModel.Web.Test, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.WorkflowServices, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.WasHosting, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Xaml.Hosting, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("XamlBuildTask, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("SMSvcHost, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("SMDiagnostics, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("Microsoft.Transactions.Bridge, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("System.IO.Log, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("System.Runtime.Serialization, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.IdentityModel, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.IdentityModel.Selectors, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.IdentityModel.Services, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("WorkflowManagementService, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.Activities.DurableInstancing, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("XsdBuildTask, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.ServiceModel.Friend, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("Microsoft.CDF.Test.Persistence, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("CDF.CIT.Scenarios.Common, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("WireTool, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("WsatTest, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("WCF.CIT.ChannelModel, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: InternalsVisibleTo("System.Activities.Core.Presentation, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("System.Activities.Presentation, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("Microsoft.Activities.Build, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: InternalsVisibleTo("Microsoft.VisualStudio.ServiceModel, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
[assembly: AssemblyTitle("System.ServiceModel.Internals.dll")]
[assembly: AssemblyDescription("Contains share code for some System.ServiceModel libraries")]
[assembly: AssemblyDefaultAlias("System.ServiceModel.dll")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyKeyFile("../ecma.pub")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: SecurityCritical(SecurityCriticalScope.Explicit)]
[assembly: InternalsVisibleTo("System.Runtime.DurableInstancing, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.ServiceModel.Web, PublicKey=00000000000000000400000000000000")]
[assembly: ComVisible(false)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
internal static class AssemblyRef
{
	internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string EcmaPublicKey = "b77a5c561934e089";

	public const string FrameworkPublicKeyFull = "00000000000000000400000000000000";

	public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000";

	public const string MicrosoftPublicKey = "b03f5f7f11d50a3a";

	public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class SR
{
	internal static string GetString(string name, params object[] args)
	{
		return GetString(CultureInfo.InvariantCulture, name, args);
	}

	internal static string GetString(CultureInfo culture, string name, params object[] args)
	{
		return string.Format(culture, name, args);
	}

	internal static string GetString(string name)
	{
		return name;
	}

	internal static string GetString(CultureInfo culture, string name)
	{
		return name;
	}

	internal static string Format(string resourceFormat, params object[] args)
	{
		if (args != null)
		{
			return string.Format(CultureInfo.InvariantCulture, resourceFormat, args);
		}
		return resourceFormat;
	}

	internal static string Format(string resourceFormat, object p1)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1);
	}

	internal static string Format(string resourceFormat, object p1, object p2)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2);
	}

	internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2)
	{
		return string.Format(ci, resourceFormat, p1, p2);
	}

	internal static string Format(string resourceFormat, object p1, object p2, object p3)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3);
	}

	internal static string GetResourceString(string str)
	{
		return str;
	}
}
namespace System.ServiceModel.Internals
{
	internal static class LocalAppContextSwitches
	{
		public static readonly bool IncludeNullExceptionMessageInETWTrace;
	}
}
namespace System.Runtime
{
	internal abstract class ActionItem
	{
		[SecurityCritical]
		private static class CallbackHelper
		{
			private static Action<object> invokeWithoutContextCallback;

			private static ContextCallback onContextAppliedCallback;

			public static Action<object> InvokeWithoutContextCallback
			{
				get
				{
					if (invokeWithoutContextCallback == null)
					{
						invokeWithoutContextCallback = InvokeWithoutContext;
					}
					return invokeWithoutContextCallback;
				}
			}

			public static ContextCallback OnContextAppliedCallback
			{
				get
				{
					if (onContextAppliedCallback == null)
					{
						onContextAppliedCallback = OnContextApplied;
					}
					return onContextAppliedCallback;
				}
			}

			private static void InvokeWithoutContext(object state)
			{
				((ActionItem)state).Invoke();
				((ActionItem)state).isScheduled = false;
			}

			private static void OnContextApplied(object o)
			{
				((ActionItem)o).Invoke();
				((ActionItem)o).isScheduled = false;
			}
		}

		private class DefaultActionItem : ActionItem
		{
			[SecurityCritical]
			private Action<object> callback;

			[SecurityCritical]
			private object state;

			private bool flowLegacyActivityId;

			private Guid activityId;

			private EventTraceActivity eventTraceActivity;

			[SecuritySafeCritical]
			public DefaultActionItem(Action<object> callback, object state, bool isLowPriority)
			{
				base.LowPriority = isLowPriority;
				this.callback = callback;
				this.state = state;
				if (WaitCallbackActionItem.ShouldUseActivity)
				{
					flowLegacyActivityId = true;
					activityId = DiagnosticTraceBase.ActivityId;
				}
				if (Fx.Trace.IsEnd2EndActivityTracingEnabled)
				{
					eventTraceActivity = EventTraceActivity.GetFromThreadOrCreate();
					if (TraceCore.ActionItemScheduledIsEnabled(Fx.Trace))
					{
						TraceCore.ActionItemScheduled(Fx.Trace, eventTraceActivity);
					}
				}
			}

			[SecurityCritical]
			protected override void Invoke()
			{
				if (flowLegacyActivityId || Fx.Trace.IsEnd2EndActivityTracingEnabled)
				{
					TraceAndInvoke();
				}
				else
				{
					callback(state);
				}
			}

			[SecurityCritical]
			private void TraceAndInvoke()
			{
				if (flowLegacyActivityId)
				{
					Guid guid = DiagnosticTraceBase.ActivityId;
					try
					{
						DiagnosticTraceBase.ActivityId = activityId;
						callback(state);
						return;
					}
					finally
					{
						DiagnosticTraceBase.ActivityId = guid;
					}
				}
				Guid empty = Guid.Empty;
				bool flag = false;
				try
				{
					if (eventTraceActivity != null)
					{
						empty = Trace.CorrelationManager.ActivityId;
						flag = true;
						Trace.CorrelationManager.ActivityId = eventTraceActivity.ActivityId;
						if (TraceCore.ActionItemCallbackInvokedIsEnabled(Fx.Trace))
						{
							TraceCore.ActionItemCallbackInvoked(Fx.Trace, eventTraceActivity);
						}
					}
					callback(state);
				}
				finally
				{
					if (flag)
					{
						Trace.CorrelationManager.ActivityId = empty;
					}
				}
			}
		}

		private bool isScheduled;

		private bool lowPriority;

		public bool LowPriority
		{
			get
			{
				return lowPriority;
			}
			protected set
			{
				lowPriority = value;
			}
		}

		public static void Schedule(Action<object> callback, object state)
		{
			Schedule(callback, state, lowPriority: false);
		}

		[SecuritySafeCritical]
		public static void Schedule(Action<object> callback, object state, bool lowPriority)
		{
			if (PartialTrustHelpers.ShouldFlowSecurityContext || WaitCallbackActionItem.ShouldUseActivity || Fx.Trace.IsEnd2EndActivityTracingEnabled)
			{
				new DefaultActionItem(callback, state, lowPriority).Schedule();
			}
			else
			{
				ScheduleCallback(callback, state, lowPriority);
			}
		}

		[SecurityCritical]
		protected abstract void Invoke();

		[SecurityCritical]
		protected void Schedule()
		{
			if (isScheduled)
			{
				throw Fx.Exception.AsError(new InvalidOperationException("Action Item Is Already Scheduled"));
			}
			isScheduled = true;
			ScheduleCallback(CallbackHelper.InvokeWithoutContextCallback);
		}

		[SecurityCritical]
		protected void ScheduleWithoutContext()
		{
			if (isScheduled)
			{
				throw Fx.Exception.AsError(new InvalidOperationException("Action Item Is Already Scheduled"));
			}
			isScheduled = true;
			ScheduleCallback(CallbackHelper.InvokeWithoutContextCallback);
		}

		[SecurityCritical]
		private static void ScheduleCallback(Action<object> callback, object state, bool lowPriority)
		{
			if (lowPriority)
			{
				IOThreadScheduler.ScheduleCallbackLowPriNoFlow(callback, state);
			}
			else
			{
				IOThreadScheduler.ScheduleCallbackNoFlow(callback, state);
			}
		}

		[SecurityCritical]
		private void ScheduleCallback(Action<object> callback)
		{
			ScheduleCallback(callback, this, lowPriority);
		}
	}
	internal static class AssertHelper
	{
		internal static void FireAssert(string message)
		{
			try
			{
			}
			finally
			{
				Debug.Assert(condition: false, message);
			}
		}
	}
	internal enum AsyncCompletionResult
	{
		Queued,
		Completed
	}
	internal abstract class AsyncEventArgs : IAsyncEventArgs
	{
		private enum OperationState
		{
			Created,
			PendingCompletion,
			CompletedSynchronously,
			CompletedAsynchronously
		}

		private OperationState state;

		private object asyncState;

		private AsyncEventArgsCallback callback;

		private Exception exception;

		public Exception Exception => exception;

		public object AsyncState => asyncState;

		private OperationState State
		{
			set
			{
				switch (value)
				{
				case OperationState.PendingCompletion:
					if (state == OperationState.PendingCompletion)
					{
						throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncEventArgsCompletionPending(GetType())));
					}
					break;
				case OperationState.CompletedSynchronously:
				case OperationState.CompletedAsynchronously:
					if (state != OperationState.PendingCompletion)
					{
						throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncEventArgsCompletedTwice(GetType())));
					}
					break;
				}
				state = value;
			}
		}

		public void Complete(bool completedSynchronously)
		{
			Complete(completedSynchronously, null);
		}

		public virtual void Complete(bool completedSynchronously, Exception exception)
		{
			this.exception = exception;
			if (completedSynchronously)
			{
				State = OperationState.CompletedSynchronously;
				return;
			}
			State = OperationState.CompletedAsynchronously;
			callback(this);
		}

		protected void SetAsyncState(AsyncEventArgsCallback callback, object state)
		{
			if (callback == null)
			{
				throw Fx.Exception.ArgumentNull("callback");
			}
			State = OperationState.PendingCompletion;
			asyncState = state;
			this.callback = callback;
		}
	}
	internal class AsyncEventArgs<TArgument> : AsyncEventArgs
	{
		public TArgument Arguments { get; private set; }

		public virtual void Set(AsyncEventArgsCallback callback, TArgument arguments, object state)
		{
			SetAsyncState(callback, state);
			Arguments = arguments;
		}
	}
	internal class AsyncEventArgs<TArgument, TResult> : AsyncEventArgs<TArgument>
	{
		public TResult Result { get; set; }
	}
	internal delegate void AsyncEventArgsCallback(IAsyncEventArgs eventArgs);
	internal abstract class AsyncResult : IAsyncResult
	{
		protected delegate bool AsyncCompletion(IAsyncResult result);

		private static AsyncCallback asyncCompletionWrapperCallback;

		private AsyncCallback callback;

		private bool completedSynchronously;

		private bool endCalled;

		private Exception exception;

		private bool isCompleted;

		private AsyncCompletion nextAsyncCompletion;

		private object state;

		private Action beforePrepareAsyncCompletionAction;

		private Func<IAsyncResult, bool> checkSyncValidationFunc;

		private ManualResetEvent manualResetEvent;

		private object thisLock;

		public object AsyncState => state;

		public WaitHandle AsyncWaitHandle
		{
			get
			{
				if (manualResetEvent != null)
				{
					return manualResetEvent;
				}
				lock (ThisLock)
				{
					if (manualResetEvent == null)
					{
						manualResetEvent = new ManualResetEvent(isCompleted);
					}
				}
				return manualResetEvent;
			}
		}

		public bool CompletedSynchronously => completedSynchronously;

		public bool HasCallback => callback != null;

		public bool IsCompleted => isCompleted;

		protected Action<AsyncResult, Exception> OnCompleting { get; set; }

		private object ThisLock => thisLock;

		protected Action<AsyncCallback, IAsyncResult> VirtualCallback { get; set; }

		protected AsyncResult(AsyncCallback callback, object state)
		{
			this.callback = callback;
			this.state = state;
			thisLock = new object();
		}

		protected void Complete(bool completedSynchronously)
		{
			if (isCompleted)
			{
				throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultCompletedTwice(GetType())));
			}
			this.completedSynchronously = completedSynchronously;
			if (OnCompleting != null)
			{
				try
				{
					OnCompleting(this, exception);
				}
				catch (Exception ex)
				{
					if (Fx.IsFatal(ex))
					{
						throw;
					}
					exception = ex;
				}
			}
			if (completedSynchronously)
			{
				isCompleted = true;
			}
			else
			{
				lock (ThisLock)
				{
					isCompleted = true;
					if (manualResetEvent != null)
					{
						manualResetEvent.Set();
					}
				}
			}
			if (callback == null)
			{
				return;
			}
			try
			{
				if (VirtualCallback != null)
				{
					VirtualCallback(callback, this);
				}
				else
				{
					callback(this);
				}
			}
			catch (Exception innerException)
			{
				if (Fx.IsFatal(innerException))
				{
					throw;
				}
				throw Fx.Exception.AsError(new CallbackException("Async Callback Threw Exception", innerException));
			}
		}

		protected void Complete(bool completedSynchronously, Exception exception)
		{
			this.exception = exception;
			Complete(completedSynchronously);
		}

		private static void AsyncCompletionWrapperCallback(IAsyncResult result)
		{
			if (result == null)
			{
				throw Fx.Exception.AsError(new InvalidOperationException("Invalid Null Async Result"));
			}
			if (result.CompletedSynchronously)
			{
				return;
			}
			AsyncResult asyncResult = (AsyncResult)result.AsyncState;
			if (!asyncResult.OnContinueAsyncCompletion(result))
			{
				return;
			}
			AsyncCompletion nextCompletion = asyncResult.GetNextCompletion();
			if (nextCompletion == null)
			{
				ThrowInvalidAsyncResult(result);
			}
			bool flag = false;
			Exception ex = null;
			try
			{
				flag = nextCompletion(result);
			}
			catch (Exception ex2)
			{
				if (Fx.IsFatal(ex2))
				{
					throw;
				}
				flag = true;
				ex = ex2;
			}
			if (flag)
			{
				asyncResult.Complete(completedSynchronously: false, ex);
			}
		}

		protected virtual bool OnContinueAsyncCompletion(IAsyncResult result)
		{
			return true;
		}

		protected void SetBeforePrepareAsyncCompletionAction(Action beforePrepareAsyncCompletionAction)
		{
			this.beforePrepareAsyncCompletionAction = beforePrepareAsyncCompletionAction;
		}

		protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> checkSyncValidationFunc)
		{
			this.checkSyncValidationFunc = checkSyncValidationFunc;
		}

		protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback)
		{
			if (beforePrepareAsyncCompletionAction != null)
			{
				beforePrepareAsyncCompletionAction();
			}
			nextAsyncCompletion = callback;
			if (asyncCompletionWrapperCallback == null)
			{
				asyncCompletionWrapperCallback = Fx.ThunkCallback(AsyncCompletionWrapperCallback);
			}
			return asyncCompletionWrapperCallback;
		}

		protected bool CheckSyncContinue(IAsyncResult result)
		{
			AsyncCompletion asyncCompletion;
			return TryContinueHelper(result, out asyncCompletion);
		}

		protected bool SyncContinue(IAsyncResult result)
		{
			if (TryContinueHelper(result, out var asyncCompletion))
			{
				return asyncCompletion(result);
			}
			return false;
		}

		private bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback)
		{
			if (result == null)
			{
				throw Fx.Exception.AsError(new InvalidOperationException("Invalid Null Async Result"));
			}
			callback = null;
			if (checkSyncValidationFunc != null)
			{
				if (!checkSyncValidationFunc(result))
				{
					return false;
				}
			}
			else if (!result.CompletedSynchronously)
			{
				return false;
			}
			callback = GetNextCompletion();
			if (callback == null)
			{
				ThrowInvalidAsyncResult("Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion).");
			}
			return true;
		}

		private AsyncCompletion GetNextCompletion()
		{
			AsyncCompletion result = nextAsyncCompletion;
			nextAsyncCompletion = null;
			return result;
		}

		protected static void ThrowInvalidAsyncResult(IAsyncResult result)
		{
			throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidAsyncResultImplementation(result.GetType())));
		}

		protected static void ThrowInvalidAsyncResult(string debugText)
		{
			string message = "Invalid Async Result Implementation Generic";
			throw Fx.Exception.AsError(new InvalidOperationException(message));
		}

		protected static TAsyncResult End<TAsyncResult>(IAsyncResult result) where TAsyncResult : AsyncResult
		{
			if (result == null)
			{
				throw Fx.Exception.ArgumentNull("result");
			}
			if (!(result is TAsyncResult val))
			{
				throw Fx.Exception.Argument("result", "Invalid Async Result");
			}
			if (val.endCalled)
			{
				throw Fx.Exception.AsError(new InvalidOperationException("Async Result Already Ended"));
			}
			val.endCalled = true;
			if (!val.isCompleted)
			{
				val.AsyncWaitHandle.WaitOne();
			}
			if (val.manualResetEvent != null)
			{
				val.manualResetEvent.Close();
			}
			if (val.exception != null)
			{
				throw Fx.Exception.AsError(val.exception);
			}
			return val;
		}
	}
	internal class AsyncWaitHandle
	{
		private class AsyncWaiter : ActionItem
		{
			[SecurityCritical]
			private Action<object, TimeoutException> callback;

			[SecurityCritical]
			private object state;

			private IOThreadTimer timer;

			private TimeSpan originalTimeout;

			public AsyncWaitHandle Parent { get; private set; }

			public bool TimedOut { get; set; }

			[SecuritySafeCritical]
			public AsyncWaiter(AsyncWaitHandle parent, Action<object, TimeoutException> callback, object state)
			{
				Parent = parent;
				this.callback = callback;
				this.state = state;
			}

			[SecuritySafeCritical]
			public void Call()
			{
				Schedule();
			}

			[SecurityCritical]
			protected override void Invoke()
			{
				callback(state, TimedOut ? new TimeoutException(InternalSR.TimeoutOnOperation(originalTimeout)) : null);
			}

			public void SetTimer(Action<object> callback, object state, TimeSpan timeout)
			{
				if (timer != null)
				{
					throw Fx.Exception.AsError(new InvalidOperationException("Must Cancel Old Timer"));
				}
				originalTimeout = timeout;
				timer = new IOThreadTimer(callback, state, isTypicallyCanceledShortlyAfterBeingSet: false);
				timer.Set(timeout);
			}

			public void CancelTimer()
			{
				if (timer != null)
				{
					timer.Cancel();
					timer = null;
				}
			}
		}

		private static Action<object> timerCompleteCallback;

		private List<AsyncWaiter> asyncWaiters;

		private bool isSignaled;

		private EventResetMode resetMode;

		private object syncObject;

		private int syncWaiterCount;

		public AsyncWaitHandle()
			: this(EventResetMode.AutoReset)
		{
		}

		public AsyncWaitHandle(EventResetMode resetMode)
		{
			this.resetMode = resetMode;
			syncObject = new object();
		}

		public bool WaitAsync(Action<object, TimeoutException> callback, object state, TimeSpan timeout)
		{
			if (!isSignaled || (isSignaled && resetMode == EventResetMode.AutoReset))
			{
				lock (syncObject)
				{
					if (isSignaled && resetMode == EventResetMode.AutoReset)
					{
						isSignaled = false;
					}
					else if (!isSignaled)
					{
						AsyncWaiter asyncWaiter = new AsyncWaiter(this, callback, state);
						if (asyncWaiters == null)
						{
							asyncWaiters = new List<AsyncWaiter>();
						}
						asyncWaiters.Add(asyncWaiter);
						if (timeout != TimeSpan.MaxValue)
						{
							if (timerCompleteCallback == null)
							{
								timerCompleteCallback = OnTimerComplete;
							}
							asyncWaiter.SetTimer(timerCompleteCallback, asyncWaiter, timeout);
						}
						return false;
					}
				}
			}
			return true;
		}

		private static void OnTimerComplete(object state)
		{
			AsyncWaiter asyncWaiter = (AsyncWaiter)state;
			AsyncWaitHandle parent = asyncWaiter.Parent;
			bool flag = false;
			lock (parent.syncObject)
			{
				if (parent.asyncWaiters != null && parent.asyncWaiters.Remove(asyncWaiter))
				{
					asyncWaiter.TimedOut = true;
					flag = true;
				}
			}
			asyncWaiter.CancelTimer();
			if (flag)
			{
				asyncWaiter.Call();
			}
		}

		public bool Wait(TimeSpan timeout)
		{
			if (!isSignaled || (isSignaled && resetMode == EventResetMode.AutoReset))
			{
				lock (syncObject)
				{
					if (isSignaled && resetMode == EventResetMode.AutoReset)
					{
						isSignaled = false;
					}
					else if (!isSignaled)
					{
						bool flag = false;
						try
						{
							try
							{
							}
							finally
							{
								syncWaiterCount++;
								flag = true;
							}
							if (timeout == TimeSpan.MaxValue)
							{
								if (!Monitor.Wait(syncObject, -1))
								{
									return false;
								}
							}
							else if (!Monitor.Wait(syncObject, timeout))
							{
								return false;
							}
						}
						finally
						{
							if (flag)
							{
								syncWaiterCount--;
							}
						}
					}
				}
			}
			return true;
		}

		public void Set()
		{
			List<AsyncWaiter> list = null;
			AsyncWaiter asyncWaiter = null;
			if (!isSignaled)
			{
				lock (syncObject)
				{
					if (!isSignaled)
					{
						if (resetMode == EventResetMode.ManualReset)
						{
							isSignaled = true;
							Monitor.PulseAll(syncObject);
							list = asyncWaiters;
							asyncWaiters = null;
						}
						else if (syncWaiterCount > 0)
						{
							Monitor.Pulse(syncObject);
						}
						else if (asyncWaiters != null && asyncWaiters.Count > 0)
						{
							asyncWaiter = asyncWaiters[0];
							asyncWaiters.RemoveAt(0);
						}
						else
						{
							isSignaled = true;
						}
					}
				}
			}
			if (list != null)
			{
				foreach (AsyncWaiter item in list)
				{
					item.CancelTimer();
					item.Call();
				}
			}
			if (asyncWaiter != null)
			{
				asyncWaiter.CancelTimer();
				asyncWaiter.Call();
			}
		}

		public void Reset()
		{
			isSignaled = false;
		}
	}
	internal sealed class BackoffTimeoutHelper
	{
		private static readonly int maxSkewMilliseconds = (int)(IOThreadTimer.SystemTimeResolutionTicks / 10000);

		private static readonly long maxDriftTicks = IOThreadTimer.SystemTimeResolutionTicks * 2;

		private static readonly TimeSpan defaultInitialWaitTime = TimeSpan.FromMilliseconds(1.0);

		private static readonly TimeSpan defaultMaxWaitTime = TimeSpan.FromMinutes(1.0);

		private DateTime deadline;

		private TimeSpan maxWaitTime;

		private TimeSpan waitTime;

		private IOThreadTimer backoffTimer;

		private Action<object> backoffCallback;

		private object backoffState;

		private Random random;

		private TimeSpan originalTimeout;

		public TimeSpan OriginalTimeout => originalTimeout;

		internal BackoffTimeoutHelper(TimeSpan timeout)
			: this(timeout, defaultMaxWaitTime)
		{
		}

		internal BackoffTimeoutHelper(TimeSpan timeout, TimeSpan maxWaitTime)
			: this(timeout, maxWaitTime, defaultInitialWaitTime)
		{
		}

		internal BackoffTimeoutHelper(TimeSpan timeout, TimeSpan maxWaitTime, TimeSpan initialWaitTime)
		{
			random = new Random(GetHashCode());
			this.maxWaitTime = maxWaitTime;
			originalTimeout = timeout;
			Reset(timeout, initialWaitTime);
		}

		private void Reset(TimeSpan timeout, TimeSpan initialWaitTime)
		{
			if (timeout == TimeSpan.MaxValue)
			{
				deadline = DateTime.MaxValue;
			}
			else
			{
				deadline = DateTime.UtcNow + timeout;
			}
			waitTime = initialWaitTime;
		}

		public bool IsExpired()
		{
			if (deadline == DateTime.MaxValue)
			{
				return false;
			}
			return DateTime.UtcNow >= deadline;
		}

		public void WaitAndBackoff(Action<object> callback, object state)
		{
			if (backoffCallback != callback || backoffState != state)
			{
				if (backoffTimer != null)
				{
					backoffTimer.Cancel();
				}
				backoffCallback = callback;
				backoffState = state;
				backoffTimer = new IOThreadTimer(callback, state, isTypicallyCanceledShortlyAfterBeingSet: false, maxSkewMilliseconds);
			}
			TimeSpan timeFromNow = WaitTimeWithDrift();
			Backoff();
			backoffTimer.Set(timeFromNow);
		}

		public void WaitAndBackoff()
		{
			Thread.Sleep(WaitTimeWithDrift());
			Backoff();
		}

		private TimeSpan WaitTimeWithDrift()
		{
			return Ticks.ToTimeSpan(Math.Max(Ticks.FromTimeSpan(defaultInitialWaitTime), Ticks.Add(Ticks.FromTimeSpan(waitTime), (uint)random.Next() % (2 * maxDriftTicks + 1) - maxDriftTicks)));
		}

		private void Backoff()
		{
			if (waitTime.Ticks >= maxWaitTime.Ticks / 2)
			{
				waitTime = maxWaitTime;
			}
			else
			{
				waitTime = TimeSpan.FromTicks(waitTime.Ticks * 2);
			}
			if (!(deadline != DateTime.MaxValue))
			{
				return;
			}
			TimeSpan timeSpan = deadline - DateTime.UtcNow;
			if (waitTime > timeSpan)
			{
				waitTime = timeSpan;
				if (waitTime < TimeSpan.Zero)
				{
					waitTime = TimeSpan.Zero;
				}
			}
		}
	}
	internal class BufferedOutputStream : Stream
	{
		private InternalBufferManager bufferManager;

		private byte[][] chunks;

		private int chunkCount;

		private byte[] currentChunk;

		private int currentChunkSize;

		private int maxSize;

		private int maxSizeQuota;

		private int totalSize;

		private bool callerReturnsBuffer;

		private bool bufferReturned;

		private bool initialized;

		public override bool CanRead => false;

		public override bool CanSeek => false;

		public override bool CanWrite => true;

		public override long Length => totalSize;

		public override long Position
		{
			get
			{
				throw Fx.Exception.AsError(new NotSupportedException("Seek Not Supported"));
			}
			set
			{
				throw Fx.Exception.AsError(new NotSupportedException("Seek Not Supported"));
			}
		}

		public BufferedOutputStream()
		{
			chunks = new byte[4][];
		}

		public BufferedOutputStream(int initialSize, int maxSize, InternalBufferManager bufferManager)
			: this()
		{
			Reinitialize(initialSize, maxSize, bufferManager);
		}

		public BufferedOutputStream(int maxSize)
			: this(0, maxSize, InternalBufferManager.Create(0L, int.MaxValue))
		{
		}

		public void Reinitialize(int initialSize, int maxSizeQuota, InternalBufferManager bufferManager)
		{
			Reinitialize(initialSize, maxSizeQuota, maxSizeQuota, bufferManager);
		}

		public void Reinitialize(int initialSize, int maxSizeQuota, int effectiveMaxSize, InternalBufferManager bufferManager)
		{
			this.maxSizeQuota = maxSizeQuota;
			maxSize = effectiveMaxSize;
			this.bufferManager = bufferManager;
			currentChunk = bufferManager.TakeBuffer(initialSize);
			currentChunkSize = 0;
			totalSize = 0;
			chunkCount = 1;
			chunks[0] = currentChunk;
			initialized = true;
		}

		private void AllocNextChunk(int minimumChunkSize)
		{
			int num = ((currentChunk.Length <= 1073741823) ? (currentChunk.Length * 2) : int.MaxValue);
			if (minimumChunkSize > num)
			{
				num = minimumChunkSize;
			}
			byte[] array = bufferManager.TakeBuffer(num);
			if (chunkCount == chunks.Length)
			{
				byte[][] destinationArray = new byte[chunks.Length * 2][];
				Array.Copy(chunks, destinationArray, chunks.Length);
				chunks = destinationArray;
			}
			chunks[chunkCount++] = array;
			currentChunk = array;
			currentChunkSize = 0;
		}

		public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
		{
			throw Fx.Exception.AsError(new NotSupportedException("Read Not Supported"));
		}

		public override int EndRead(IAsyncResult result)
		{
			throw Fx.Exception.AsError(new NotSupportedException("Read Not Supported"));
		}

		public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
		{
			Write(buffer, offset, size);
			return new CompletedAsyncResult(callback, state);
		}

		public override void EndWrite(IAsyncResult result)
		{
			CompletedAsyncResult.End(result);
		}

		public void Clear()
		{
			if (!callerReturnsBuffer)
			{
				for (int i = 0; i < chunkCount; i++)
				{
					bufferManager.ReturnBuffer(chunks[i]);
					chunks[i] = null;
				}
			}
			callerReturnsBuffer = false;
			initialized = false;
			bufferReturned = false;
			chunkCount = 0;
			currentChunk = null;
		}

		public override void Close()
		{
		}

		public override void Flush()
		{
		}

		public override int Read(byte[] buffer, int offset, int size)
		{
			throw Fx.Exception.AsError(new NotSupportedException("Read Not Supported"));
		}

		public override int ReadByte()
		{
			throw Fx.Exception.AsError(new NotSupportedException("Read Not Supported"));
		}

		public override long Seek(long offset, SeekOrigin origin)
		{
			throw Fx.Exception.AsError(new NotSupportedException("Seek Not Supported"));
		}

		public override void SetLength(long value)
		{
			throw Fx.Exception.AsError(new NotSupportedException("Seek Not Supported"));
		}

		public MemoryStream ToMemoryStream()
		{
			int bufferSize;
			return new MemoryStream(ToArray(out bufferSize), 0, bufferSize);
		}

		public byte[] ToArray(out int bufferSize)
		{
			byte[] array;
			if (chunkCount == 1)
			{
				array = currentChunk;
				bufferSize = currentChunkSize;
				callerReturnsBuffer = true;
			}
			else
			{
				array = bufferManager.TakeBuffer(totalSize);
				int num = 0;
				int num2 = chunkCount - 1;
				for (int i = 0; i < num2; i++)
				{
					byte[] array2 = chunks[i];
					Buffer.BlockCopy(array2, 0, array, num, array2.Length);
					num += array2.Length;
				}
				Buffer.BlockCopy(currentChunk, 0, array, num, currentChunkSize);
				bufferSize = totalSize;
			}
			bufferReturned = true;
			return array;
		}

		public void Skip(int size)
		{
			WriteCore(null, 0, size);
		}

		public override void Write(byte[] buffer, int offset, int size)
		{
			WriteCore(buffer, offset, size);
		}

		protected virtual Exception CreateQuotaExceededException(int maxSizeQuota)
		{
			return new InvalidOperationException(InternalSR.BufferedOutputStreamQuotaExceeded(maxSizeQuota));
		}

		private void WriteCore(byte[] buffer, int offset, int size)
		{
			if (size < 0)
			{
				throw Fx.Exception.ArgumentOutOfRange("size", size, "Value Must Be Non Negative");
			}
			if (int.MaxValue - size < totalSize)
			{
				throw Fx.Exception.AsError(CreateQuotaExceededException(maxSizeQuota));
			}
			int num = totalSize + size;
			if (num > maxSize)
			{
				throw Fx.Exception.AsError(CreateQuotaExceededException(maxSizeQuota));
			}
			int num2 = currentChunk.Length - currentChunkSize;
			if (size > num2)
			{
				if (num2 > 0)
				{
					if (buffer != null)
					{
						Buffer.BlockCopy(buffer, offset, currentChunk, currentChunkSize, num2);
					}
					currentChunkSize = currentChunk.Length;
					offset += num2;
					size -= num2;
				}
				AllocNextChunk(size);
			}
			if (buffer != null)
			{
				Buffer.BlockCopy(buffer, offset, currentChunk, currentChunkSize, size);
			}
			totalSize = num;
			currentChunkSize += size;
		}

		public override void WriteByte(byte value)
		{
			if (totalSize == maxSize)
			{
				throw Fx.Exception.AsError(CreateQuotaExceededException(maxSize));
			}
			if (currentChunkSize == currentChunk.Length)
			{
				AllocNextChunk(1);
			}
			currentChunk[currentChunkSize++] = value;
		}
	}
	[Serializable]
	internal class CallbackException : FatalException
	{
		public CallbackException()
		{
		}

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

		protected CallbackException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	internal class CompletedAsyncResult : AsyncResult
	{
		public CompletedAsyncResult(AsyncCallback callback, object state)
			: base(callback, state)
		{
			Complete(completedSynchronously: true);
		}

		public static void End(IAsyncResult result)
		{
			Fx.AssertAndThrowFatal(result.IsCompleted, "CompletedAsyncResult was not completed!");
			AsyncResult.End<CompletedAsyncResult>(result);
		}
	}
	internal class CompletedAsyncResult<T> : AsyncResult
	{
		private T data;

		public CompletedAsyncResult(T data, AsyncCallback callback, object state)
			: base(callback, state)
		{
			this.data = data;
			Complete(completedSynchronously: true);
		}

		public static T End(IAsyncResult result)
		{
			Fx.AssertAndThrowFatal(result.IsCompleted, "CompletedAsyncResult<T> was not completed!");
			return AsyncResult.End<CompletedAsyncResult<T>>(result).data;
		}
	}
	internal class CompletedAsyncResult<TResult, TParameter> : AsyncResult
	{
		private TResult resultData;

		private TParameter parameter;

		public CompletedAsyncResult(TResult resultData, TParameter parameter, AsyncCallback callback, object state)
			: base(callback, state)
		{
			this.resultData = resultData;
			this.parameter = parameter;
			Complete(completedSynchronously: true);
		}

		public static TResult End(IAsyncResult result, out TParameter parameter)
		{
			Fx.AssertAndThrowFatal(result.IsCompleted, "CompletedAsyncResult<T> was not completed!");
			CompletedAsyncResult<TResult, TParameter> completedAsyncResult = AsyncResult.End<CompletedAsyncResult<TResult, TParameter>>(result);
			parameter = completedAsyncResult.parameter;
			return completedAsyncResult.resultData;
		}
	}
	internal enum ComputerNameFormat
	{
		NetBIOS,
		DnsHostName,
		Dns,
		DnsFullyQualified,
		PhysicalNetBIOS,
		PhysicalDnsHostName,
		PhysicalDnsDomain,
		PhysicalDnsFullyQualified
	}
	internal static class DiagnosticStrings
	{
		internal const string AppDomain = "AppDomain";

		internal const string ChannelTag = "Channel";

		internal const string Description = "Description";

		internal const string DataTag = "Data";

		internal const string DataItemsTag = "DataItems";

		internal const string DescriptionTag = "Description";

		internal const string ExceptionTag = "Exception";

		internal const string ExceptionTypeTag = "ExceptionType";

		internal const string ExceptionStringTag = "ExceptionString";

		internal const string ExtendedDataTag = "ExtendedData";

		internal const string InnerExceptionTag = "InnerException";

		internal const string KeyTag = "Key";

		internal const string MessageTag = "Message";

		internal const string NamespaceTag = "xmlns";

		internal const string NativeErrorCodeTag = "NativeErrorCode";

		internal const string Separator = ":";

		internal const string SeverityTag = "Severity";

		internal const string SourceTag = "Source";

		internal const string StackTraceTag = "StackTrace";

		internal const string Task = "Task";

		internal const string TraceCodeTag = "TraceIdentifier";

		internal const string TraceRecordTag = "TraceRecord";

		internal const string ValueTag = "Value";
	}
	internal class DuplicateDetector<T> where T : class
	{
		private LinkedList<T> fifoList;

		private Dictionary<T, LinkedListNode<T>> items;

		private int capacity;

		private object thisLock;

		public DuplicateDetector(int capacity)
		{
			this.capacity = capacity;
			items = new Dictionary<T, LinkedListNode<T>>();
			fifoList = new LinkedList<T>();
			thisLock = new object();
		}

		public bool AddIfNotDuplicate(T value)
		{
			bool result = false;
			lock (thisLock)
			{
				if (!items.ContainsKey(value))
				{
					Add(value);
					result = true;
				}
			}
			return result;
		}

		private void Add(T value)
		{
			if (items.Count == capacity)
			{
				LinkedListNode<T> last = fifoList.Last;
				items.Remove(last.Value);
				fifoList.Remove(last);
			}
			items.Add(value, fifoList.AddFirst(value));
		}

		public bool Remove(T value)
		{
			bool result = false;
			lock (thisLock)
			{
				if (items.TryGetValue(value, out var value2))
				{
					items.Remove(value);
					fifoList.Remove(value2);
					result = true;
				}
			}
			return result;
		}

		public void Clear()
		{
			lock (thisLock)
			{
				fifoList.Clear();
				items.Clear();
			}
		}
	}
	internal class ExceptionTrace
	{
		private const ushort FailFastEventLogCategory = 6;

		private string eventSourceName;

		private readonly EtwDiagnosticTrace diagnosticTrace;

		public ExceptionTrace(string eventSourceName, EtwDiagnosticTrace diagnosticTrace)
		{
			this.eventSourceName = eventSourceName;
			this.diagnosticTrace = diagnosticTrace;
		}

		public void AsInformation(Exception exception)
		{
			TraceCore.HandledException(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception);
		}

		public void AsWarning(Exception exception)
		{
			TraceCore.HandledExceptionWarning(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception);
		}

		public Exception AsError(Exception exception)
		{
			if (exception is AggregateException aggregateException)
			{
				return AsError<Exception>(aggregateException);
			}
			if (exception is TargetInvocationException ex && ex.InnerException != null)
			{
				return AsError(ex.InnerException);
			}
			return TraceException(exception);
		}

		public Exception AsError(Exception exception, string eventSource)
		{
			if (exception is AggregateException aggregateException)
			{
				return AsError<Exception>(aggregateException, eventSource);
			}
			if (exception is TargetInvocationException ex && ex.InnerException != null)
			{
				return AsError(ex.InnerException, eventSource);
			}
			return TraceException(exception, eventSource);
		}

		public Exception AsError(TargetInvocationException targetInvocationException, string eventSource)
		{
			if (Fx.IsFatal(targetInvocationException))
			{
				return targetInvocationException;
			}
			Exception innerException = targetInvocationException.InnerException;
			if (innerException != null)
			{
				return AsError(innerException, eventSource);
			}
			return TraceException((Exception)targetInvocationException, eventSource);
		}

		public Exception AsError<TPreferredException>(AggregateException aggregateException)
		{
			return AsError<TPreferredException>(aggregateException, eventSourceName);
		}

		public Exception AsError<TPreferredException>(AggregateException aggregateException, string eventSource)
		{
			if (Fx.IsFatal(aggregateException))
			{
				return aggregateException;
			}
			ReadOnlyCollection<Exception> innerExceptions = aggregateException.Flatten().InnerExceptions;
			if (innerExceptions.Count == 0)
			{
				return TraceException(aggregateException, eventSource);
			}
			Exception ex = null;
			foreach (Exception item in innerExceptions)
			{
				Exception ex3 = ((item is TargetInvocationException ex2 && ex2.InnerException != null) ? ex2.InnerException : item);
				if (ex3 is TPreferredException && ex == null)
				{
					ex = ex3;
				}
				TraceException(ex3, eventSource);
			}
			if (ex == null)
			{
				ex = innerExceptions[0];
			}
			return ex;
		}

		public ArgumentException Argument(string paramName, string message)
		{
			return TraceException(new ArgumentException(message, paramName));
		}

		public ArgumentNullException ArgumentNull(string paramName)
		{
			return TraceException(new ArgumentNullException(paramName));
		}

		public ArgumentNullException ArgumentNull(string paramName, string message)
		{
			return TraceException(new ArgumentNullException(paramName, message));
		}

		public ArgumentException ArgumentNullOrEmpty(string paramName)
		{
			return Argument(paramName, InternalSR.ArgumentNullOrEmpty(paramName));
		}

		public ArgumentOutOfRangeException ArgumentOutOfRange(string paramName, object actualValue, string message)
		{
			return TraceException(new ArgumentOutOfRangeException(paramName, actualValue, message));
		}

		public ObjectDisposedException ObjectDisposed(string message)
		{
			return TraceException(new ObjectDisposedException(null, message));
		}

		public void TraceUnhandledException(Exception exception)
		{
			TraceCore.UnhandledException(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception);
		}

		public void TraceHandledException(Exception exception, TraceEventType traceEventType)
		{
			switch (traceEventType)
			{
			case TraceEventType.Error:
				if (TraceCore.HandledExceptionErrorIsEnabled(diagnosticTrace))
				{
					TraceCore.HandledExceptionError(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception);
				}
				break;
			case TraceEventType.Warning:
				if (TraceCore.HandledExceptionWarningIsEnabled(diagnosticTrace))
				{
					TraceCore.HandledExceptionWarning(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception);
				}
				break;
			case TraceEventType.Verbose:
				if (TraceCore.HandledExceptionVerboseIsEnabled(diagnosticTrace))
				{
					TraceCore.HandledExceptionVerbose(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception);
				}
				break;
			default:
				if (TraceCore.HandledExceptionIsEnabled(diagnosticTrace))
				{
					TraceCore.HandledException(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception);
				}
				break;
			}
		}

		public void TraceEtwException(Exception exception, TraceEventType eventType)
		{
			switch (eventType)
			{
			case TraceEventType.Error:
			case TraceEventType.Warning:
				if (TraceCore.ThrowingEtwExceptionIsEnabled(diagnosticTrace))
				{
					TraceCore.ThrowingEtwException(diagnosticTrace, eventSourceName, (exception != null) ? exception.ToString() : string.Empty, exception);
				}
				break;
			case TraceEventType.Critical:
				if (TraceCore.EtwUnhandledExceptionIsEnabled(diagnosticTrace))
				{
					TraceCore.EtwUnhandledException(diagnosticTrace, (exception != null) ? exception.ToString() : string.Empty, exception);
				}
				break;
			default:
				if (TraceCore.ThrowingEtwExceptionVerboseIsEnabled(diagnosticTrace))
				{
					TraceCore.ThrowingEtwExceptionVerbose(diagnosticTrace, eventSourceName, (exception != null) ? exception.ToString() : string.Empty, exception);
				}
				break;
			}
		}

		private TException TraceException<TException>(TException exception) where TException : Exception
		{
			return TraceException(exception, eventSourceName);
		}

		[SecuritySafeCritical]
		private TException TraceException<TException>(TException exception, string eventSource) where TException : Exception
		{
			if (TraceCore.ThrowingExceptionIsEnabled(diagnosticTrace))
			{
				TraceCore.ThrowingException(diagnosticTrace, eventSource, (exception != null) ? exception.ToString() : string.Empty, exception);
			}
			BreakOnException(exception);
			return exception;
		}

		[SecuritySafeCritical]
		private void BreakOnException(Exception exception)
		{
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal void TraceFailFast(string message)
		{
			EventLogger eventLogger = null;
			eventLogger = new EventLogger(eventSourceName, diagnosticTrace);
			TraceFailFast(message, eventLogger);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		internal void TraceFailFast(string message, EventLogger logger)
		{
			if (logger == null)
			{
				return;
			}
			try
			{
				string text = null;
				try
				{
					text = new StackTrace().ToString();
				}
				catch (Exception ex)
				{
					text = ex.Message;
					if (Fx.IsFatal(ex))
					{
						throw;
					}
				}
				finally
				{
					logger.LogEvent(TraceEventType.Critical, 6, 3221291110u, message, text);
				}
			}
			catch (Exception ex2)
			{
				logger.LogEvent(TraceEventType.Critical, 6, 3221291111u, ex2.ToString());
				if (Fx.IsFatal(ex2))
				{
					throw;
				}
			}
		}
	}
	internal delegate void FastAsyncCallback(object state, Exception asyncException);
	[Serializable]
	internal class FatalException : SystemException
	{
		public FatalException()
		{
		}

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

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

		protected FatalException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	internal static class Fx
	{
		public abstract class ExceptionHandler
		{
			public abstract bool HandleException(Exception exception);
		}

		public static class Tag
		{
			public enum CacheAttrition
			{
				None,
				ElementOnTimer,
				ElementOnGC,
				ElementOnCallback,
				FullPurgeOnTimer,
				FullPurgeOnEachAccess,
				PartialPurgeOnTimer,
				PartialPurgeOnEachAccess
			}

			public enum ThrottleAction
			{
				Reject,
				Pause
			}

			public enum ThrottleMetric
			{
				Count,
				Rate,
				Other
			}

			public enum Location
			{
				InProcess,
				OutOfProcess,
				LocalSystem,
				LocalOrRemoteSystem,
				RemoteSystem
			}

			public enum SynchronizationKind
			{
				LockStatement,
				MonitorWait,
				MonitorExplicit,
				InterlockedNoSpin,
				InterlockedWithSpin,
				FromFieldType
			}

			[Flags]
			public enum BlocksUsing
			{
				MonitorEnter = 0,
				MonitorWait = 1,
				ManualResetEvent = 2,
				AutoResetEvent = 3,
				AsyncResult = 4,
				IAsyncResult = 5,
				PInvoke = 6,
				InputQueue = 7,
				ThreadNeutralSemaphore = 8,
				PrivatePrimitive = 9,
				OtherInternalPrimitive = 0xA,
				OtherFrameworkPrimitive = 0xB,
				OtherInterop = 0xC,
				Other = 0xD,
				NonBlocking = 0xE
			}

			public static class Strings
			{
				internal const string ExternallyManaged = "externally managed";

				internal const string AppDomain = "AppDomain";

				internal const string DeclaringInstance = "instance of declaring class";

				internal const string Unbounded = "unbounded";

				internal const string Infinite = "infinite";
			}

			[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
			[Conditional("DEBUG")]
			public sealed class FriendAccessAllowedAttribute : Attribute
			{
				public string AssemblyName { get; set; }

				public FriendAccessAllowedAttribute(string assemblyName)
				{
					AssemblyName = assemblyName;
				}
			}

			public static class Throws
			{
				[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
				[Conditional("CODE_ANALYSIS_CDF")]
				public sealed class TimeoutAttribute : ThrowsAttribute
				{
					public TimeoutAttribute()
						: this("The operation timed out.")
					{
					}

					public TimeoutAttribute(string diagnosis)
						: base(typeof(TimeoutException), diagnosis)
					{
					}
				}
			}

			[AttributeUsage(AttributeTargets.Field)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class CacheAttribute : Attribute
			{
				private readonly Type elementType;

				private readonly CacheAttrition cacheAttrition;

				public Type ElementType => elementType;

				public CacheAttrition CacheAttrition => cacheAttrition;

				public string Scope { get; set; }

				public string SizeLimit { get; set; }

				public string Timeout { get; set; }

				public CacheAttribute(Type elementType, CacheAttrition cacheAttrition)
				{
					Scope = "instance of declaring class";
					SizeLimit = "unbounded";
					Timeout = "infinite";
					if (elementType == null)
					{
						throw Exception.ArgumentNull("elementType");
					}
					this.elementType = elementType;
					this.cacheAttrition = cacheAttrition;
				}
			}

			[AttributeUsage(AttributeTargets.Field)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class QueueAttribute : Attribute
			{
				private readonly Type elementType;

				public Type ElementType => elementType;

				public string Scope { get; set; }

				public string SizeLimit { get; set; }

				public bool StaleElementsRemovedImmediately { get; set; }

				public bool EnqueueThrowsIfFull { get; set; }

				public QueueAttribute(Type elementType)
				{
					Scope = "instance of declaring class";
					SizeLimit = "unbounded";
					if (elementType == null)
					{
						throw Exception.ArgumentNull("elementType");
					}
					this.elementType = elementType;
				}
			}

			[AttributeUsage(AttributeTargets.Field)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class ThrottleAttribute : Attribute
			{
				private readonly ThrottleAction throttleAction;

				private readonly ThrottleMetric throttleMetric;

				private readonly string limit;

				public ThrottleAction ThrottleAction => throttleAction;

				public ThrottleMetric ThrottleMetric => throttleMetric;

				public string Limit => limit;

				public string Scope { get; set; }

				public ThrottleAttribute(ThrottleAction throttleAction, ThrottleMetric throttleMetric, string limit)
				{
					Scope = "AppDomain";
					if (string.IsNullOrEmpty(limit))
					{
						throw Exception.ArgumentNullOrEmpty("limit");
					}
					this.throttleAction = throttleAction;
					this.throttleMetric = throttleMetric;
					this.limit = limit;
				}
			}

			[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class ExternalResourceAttribute : Attribute
			{
				private readonly Location location;

				private readonly string description;

				public Location Location => location;

				public string Description => description;

				public ExternalResourceAttribute(Location location, string description)
				{
					this.location = location;
					this.description = description;
				}
			}

			[AttributeUsage(AttributeTargets.Class | AttributeTargets.Field, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class SynchronizationObjectAttribute : Attribute
			{
				public bool Blocking { get; set; }

				public string Scope { get; set; }

				public SynchronizationKind Kind { get; set; }

				public SynchronizationObjectAttribute()
				{
					Blocking = true;
					Scope = "instance of declaring class";
					Kind = SynchronizationKind.FromFieldType;
				}
			}

			[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class SynchronizationPrimitiveAttribute : Attribute
			{
				private readonly BlocksUsing blocksUsing;

				public BlocksUsing BlocksUsing => blocksUsing;

				public bool SupportsAsync { get; set; }

				public bool Spins { get; set; }

				public string ReleaseMethod { get; set; }

				public SynchronizationPrimitiveAttribute(BlocksUsing blocksUsing)
				{
					this.blocksUsing = blocksUsing;
				}
			}

			[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class BlockingAttribute : Attribute
			{
				public string CancelMethod { get; set; }

				public Type CancelDeclaringType { get; set; }

				public string Conditional { get; set; }
			}

			[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class GuaranteeNonBlockingAttribute : Attribute
			{
			}

			[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class NonThrowingAttribute : Attribute
			{
			}

			[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public class ThrowsAttribute : Attribute
			{
				private readonly Type exceptionType;

				private readonly string diagnosis;

				public Type ExceptionType => exceptionType;

				public string Diagnosis => diagnosis;

				public ThrowsAttribute(Type exceptionType, string diagnosis)
				{
					if (exceptionType == null)
					{
						throw Exception.ArgumentNull("exceptionType");
					}
					if (string.IsNullOrEmpty(diagnosis))
					{
						throw Exception.ArgumentNullOrEmpty("diagnosis");
					}
					this.exceptionType = exceptionType;
					this.diagnosis = diagnosis;
				}
			}

			[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class InheritThrowsAttribute : Attribute
			{
				public Type FromDeclaringType { get; set; }

				public string From { get; set; }
			}

			[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class KnownXamlExternalAttribute : Attribute
			{
			}

			[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class XamlVisibleAttribute : Attribute
			{
				public bool Visible { get; private set; }

				public XamlVisibleAttribute()
					: this(visible: true)
				{
				}

				public XamlVisibleAttribute(bool visible)
				{
					Visible = visible;
				}
			}

			[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
			[Conditional("CODE_ANALYSIS_CDF")]
			public sealed class SecurityNoteAttribute : Attribute
			{
				public string Critical { get; set; }

				public string Safe { get; set; }

				public string Miscellaneous { get; set; }
			}
		}

		private abstract class Thunk<T> where T : class
		{
			[SecurityCritical]
			private T callback;

			internal T Callback
			{
				[SecuritySafeCritical]
				get
				{
					return callback;
				}
			}

			[SecuritySafeCritical]
			protected Thunk(T callback)
			{
				this.callback = callback;
			}
		}

		private sealed class ActionThunk<T1> : Thunk<Action<T1>>
		{
			public Action<T1> ThunkFrame => UnhandledExceptionFrame;

			public ActionThunk(Action<T1> callback)
				: base(callback)
			{
			}

			[SecuritySafeCritical]
			private void UnhandledExceptionFrame(T1 result)
			{
				RuntimeHelpers.PrepareConstrainedRegions();
				try
				{
					base.Callback(result);
				}
				catch (Exception exception)
				{
					if (!HandleAtThreadBase(exception))
					{
						throw;
					}
				}
			}
		}

		private sealed class AsyncThunk : Thunk<AsyncCallback>
		{
			public AsyncCallback ThunkFrame => UnhandledExceptionFrame;

			public AsyncThunk(AsyncCallback callback)
				: base(callback)
			{
			}

			[SecuritySafeCritical]
			private void UnhandledExceptionFrame(IAsyncResult result)
			{
				RuntimeHelpers.PrepareConstrainedRegions();
				try
				{
					base.Callback(result);
				}
				catch (Exception exception)
				{
					if (!HandleAtThreadBase(exception))
					{
						throw;
					}
				}
			}
		}

		private sealed class WaitThunk : Thunk<WaitCallback>
		{
			public WaitCallback ThunkFrame => UnhandledExceptionFrame;

			public WaitThunk(WaitCallback callback)
				: base(callback)
			{
			}

			[SecuritySafeCritical]
			private void UnhandledExceptionFrame(object state)
			{
				RuntimeHelpers.PrepareConstrainedRegions();
				try
				{
					base.Callback(state);
				}
				catch (Exception exception)
				{
					if (!HandleAtThreadBase(exception))
					{
						throw;
					}
				}
			}
		}

		private sealed class TimerThunk : Thunk<TimerCallback>
		{
			public TimerCallback ThunkFrame => UnhandledExceptionFrame;

			public TimerThunk(TimerCallback callback)
				: base(callback)
			{
			}

			[SecuritySafeCritical]
			private void UnhandledExceptionFrame(object state)
			{
				RuntimeHelpers.PrepareConstrainedRegions();
				try
				{
					base.Callback(state);
				}
				catch (Exception exception)
				{
					if (!HandleAtThreadBase(exception))
					{
						throw;
					}
				}
			}
		}

		private sealed class WaitOrTimerThunk : Thunk<WaitOrTimerCallback>
		{
			public WaitOrTimerCallback ThunkFrame => UnhandledExceptionFrame;

			public WaitOrTimerThunk(WaitOrTimerCallback callback)
				: base(callback)
			{
			}

			[SecuritySafeCritical]
			private void UnhandledExceptionFrame(object state, bool timedOut)
			{
				RuntimeHelpers.PrepareConstrainedRegions();
				try
				{
					base.Callback(state, timedOut);
				}
				catch (Exception exception)
				{
					if (!HandleAtThreadBase(exception))
					{
						throw;
					}
				}
			}
		}

		private sealed class SendOrPostThunk : Thunk<SendOrPostCallback>
		{
			public SendOrPostCallback ThunkFrame => UnhandledExceptionFrame;

			public SendOrPostThunk(SendOrPostCallback callback)
				: base(callback)
			{
			}

			[SecuritySafeCritical]
			private void UnhandledExceptionFrame(object state)
			{
				RuntimeHelpers.PrepareConstrainedRegions();
				try
				{
					base.Callback(state);
				}
				catch (Exception exception)
				{
					if (!HandleAtThreadBase(exception))
					{
						throw;
					}
				}
			}
		}

		[SecurityCritical]
		private sealed class IOCompletionThunk
		{
			private IOCompletionCallback callback;

			public unsafe IOCompletionCallback ThunkFrame => UnhandledExceptionFrame;

			public IOCompletionThunk(IOCompletionCallback callback)
			{
				this.callback = callback;
			}

			private unsafe void UnhandledExceptionFrame(uint error, uint bytesRead, NativeOverlapped* nativeOverlapped)
			{
				RuntimeHelpers.PrepareConstrainedRegions();
				try
				{
					callback(error, bytesRead, nativeOverlapped);
				}
				catch (Exception exception)
				{
					if (!HandleAtThreadBase(exception))
					{
						throw;
					}
				}
			}
		}

		[Serializable]
		private class InternalException : SystemException
		{
			public InternalException(string description)
				: base(InternalSR.ShipAssertExceptionMessage(description))
			{
			}

			protected InternalException(SerializationInfo info, StreamingContext context)
				: base(info, context)
			{
			}
		}

		[Serializable]
		private class FatalInternalException : InternalException
		{
			public FatalInternalException(string description)
				: base(description)
			{
			}

			protected FatalInternalException(SerializationInfo info, StreamingContext context)
				: base(info, context)
			{
			}
		}

		private const string defaultEventSource = "System.Runtime";

		private static ExceptionTrace exceptionTrace;

		private static EtwDiagnosticTrace diagnosticTrace;

		[SecurityCritical]
		private static ExceptionHandler asynchronousThreadExceptionHandler;

		public static ExceptionTrace Exception
		{
			get
			{
				if (exceptionTrace == null)
				{
					exceptionTrace = new ExceptionTrace("System.Runtime", Trace);
				}
				return exceptionTrace;
			}
		}

		public static EtwDiagnosticTrace Trace
		{
			get
			{
				if (diagnosticTrace == null)
				{
					diagnosticTrace = InitializeTracing();
				}
				return diagnosticTrace;
			}
		}

		public static ExceptionHandler AsynchronousThreadExceptionHandler
		{
			[SecuritySafeCritical]
			[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
			get
			{
				return asynchronousThreadExceptionHandler;
			}
			[SecurityCritical]
			set
			{
				asynchronousThreadExceptionHandler = value;
			}
		}

		internal static bool AssertsFailFast => false;

		internal static Type[] BreakOnExceptionTypes => null;

		internal static bool FastDebug => false;

		internal static bool StealthDebugger => false;

		[SecuritySafeCritical]
		private static EtwDiagnosticTrace InitializeTracing()
		{
			EtwDiagnosticTrace etwDiagnosticTrace = new EtwDiagnosticTrace("System.Runtime", EtwDiagnosticTrace.DefaultEtwProviderId);
			if (etwDiagnosticTrace.EtwProvider != null)
			{
				etwDiagnosticTrace.RefreshState = (Action)Delegate.Combine(etwDiagnosticTrace.RefreshState, (Action)delegate
				{
					UpdateLevel();
				});
			}
			UpdateLevel(etwDiagnosticTrace);
			return etwDiagnosticTrace;
		}

		[Conditional("DEBUG")]
		public static void Assert(bool condition, string description)
		{
		}

		[Conditional("DEBUG")]
		public static void Assert(string description)
		{
			AssertHelper.FireAssert(description);
		}

		public static void AssertAndThrow(bool condition, string description)
		{
			if (!condition)
			{
				AssertAndThrow(description);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static Exception AssertAndThrow(string description)
		{
			TraceCore.ShipAssertExceptionMessage(Trace, description);
			throw new InternalException(description);
		}

		public static void AssertAndThrowFatal(bool condition, string description)
		{
			if (!condition)
			{
				AssertAndThrowFatal(description);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static Exception AssertAndThrowFatal(string description)
		{
			TraceCore.ShipAssertExceptionMessage(Trace, description);
			throw new FatalInternalException(description);
		}

		public static void AssertAndFailFast(bool condition, string description)
		{
			if (!condition)
			{
				AssertAndFailFast(description);
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		[SecuritySafeCritical]
		public static Exception AssertAndFailFast(string description)
		{
			string message = InternalSR.FailFastMessage(description);
			try
			{
				try
				{
					Exception.TraceFailFast(message);
				}
				finally
				{
					Environment.FailFast(message);
				}
			}
			catch
			{
				throw;
			}
			return null;
		}

		public static bool IsFatal(Exception exception)
		{
			while (exception != null)
			{
				if (exception is FatalException || (exception is OutOfMemoryException && !(exception is InsufficientMemoryException)) || exception is ThreadAbortException || exception is FatalInternalException)
				{
					return true;
				}
				if (exception is TypeInitializationException || exception is TargetInvocationException)
				{
					exception = exception.InnerException;
					continue;
				}
				if (!(exception is AggregateException))
				{
					break;
				}
				foreach (Exception innerException in ((AggregateException)exception).InnerExceptions)
				{
					if (IsFatal(innerException))
					{
						return true;
					}
				}
				break;
			}
			return false;
		}

		public static Action<T1> ThunkCallback<T1>(Action<T1> callback)
		{
			return new ActionThunk<T1>(callback).ThunkFrame;
		}

		public static AsyncCallback ThunkCallback(AsyncCallback callback)
		{
			return new AsyncThunk(callback).ThunkFrame;
		}

		public static WaitCallback ThunkCallback(WaitCallback callback)
		{
			return new WaitThunk(callback).ThunkFrame;
		}

		public static TimerCallback ThunkCallback(TimerCallback callback)
		{
			return new TimerThunk(callback).ThunkFrame;
		}

		public static WaitOrTimerCallback ThunkCallback(WaitOrTimerCallback callback)
		{
			return new WaitOrTimerThunk(callback).ThunkFrame;
		}

		public static SendOrPostCallback ThunkCallback(SendOrPostCallback callback)
		{
			return new SendOrPostThunk(callback).ThunkFrame;
		}

		[SecurityCritical]
		public static IOCompletionCallback ThunkCallback(IOCompletionCallback callback)
		{
			return new IOCompletionThunk(callback).ThunkFrame;
		}

		public static Guid CreateGuid(string guidString)
		{
			bool flag = false;
			Guid empty = Guid.Empty;
			try
			{
				empty = new Guid(guidString);
				flag = true;
				return empty;
			}
			finally
			{
				if (!flag)
				{
					AssertAndThrow("Creation of the Guid failed.");
				}
			}
		}

		public static bool TryCreateGuid(string guidString, out Guid result)
		{
			bool result2 = false;
			result = Guid.Empty;
			try
			{
				result = new Guid(guidString);
				result2 = true;
			}
			catch (ArgumentException)
			{
			}
			catch (FormatException)
			{
			}
			catch (OverflowException)
			{
			}
			return result2;
		}

		public static byte[] AllocateByteArray(int size)
		{
			try
			{
				return new byte[size];
			}
			catch (OutOfMemoryException innerException)
			{
				throw Exception.AsError(new InsufficientMemoryException(InternalSR.BufferAllocationFailed(size), innerException));
			}
		}

		public static char[] AllocateCharArray(int size)
		{
			try
			{
				return new char[size];
			}
			catch (OutOfMemoryException innerException)
			{
				throw Exception.AsError(new InsufficientMemoryException(InternalSR.BufferAllocationFailed(size * 2), innerException));
			}
		}

		[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
		private static void TraceExceptionNoThrow(Exception exception)
		{
			try
			{
				Exception.TraceUnhandledException(exception);
			}
			catch
			{
			}
		}

		[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
		private static bool HandleAtThreadBase(Exception exception)
		{
			if (exception == null)
			{
				return false;
			}
			TraceExceptionNoThrow(exception);
			try
			{
				return AsynchronousThreadExceptionHandler?.HandleException(exception) ?? false;
			}
			catch (Exception exception2)
			{
				TraceExceptionNoThrow(exception2);
			}
			return false;
		}

		private static void UpdateLevel(EtwDiagnosticTrace trace)
		{
			if (trace != null && (TraceCore.ActionItemCallbackInvokedIsEnabled(trace) || TraceCore.ActionItemScheduledIsEnabled(trace)))
			{
				trace.SetEnd2EndActivityTracingEnabled(isEnd2EndTracingEnabled: true);
			}
		}

		private static void UpdateLevel()
		{
			UpdateLevel(Trace);
		}
	}
	internal static class FxCop
	{
		public static class Category
		{
			public const string Design = "Microsoft.Design";

			public const string Globalization = "Microsoft.Globalization";

			public const string Maintainability = "Microsoft.Maintainability";

			public const string MSInternal = "Microsoft.MSInternal";

			public const string Naming = "Microsoft.Naming";

			public const string Performance = "Microsoft.Performance";

			public const string Reliability = "Microsoft.Reliability";

			public const string Security = "Microsoft.Security";

			public const string Usage = "Microsoft.Usage";

			public const string Configuration = "Configuration";

			public const string ReliabilityBasic = "Reliability";

			public const string Xaml = "XAML";
		}

		public static class Rule
		{
			public const string AptcaMethodsShouldOnlyCallAptcaMethods = "CA2116:AptcaMethodsShouldOnlyCallAptcaMethods";

			public const string AssembliesShouldHaveValidStrongNames = "CA2210:AssembliesShouldHaveValidStrongNames";

			public const string AvoidCallingProblematicMethods = "CA2001:AvoidCallingProblematicMethods";

			public const string AvoidExcessiveComplexity = "CA1502:AvoidExcessiveComplexity";

			public const string AvoidNamespacesWithFewTypes = "CA1020:AvoidNamespacesWithFewTypes";

			public const string AvoidOutParameters = "CA1021:AvoidOutParameters";

			public const string AvoidUncalledPrivateCode = "CA1811:AvoidUncalledPrivateCode";

			public const string AvoidUninstantiatedInternalClasses = "CA1812:AvoidUninstantiatedInternalClasses";

			public const string AvoidUnsealedAttributes = "CA1813:AvoidUnsealedAttributes";

			public const string CollectionPropertiesShouldBeReadOnly = "CA2227:CollectionPropertiesShouldBeReadOnly";

			public const string CollectionsShouldImplementGenericInterface = "CA1010:CollectionsShouldImplementGenericInterface";

			public const string ConfigurationPropertyAttributeRule = "Configuration102:ConfigurationPropertyAttributeRule";

			public const string ConfigurationValidatorAttributeRule = "Configuration104:ConfigurationValidatorAttributeRule";

			public const string ConsiderPassingBaseTypesAsParameters = "CA1011:ConsiderPassingBaseTypesAsParameters";

			public const string CommunicationObjectThrowIf = "Reliability106";

			public const string ConfigurationPropertyNameRule = "Configuration103:ConfigurationPropertyNameRule";

			public const string DefaultParametersShouldNotBeUsed = "CA1026:DefaultParametersShouldNotBeUsed";

			public const string DefineAccessorsForAttributeArguments = "CA1019:DefineAccessorsForAttributeArguments";

			public const string DiagnosticsUtilityIsFatal = "Reliability108";

			public const string DisposableFieldsShouldBeDisposed = "CA2213:DisposableFieldsShouldBeDisposed";

			public const string DoNotCallOverridableMethodsInConstructors = "CA2214:DoNotCallOverridableMethodsInConstructors";

			public const string DoNotCatchGeneralExceptionTypes = "CA1031:DoNotCatchGeneralExceptionTypes";

			public const string DoNotDeclareReadOnlyMutableReferenceTypes = "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes";

			public const string DoNotDeclareVisibleInstanceFields = "CA1051:DoNotDeclareVisibleInstanceFields";

			public const string DoNotLockOnObjectsWithWeakIdentity = "CA2002:DoNotLockOnObjectsWithWeakIdentity";

			public const string DoNotIgnoreMethodResults = "CA1806:DoNotIgnoreMethodResults";

			public const string DoNotIndirectlyExposeMethodsWithLinkDemands = "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands";

			public const string DoNotPassLiteralsAsLocalizedParameters = "CA1303:DoNotPassLiteralsAsLocalizedParameters";

			public const string DoNotRaiseReservedExceptionTypes = "CA2201:DoNotRaiseReservedExceptionTypes";

			public const string EnumsShouldHaveZeroValue = "CA1008:EnumsShouldHaveZeroValue";

			public const string FlagsEnumsShouldHavePluralNames = "CA1714:FlagsEnumsShouldHavePluralNames";

			public const string GenericMethodsShouldProvideTypeParameter = "CA1004:GenericMethodsShouldProvideTypeParameter";

			public const string IdentifiersShouldBeSpelledCorrectly = "CA1704:IdentifiersShouldBeSpelledCorrectly";

			public const string IdentifiersShouldHaveCorrectSuffix = "CA1710:IdentifiersShouldHaveCorrectSuffix";

			public const string IdentifiersShouldNotContainTypeNames = "CA1720:IdentifiersShouldNotContainTypeNames";

			public const string IdentifiersShouldNotHaveIncorrectSuffix = "CA1711:IdentifiersShouldNotHaveIncorrectSuffix";

			public const string IdentifiersShouldNotMatchKeywords = "CA1716:IdentifiersShouldNotMatchKeywords";

			public const string ImplementStandardExceptionConstructors = "CA1032:ImplementStandardExceptionConstructors";

			public const string InstantiateArgumentExceptionsCorrectly = "CA2208:InstantiateArgumentExceptionsCorrectly";

			public const string InitializeReferenceTypeStaticFieldsInline = "CA1810:InitializeReferenceTypeStaticFieldsInline";

			public const string InterfaceMethodsShouldBeCallableByChildTypes = "CA1033:InterfaceMethodsShouldBeCallableByChildTypes";

			public const string MarkISerializableTypesWithSerializable = "CA2237:MarkISerializableTypesWithSerializable";

			public const string InvariantAssertRule = "Reliability101:InvariantAssertRule";

			public const string IsFatalRule = "Reliability108:IsFatalRule";

			public const string MarkMembersAsStatic = "CA1822:MarkMembersAsStatic";

			public const string NestedTypesShouldNotBeVisible = "CA1034:NestedTypesShouldNotBeVisible";

			public const string NormalizeStringsToUppercase = "CA1308:NormalizeStringsToUppercase";

			public const string OperatorOverloadsHaveNamedAlternates = "CA2225:OperatorOverloadsHaveNamedAlternates";

			public const string PropertyNamesShouldNotMatchGetMethods = "CA1721:PropertyNamesShouldNotMatchGetMethods";

			public const string PropertyTypesMustBeXamlVisible = "XAML1002:PropertyTypesMustBeXamlVisible";

			public const string PropertyExternalTypesMustBeKnown = "XAML1010:PropertyExternalTypesMustBeKnown";

			public const string ReplaceRepetitiveArgumentsWithParamsArray = "CA1025:ReplaceRepetitiveArgumentsWithParamsArray";

			public const string ResourceStringsShouldBeSpelledCorrectly = "CA1703:ResourceStringsShouldBeSpelledCorrectly";

			public const string ReviewSuppressUnmanagedCodeSecurityUsage = "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage";

			public const string ReviewUnusedParameters = "CA1801:ReviewUnusedParameters";

			public const string SecureAsserts = "CA2106:SecureAsserts";

			public const string SecureGetObjectDataOverrides = "CA2110:SecureGetObjectDataOverrides";

			public const string ShortAcronymsShouldBeUppercase = "CA1706:ShortAcronymsShouldBeUppercase";

			public const string SpecifyIFormatProvider = "CA1305:SpecifyIFormatProvider";

			public const string SpecifyMarshalingForPInvokeStringArguments = "CA2101:SpecifyMarshalingForPInvokeStringArguments";

			public const string StaticHolderTypesShouldNotHaveConstructors = "CA1053:StaticHolderTypesShouldNotHaveConstructors";

			public const string SystemAndMicrosoftNamespacesRequireApproval = "CA:SystemAndMicrosoftNamespacesRequireApproval";

			public const string UsePropertiesWhereAppropriate = "CA1024:UsePropertiesWhereAppropriate";

			public const string UriPropertiesShouldNotBeStrings = "CA1056:UriPropertiesShouldNotBeStrings";

			public const string VariableNamesShouldNotMatchFieldNames = "CA1500:VariableNamesShouldNotMatchFieldNames";

			public const string ThunkCallbackRule = "Reliability109:ThunkCallbackRule";

			public const string TransparentMethodsMustNotReferenceCriticalCode = "CA2140:TransparentMethodsMustNotReferenceCriticalCodeFxCopRule";

			public const string TypeConvertersMustBePublic = "XAML1004:TypeConvertersMustBePublic";

			public const string TypesMustHaveXamlCallableConstructors = "XAML1007:TypesMustHaveXamlCallableConstructors";

			public const string TypeNamesShouldNotMatchNamespaces = "CA1724:TypeNamesShouldNotMatchNamespaces";

			public const string TypesShouldHavePublicParameterlessConstructors = "XAML1009:TypesShouldHavePublicParameterlessConstructors";

			public const string UseEventsWhereAppropriate = "CA1030:UseEventsWhereAppropriate";

			public const string UseNewGuidHelperRule = "Reliability113:UseNewGuidHelperRule";

			public const string WrapExceptionsRule = "Reliability102:WrapExceptionsRule";
		}
	}
	internal static class HashHelper
	{
		public static byte[] ComputeHash(byte[] buffer)
		{
			int[] array = new int[16]
			{
				7, 12, 17, 22, 5, 9, 14, 20, 4, 11,
				16, 23, 6, 10, 15, 21
			};
			uint[] array2 = new uint[64]
			{
				3614090360u, 3905402710u, 606105819u, 3250441966u, 4118548399u, 1200080426u, 2821735955u, 4249261313u, 1770035416u, 2336552879u,
				4294925233u, 2304563134u, 1804603682u, 4254626195u, 2792965006u, 1236535329u, 4129170786u, 3225465664u, 643717713u, 3921069994u,
				3593408605u, 38016083u, 3634488961u, 3889429448u, 568446438u, 3275163606u, 4107603335u, 1163531501u, 2850285829u, 4243563512u,
				1735328473u, 2368359562u, 4294588738u, 2272392833u, 1839030562u, 4259657740u, 2763975236u, 1272893353u, 4139469664u, 3200236656u,
				681279174u, 3936430074u, 3572445317u, 76029189u, 3654602809u, 3873151461u, 530742520u, 3299628645u, 4096336452u, 1126891415u,
				2878612391u, 4237533241u, 1700485571u, 2399980690u, 4293915773u, 2240044497u, 1873313359u, 4264355552u, 2734768916u, 1309151649u,
				4149444226u, 3174756917u, 718787259u, 3951481745u
			};
			int num = (buffer.Length + 8) / 64 + 1;
			uint num2 = 1732584193u;
			uint num3 = 4023233417u;
			uint num4 = 2562383102u;
			uint num5 = 271733878u;
			for (int i = 0; i < num; i++)
			{
				byte[] array3 = buffer;
				int num6 = i * 64;
				if (num6 + 64 > buffer.Length)
				{
					array3 = new byte[64];
					for (int j = num6; j < buffer.Length; j++)
					{
						array3[j - num6] = buffer[j];
					}
					if (num6 <= buffer.Length)
					{
						array3[buffer.Length - num6] = 128;
					}
					if (i == num - 1)
					{
						array3[56] = (byte)(buffer.Length << 3);
						array3[57] = (byte)(buffer.Length >> 5);
						array3[58] = (byte)(buffer.Length >> 13);
						array3[59] = (byte)(buffer.Length >> 21);
					}
					num6 = 0;
				}
				uint num7 = num2;
				uint num8 = num3;
				uint num9 = num4;
				uint num10 = num5;
				for (int k = 0; k < 64; k++)
				{
					uint num11;
					int num12;
					if (k < 16)
					{
						num11 = (num8 & num9) | (~num8 & num10);
						num12 = k;
					}
					else if (k < 32)
					{
						num11 = (num8 & num10) | (num9 & ~num10);
						num12 = 5 * k + 1;
					}
					else if (k < 48)
					{
						num11 = num8 ^ num9 ^ num10;
						num12 = 3 * k + 5;
					}
					else
					{
						num11 = num9 ^ (num8 | ~num10);
						num12 = 7 * k;
					}
					num12 = (num12 & 0xF) * 4 + num6;
					uint num13 = num10;
					num10 = num9;
					num9 = num8;
					num8 = num7 + num11 + array2[k] + (uint)(array3[num12] + (array3[num12 + 1] << 8) + (array3[num12 + 2] << 16) + (array3[num12 + 3] << 24));
					num8 = (num8 << array[(k & 3) | ((k >> 2) & -4)]) | (num8 >> 32 - array[(k & 3) | ((k >> 2) & -4)]);
					num8 += num9;
					num7 = num13;
				}
				num2 += num7;
				num3 += num8;
				num4 += num9;
				num5 += num10;
			}
			return new byte[16]
			{
				(byte)num2,
				(byte)(num2 >> 8),
				(byte)(num2 >> 16),
				(byte)(num2 >> 24),
				(byte)num3,
				(byte)(num3 >> 8),
				(byte)(num3 >> 16),
				(byte)(num3 >> 24),
				(byte)num4,
				(byte)(num4 >> 8),
				(byte)(num4 >> 16),
				(byte)(num4 >> 24),
				(byte)num5,
				(byte)(num5 >> 8),
				(byte)(num5 >> 16),
				(byte)(num5 >> 24)
			};
		}
	}
	internal interface IAsyncEventArgs
	{
		object AsyncState { get; }

		Exception Exception { get; }
	}
	internal class IOThreadCancellationTokenSource : IDisposable
	{
		private static readonly Action<object> onCancel = Fx.ThunkCallback<object>(OnCancel);

		private readonly TimeSpan timeout;

		private CancellationTokenSource source;

		private CancellationToken? token;

		private IOThreadTimer timer;

		public CancellationToken Token
		{
			get
			{
				if (!token.HasValue)
				{
					if (timeout >= TimeoutHelper.MaxWait)
					{
						token = CancellationToken.None;
					}
					else
					{
						timer = new IOThreadTimer(onCancel, this, isTypicallyCanceledShortlyAfterBeingSet: true);
						source = new CancellationTokenSource();
						timer.Set(timeout);
						token = source.Token;
					}
				}
				return token.Value;
			}
		}

		public IOThreadCancellationTokenSource(TimeSpan timeout)
		{
			TimeoutHelper.ThrowIfNegativeArgument(timeout);
			this.timeout = timeout;
		}

		public IOThreadCancellationTokenSource(int timeout)
			: this(TimeSpan.FromMilliseconds(timeout))
		{
		}

		public void Dispose()
		{
			if (source != null && timer.Cancel())
			{
				source.Dispose();
				source = null;
			}
		}

		private static void OnCancel(object obj)
		{
			((IOThreadCancellationTokenSource)obj).Cancel();
		}

		private void Cancel()
		{
			source.Cancel();
			source.Dispose();
			source = null;
		}
	}
	internal class IOThreadScheduler
	{
		private static class Bits
		{
			public const int HiShift = 16;

			public const int HiOne = 65536;

			public const int LoHiBit = 32768;

			public const int HiHiBit = int.MinValue;

			public const int LoCountMask = 32767;

			public const int HiCountMask = 2147418112;

			public const int LoMask = 65535;

			public const int HiMask = -65536;

			public const int HiBits = -2147450880;

			public static int Count(int slot)
			{
				return (((slot >> 16) - slot + 2) & 0xFFFF) - 1;
			}

			public static int CountNoIdle(int slot)
			{
				return ((slot >> 16) - slot + 1) & 0xFFFF;
			}

			public static int IncrementLo(int slot)
			{
				return ((slot + 1) & 0xFFFF) | (slot & -65536);
			}

			public static bool IsComplete(int gate)
			{
				return (gate & -65536) == gate << 16;
			}
		}

		private struct Slot
		{
			private int gate;

			private Action<object> callback;

			private object state;

			public bool TryEnqueueWorkItem(Action<object> callback, object state, out bool wrapped)
			{
				int num = Interlocked.Increment(ref gate);
				wrapped = (num & 0x7FFF) != 1;
				if (wrapped)
				{
					if (((uint)num & 0x8000u) != 0 && Bits.IsComplete(num))
					{
						Interlocked.CompareExchange(ref gate, 0, num);
					}
					return false;
				}
				this.state = state;
				this.callback = callback;
				num = Interlocked.Add(ref gate, 32768);
				if ((num & 0x7FFF0000) == 0)
				{
					return true;
				}
				this.state = null;
				this.callback = null;
				if (num >> 16 != (num & 0x7FFF) || Interlocked.CompareExchange(ref gate, 0, num) != num)
				{
					num = Interlocked.Add(ref gate, int.MinValue);
					if (Bits.IsComplete(num))
					{
						Interlocked.CompareExchange(ref gate, 0, num);
					}
				}
				return false;
			}

			public void DequeueWorkItem(out Action<object> callback, out object state)
			{
				int num = Interlocked.Add(ref gate, 65536);
				if ((num & 0x8000) == 0)
				{
					callback = null;
					state = null;
				}
				else if ((num & 0x7FFF0000) == 65536)
				{
					callback = this.callback;
					state = this.state;
					this.state = null;
					this.callback = null;
					if ((num & 0x7FFF) != 1 || Interlocked.CompareExchange(ref gate, 0, num) != num)
					{
						num = Interlocked.Add(ref gate, int.MinValue);
						if (Bits.IsComplete(num))
						{
							Interlocked.CompareExchange(ref gate, 0, num);
						}
					}
				}
				else
				{
					callback = null;
					state = null;
					if (Bits.IsComplete(num))
					{
						Interlocked.CompareExchange(ref gate, 0, num);
					}
				}
			}
		}

		[SecurityCritical]
		private class ScheduledOverlapped
		{
			private unsafe readonly NativeOverlapped* nativeOverlapped;

			private IOThreadScheduler scheduler;

			public unsafe ScheduledOverlapped()
			{
				nativeOverlapped = new Overlapped().UnsafePack(Fx.ThunkCallback(IOCallback), null);
			}

			private unsafe void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped)
			{
				IOThreadScheduler iOThreadScheduler = scheduler;
				scheduler = null;
				Action<object> callback;
				object state;
				try
				{
				}
				finally
				{
					iOThreadScheduler.CompletionCallback(out callback, out state);
				}
				bool flag = true;
				while (flag)
				{
					callback?.Invoke(state);
					try
					{
					}
					finally
					{
						flag = iOThreadScheduler.TryCoalesce(out callback, out state);
					}
				}
			}

			public unsafe void Post(IOThreadScheduler iots)
			{
				scheduler = iots;
				ThreadPool.UnsafeQueueNativeOverlapped(nativeOverlapped);
			}

			public unsafe void Cleanup()
			{
				if (scheduler != null)
				{
					throw Fx.AssertAndThrowFatal("Cleanup called on an overlapped that is in-flight.");
				}
				Overlapped.Free(nativeOverlapped);
			}
		}

		private 

BepInEx/core/System.Text.Encoding.CodePages.dll

Decompiled 2 weeks ago
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using FxResources.System.Text.Encoding.CodePages;
using Microsoft.CodeAnalysis;
using Microsoft.Win32.SafeHandles;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Text.Encoding.CodePages")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides support for code-page based encodings, including Windows-1252, Shift-JIS, and GB2312.\r\n\r\nCommonly Used Types:\r\nSystem.Text.CodePagesEncodingProvider")]
[assembly: AssemblyFileVersion("7.0.22.51805")]
[assembly: AssemblyInformationalVersion("7.0.0+d099f075e45d2aa6007a22b71b45a08758559f80")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Text.Encoding.CodePages")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("7.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FxResources.System.Text.Encoding.CodePages
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled) && isEnabled;

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArgumentOutOfRange_NeedNonNegNum => GetResourceString("ArgumentOutOfRange_NeedNonNegNum");

		internal static string ArgumentOutOfRange_IndexCount => GetResourceString("ArgumentOutOfRange_IndexCount");

		internal static string ArgumentOutOfRange_IndexCountBuffer => GetResourceString("ArgumentOutOfRange_IndexCountBuffer");

		internal static string NotSupported_NoCodepageData => GetResourceString("NotSupported_NoCodepageData");

		internal static string Argument_EncodingConversionOverflowBytes => GetResourceString("Argument_EncodingConversionOverflowBytes");

		internal static string Argument_InvalidCharSequenceNoIndex => GetResourceString("Argument_InvalidCharSequenceNoIndex");

		internal static string ArgumentOutOfRange_GetByteCountOverflow => GetResourceString("ArgumentOutOfRange_GetByteCountOverflow");

		internal static string Argument_EncodingConversionOverflowChars => GetResourceString("Argument_EncodingConversionOverflowChars");

		internal static string ArgumentOutOfRange_GetCharCountOverflow => GetResourceString("ArgumentOutOfRange_GetCharCountOverflow");

		internal static string Argument_EncoderFallbackNotEmpty => GetResourceString("Argument_EncoderFallbackNotEmpty");

		internal static string Argument_RecursiveFallback => GetResourceString("Argument_RecursiveFallback");

		internal static string Argument_RecursiveFallbackBytes => GetResourceString("Argument_RecursiveFallbackBytes");

		internal static string ArgumentOutOfRange_Range => GetResourceString("ArgumentOutOfRange_Range");

		internal static string Argument_CodepageNotSupported => GetResourceString("Argument_CodepageNotSupported");

		internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess");

		internal static string ArgumentOutOfRange_IndexMustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_IndexMustBeLessOrEqual");

		internal static string MissingEncodingNameResource => GetResourceString("MissingEncodingNameResource");

		internal static string Globalization_cp_37 => GetResourceString("Globalization_cp_37");

		internal static string Globalization_cp_437 => GetResourceString("Globalization_cp_437");

		internal static string Globalization_cp_500 => GetResourceString("Globalization_cp_500");

		internal static string Globalization_cp_708 => GetResourceString("Globalization_cp_708");

		internal static string Globalization_cp_720 => GetResourceString("Globalization_cp_720");

		internal static string Globalization_cp_737 => GetResourceString("Globalization_cp_737");

		internal static string Globalization_cp_775 => GetResourceString("Globalization_cp_775");

		internal static string Globalization_cp_850 => GetResourceString("Globalization_cp_850");

		internal static string Globalization_cp_852 => GetResourceString("Globalization_cp_852");

		internal static string Globalization_cp_855 => GetResourceString("Globalization_cp_855");

		internal static string Globalization_cp_857 => GetResourceString("Globalization_cp_857");

		internal static string Globalization_cp_858 => GetResourceString("Globalization_cp_858");

		internal static string Globalization_cp_860 => GetResourceString("Globalization_cp_860");

		internal static string Globalization_cp_861 => GetResourceString("Globalization_cp_861");

		internal static string Globalization_cp_862 => GetResourceString("Globalization_cp_862");

		internal static string Globalization_cp_863 => GetResourceString("Globalization_cp_863");

		internal static string Globalization_cp_864 => GetResourceString("Globalization_cp_864");

		internal static string Globalization_cp_865 => GetResourceString("Globalization_cp_865");

		internal static string Globalization_cp_866 => GetResourceString("Globalization_cp_866");

		internal static string Globalization_cp_869 => GetResourceString("Globalization_cp_869");

		internal static string Globalization_cp_870 => GetResourceString("Globalization_cp_870");

		internal static string Globalization_cp_874 => GetResourceString("Globalization_cp_874");

		internal static string Globalization_cp_875 => GetResourceString("Globalization_cp_875");

		internal static string Globalization_cp_932 => GetResourceString("Globalization_cp_932");

		internal static string Globalization_cp_936 => GetResourceString("Globalization_cp_936");

		internal static string Globalization_cp_949 => GetResourceString("Globalization_cp_949");

		internal static string Globalization_cp_950 => GetResourceString("Globalization_cp_950");

		internal static string Globalization_cp_1026 => GetResourceString("Globalization_cp_1026");

		internal static string Globalization_cp_1047 => GetResourceString("Globalization_cp_1047");

		internal static string Globalization_cp_1140 => GetResourceString("Globalization_cp_1140");

		internal static string Globalization_cp_1141 => GetResourceString("Globalization_cp_1141");

		internal static string Globalization_cp_1142 => GetResourceString("Globalization_cp_1142");

		internal static string Globalization_cp_1143 => GetResourceString("Globalization_cp_1143");

		internal static string Globalization_cp_1144 => GetResourceString("Globalization_cp_1144");

		internal static string Globalization_cp_1145 => GetResourceString("Globalization_cp_1145");

		internal static string Globalization_cp_1146 => GetResourceString("Globalization_cp_1146");

		internal static string Globalization_cp_1147 => GetResourceString("Globalization_cp_1147");

		internal static string Globalization_cp_1148 => GetResourceString("Globalization_cp_1148");

		internal static string Globalization_cp_1149 => GetResourceString("Globalization_cp_1149");

		internal static string Globalization_cp_1250 => GetResourceString("Globalization_cp_1250");

		internal static string Globalization_cp_1251 => GetResourceString("Globalization_cp_1251");

		internal static string Globalization_cp_1252 => GetResourceString("Globalization_cp_1252");

		internal static string Globalization_cp_1253 => GetResourceString("Globalization_cp_1253");

		internal static string Globalization_cp_1254 => GetResourceString("Globalization_cp_1254");

		internal static string Globalization_cp_1255 => GetResourceString("Globalization_cp_1255");

		internal static string Globalization_cp_1256 => GetResourceString("Globalization_cp_1256");

		internal static string Globalization_cp_1257 => GetResourceString("Globalization_cp_1257");

		internal static string Globalization_cp_1258 => GetResourceString("Globalization_cp_1258");

		internal static string Globalization_cp_1361 => GetResourceString("Globalization_cp_1361");

		internal static string Globalization_cp_10000 => GetResourceString("Globalization_cp_10000");

		internal static string Globalization_cp_10001 => GetResourceString("Globalization_cp_10001");

		internal static string Globalization_cp_10002 => GetResourceString("Globalization_cp_10002");

		internal static string Globalization_cp_10003 => GetResourceString("Globalization_cp_10003");

		internal static string Globalization_cp_10004 => GetResourceString("Globalization_cp_10004");

		internal static string Globalization_cp_10005 => GetResourceString("Globalization_cp_10005");

		internal static string Globalization_cp_10006 => GetResourceString("Globalization_cp_10006");

		internal static string Globalization_cp_10007 => GetResourceString("Globalization_cp_10007");

		internal static string Globalization_cp_10008 => GetResourceString("Globalization_cp_10008");

		internal static string Globalization_cp_10010 => GetResourceString("Globalization_cp_10010");

		internal static string Globalization_cp_10017 => GetResourceString("Globalization_cp_10017");

		internal static string Globalization_cp_10021 => GetResourceString("Globalization_cp_10021");

		internal static string Globalization_cp_10029 => GetResourceString("Globalization_cp_10029");

		internal static string Globalization_cp_10079 => GetResourceString("Globalization_cp_10079");

		internal static string Globalization_cp_10081 => GetResourceString("Globalization_cp_10081");

		internal static string Globalization_cp_10082 => GetResourceString("Globalization_cp_10082");

		internal static string Globalization_cp_20000 => GetResourceString("Globalization_cp_20000");

		internal static string Globalization_cp_20001 => GetResourceString("Globalization_cp_20001");

		internal static string Globalization_cp_20002 => GetResourceString("Globalization_cp_20002");

		internal static string Globalization_cp_20003 => GetResourceString("Globalization_cp_20003");

		internal static string Globalization_cp_20004 => GetResourceString("Globalization_cp_20004");

		internal static string Globalization_cp_20005 => GetResourceString("Globalization_cp_20005");

		internal static string Globalization_cp_20105 => GetResourceString("Globalization_cp_20105");

		internal static string Globalization_cp_20106 => GetResourceString("Globalization_cp_20106");

		internal static string Globalization_cp_20107 => GetResourceString("Globalization_cp_20107");

		internal static string Globalization_cp_20108 => GetResourceString("Globalization_cp_20108");

		internal static string Globalization_cp_20261 => GetResourceString("Globalization_cp_20261");

		internal static string Globalization_cp_20269 => GetResourceString("Globalization_cp_20269");

		internal static string Globalization_cp_20273 => GetResourceString("Globalization_cp_20273");

		internal static string Globalization_cp_20277 => GetResourceString("Globalization_cp_20277");

		internal static string Globalization_cp_20278 => GetResourceString("Globalization_cp_20278");

		internal static string Globalization_cp_20280 => GetResourceString("Globalization_cp_20280");

		internal static string Globalization_cp_20284 => GetResourceString("Globalization_cp_20284");

		internal static string Globalization_cp_20285 => GetResourceString("Globalization_cp_20285");

		internal static string Globalization_cp_20290 => GetResourceString("Globalization_cp_20290");

		internal static string Globalization_cp_20297 => GetResourceString("Globalization_cp_20297");

		internal static string Globalization_cp_20420 => GetResourceString("Globalization_cp_20420");

		internal static string Globalization_cp_20423 => GetResourceString("Globalization_cp_20423");

		internal static string Globalization_cp_20424 => GetResourceString("Globalization_cp_20424");

		internal static string Globalization_cp_20833 => GetResourceString("Globalization_cp_20833");

		internal static string Globalization_cp_20838 => GetResourceString("Globalization_cp_20838");

		internal static string Globalization_cp_20866 => GetResourceString("Globalization_cp_20866");

		internal static string Globalization_cp_20871 => GetResourceString("Globalization_cp_20871");

		internal static string Globalization_cp_20880 => GetResourceString("Globalization_cp_20880");

		internal static string Globalization_cp_20905 => GetResourceString("Globalization_cp_20905");

		internal static string Globalization_cp_20924 => GetResourceString("Globalization_cp_20924");

		internal static string Globalization_cp_20932 => GetResourceString("Globalization_cp_20932");

		internal static string Globalization_cp_20936 => GetResourceString("Globalization_cp_20936");

		internal static string Globalization_cp_20949 => GetResourceString("Globalization_cp_20949");

		internal static string Globalization_cp_21025 => GetResourceString("Globalization_cp_21025");

		internal static string Globalization_cp_21027 => GetResourceString("Globalization_cp_21027");

		internal static string Globalization_cp_21866 => GetResourceString("Globalization_cp_21866");

		internal static string Globalization_cp_28592 => GetResourceString("Globalization_cp_28592");

		internal static string Globalization_cp_28593 => GetResourceString("Globalization_cp_28593");

		internal static string Globalization_cp_28594 => GetResourceString("Globalization_cp_28594");

		internal static string Globalization_cp_28595 => GetResourceString("Globalization_cp_28595");

		internal static string Globalization_cp_28596 => GetResourceString("Globalization_cp_28596");

		internal static string Globalization_cp_28597 => GetResourceString("Globalization_cp_28597");

		internal static string Globalization_cp_28598 => GetResourceString("Globalization_cp_28598");

		internal static string Globalization_cp_28599 => GetResourceString("Globalization_cp_28599");

		internal static string Globalization_cp_28603 => GetResourceString("Globalization_cp_28603");

		internal static string Globalization_cp_28605 => GetResourceString("Globalization_cp_28605");

		internal static string Globalization_cp_29001 => GetResourceString("Globalization_cp_29001");

		internal static string Globalization_cp_38598 => GetResourceString("Globalization_cp_38598");

		internal static string Globalization_cp_50000 => GetResourceString("Globalization_cp_50000");

		internal static string Globalization_cp_50220 => GetResourceString("Globalization_cp_50220");

		internal static string Globalization_cp_50221 => GetResourceString("Globalization_cp_50221");

		internal static string Globalization_cp_50222 => GetResourceString("Globalization_cp_50222");

		internal static string Globalization_cp_50225 => GetResourceString("Globalization_cp_50225");

		internal static string Globalization_cp_50227 => GetResourceString("Globalization_cp_50227");

		internal static string Globalization_cp_50229 => GetResourceString("Globalization_cp_50229");

		internal static string Globalization_cp_50930 => GetResourceString("Globalization_cp_50930");

		internal static string Globalization_cp_50931 => GetResourceString("Globalization_cp_50931");

		internal static string Globalization_cp_50933 => GetResourceString("Globalization_cp_50933");

		internal static string Globalization_cp_50935 => GetResourceString("Globalization_cp_50935");

		internal static string Globalization_cp_50937 => GetResourceString("Globalization_cp_50937");

		internal static string Globalization_cp_50939 => GetResourceString("Globalization_cp_50939");

		internal static string Globalization_cp_51932 => GetResourceString("Globalization_cp_51932");

		internal static string Globalization_cp_51936 => GetResourceString("Globalization_cp_51936");

		internal static string Globalization_cp_51949 => GetResourceString("Globalization_cp_51949");

		internal static string Globalization_cp_52936 => GetResourceString("Globalization_cp_52936");

		internal static string Globalization_cp_54936 => GetResourceString("Globalization_cp_54936");

		internal static string Globalization_cp_57002 => GetResourceString("Globalization_cp_57002");

		internal static string Globalization_cp_57003 => GetResourceString("Globalization_cp_57003");

		internal static string Globalization_cp_57004 => GetResourceString("Globalization_cp_57004");

		internal static string Globalization_cp_57005 => GetResourceString("Globalization_cp_57005");

		internal static string Globalization_cp_57006 => GetResourceString("Globalization_cp_57006");

		internal static string Globalization_cp_57007 => GetResourceString("Globalization_cp_57007");

		internal static string Globalization_cp_57008 => GetResourceString("Globalization_cp_57008");

		internal static string Globalization_cp_57009 => GetResourceString("Globalization_cp_57009");

		internal static string Globalization_cp_57010 => GetResourceString("Globalization_cp_57010");

		internal static string Globalization_cp_57011 => GetResourceString("Globalization_cp_57011");

		private static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		internal static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		internal static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.Versioning
{
	internal abstract class OSPlatformAttribute : Attribute
	{
		public string PlatformName { get; }

		private protected OSPlatformAttribute(string platformName)
		{
			PlatformName = platformName;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false, Inherited = false)]
	internal sealed class TargetPlatformAttribute : OSPlatformAttribute
	{
		public TargetPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformAttribute : OSPlatformAttribute
	{
		public string Message { get; }

		public UnsupportedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}

		public UnsupportedOSPlatformAttribute(string platformName, string message)
			: base(platformName)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)]
	internal sealed class ObsoletedOSPlatformAttribute : OSPlatformAttribute
	{
		public string Message { get; }

		public string Url { get; set; }

		public ObsoletedOSPlatformAttribute(string platformName)
			: base(platformName)
		{
		}

		public ObsoletedOSPlatformAttribute(string platformName, string message)
			: base(platformName)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class SupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public SupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class UnsupportedOSPlatformGuardAttribute : OSPlatformAttribute
	{
		public UnsupportedOSPlatformGuardAttribute(string platformName)
			: base(platformName)
		{
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Text
{
	internal abstract class BaseCodePageEncoding : EncodingNLS, ISerializable
	{
		[StructLayout(LayoutKind.Explicit)]
		internal struct CodePageDataFileHeader
		{
			[FieldOffset(0)]
			internal char TableName;

			[FieldOffset(32)]
			internal ushort Version;

			[FieldOffset(40)]
			internal short CodePageCount;

			[FieldOffset(42)]
			internal short unused1;
		}

		[StructLayout(LayoutKind.Explicit, Pack = 2)]
		internal struct CodePageIndex
		{
			[FieldOffset(0)]
			internal char CodePageName;

			[FieldOffset(32)]
			internal short CodePage;

			[FieldOffset(34)]
			internal short ByteCount;

			[FieldOffset(36)]
			internal int Offset;
		}

		[StructLayout(LayoutKind.Explicit)]
		internal struct CodePageHeader
		{
			[FieldOffset(0)]
			internal char CodePageName;

			[FieldOffset(32)]
			internal ushort VersionMajor;

			[FieldOffset(34)]
			internal ushort VersionMinor;

			[FieldOffset(36)]
			internal ushort VersionRevision;

			[FieldOffset(38)]
			internal ushort VersionBuild;

			[FieldOffset(40)]
			internal short CodePage;

			[FieldOffset(42)]
			internal short ByteCount;

			[FieldOffset(44)]
			internal char UnicodeReplace;

			[FieldOffset(46)]
			internal ushort ByteReplace;
		}

		internal const string CODE_PAGE_DATA_FILE_NAME = "codepages.nlp";

		protected int dataTableCodePage;

		protected int iExtraBytes;

		protected char[] arrayUnicodeBestFit;

		protected char[] arrayBytesBestFit;

		private const int CODEPAGE_DATA_FILE_HEADER_SIZE = 44;

		private const int CODEPAGE_HEADER_SIZE = 48;

		private static readonly byte[] s_codePagesDataHeader = new byte[44];

		protected static Stream s_codePagesEncodingDataStream = GetEncodingDataStream("codepages.nlp");

		protected static readonly object s_streamLock = new object();

		protected byte[] m_codePageHeader = new byte[48];

		protected int m_firstDataWordOffset;

		protected int m_dataSize;

		protected SafeAllocHHandle safeNativeMemoryHandle;

		internal BaseCodePageEncoding(int codepage)
			: this(codepage, codepage)
		{
		}

		internal BaseCodePageEncoding(int codepage, int dataCodePage)
			: base(codepage, new InternalEncoderBestFitFallback(null), new InternalDecoderBestFitFallback(null))
		{
			((InternalEncoderBestFitFallback)base.EncoderFallback).encoding = this;
			((InternalDecoderBestFitFallback)base.DecoderFallback).encoding = this;
			dataTableCodePage = dataCodePage;
			LoadCodePageTables();
		}

		internal BaseCodePageEncoding(int codepage, int dataCodePage, EncoderFallback enc, DecoderFallback dec)
			: base(codepage, enc, dec)
		{
			dataTableCodePage = dataCodePage;
			LoadCodePageTables();
		}

		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			throw new PlatformNotSupportedException();
		}

		private unsafe static void ReadCodePageDataFileHeader(Stream stream, byte[] codePageDataFileHeader)
		{
			int num = stream.Read(codePageDataFileHeader, 0, codePageDataFileHeader.Length);
			if (BitConverter.IsLittleEndian)
			{
				return;
			}
			fixed (byte* ptr = &codePageDataFileHeader[0])
			{
				CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr;
				char* ptr3 = &ptr2->TableName;
				for (int i = 0; i < 16; i++)
				{
					ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]);
				}
				ushort* ptr4 = &ptr2->Version;
				for (int j = 0; j < 4; j++)
				{
					ptr4[j] = BinaryPrimitives.ReverseEndianness(ptr4[j]);
				}
				ptr2->CodePageCount = BinaryPrimitives.ReverseEndianness(ptr2->CodePageCount);
			}
		}

		private unsafe static void ReadCodePageIndex(Stream stream, byte[] codePageIndex)
		{
			int num = stream.Read(codePageIndex, 0, codePageIndex.Length);
			if (BitConverter.IsLittleEndian)
			{
				return;
			}
			fixed (byte* ptr = &codePageIndex[0])
			{
				CodePageIndex* ptr2 = (CodePageIndex*)ptr;
				char* ptr3 = &ptr2->CodePageName;
				for (int i = 0; i < 16; i++)
				{
					ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]);
				}
				ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage);
				ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount);
				ptr2->Offset = BinaryPrimitives.ReverseEndianness(ptr2->Offset);
			}
		}

		private unsafe static void ReadCodePageHeader(Stream stream, byte[] codePageHeader)
		{
			int num = stream.Read(codePageHeader, 0, codePageHeader.Length);
			if (BitConverter.IsLittleEndian)
			{
				return;
			}
			fixed (byte* ptr = &codePageHeader[0])
			{
				CodePageHeader* ptr2 = (CodePageHeader*)ptr;
				char* ptr3 = &ptr2->CodePageName;
				for (int i = 0; i < 16; i++)
				{
					ptr3[i] = (char)BinaryPrimitives.ReverseEndianness(ptr3[i]);
				}
				ptr2->VersionMajor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMajor);
				ptr2->VersionMinor = BinaryPrimitives.ReverseEndianness(ptr2->VersionMinor);
				ptr2->VersionRevision = BinaryPrimitives.ReverseEndianness(ptr2->VersionRevision);
				ptr2->VersionBuild = BinaryPrimitives.ReverseEndianness(ptr2->VersionBuild);
				ptr2->CodePage = BinaryPrimitives.ReverseEndianness(ptr2->CodePage);
				ptr2->ByteCount = BinaryPrimitives.ReverseEndianness(ptr2->ByteCount);
				ptr2->UnicodeReplace = (char)BinaryPrimitives.ReverseEndianness(ptr2->UnicodeReplace);
				ptr2->ByteReplace = BinaryPrimitives.ReverseEndianness(ptr2->ByteReplace);
			}
		}

		internal static Stream GetEncodingDataStream(string tableName)
		{
			Stream manifestResourceStream = typeof(CodePagesEncodingProvider).Assembly.GetManifestResourceStream(tableName);
			if (manifestResourceStream == null)
			{
				throw new InvalidOperationException();
			}
			ReadCodePageDataFileHeader(manifestResourceStream, s_codePagesDataHeader);
			return manifestResourceStream;
		}

		private void LoadCodePageTables()
		{
			if (!FindCodePage(dataTableCodePage))
			{
				throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage));
			}
			LoadManagedCodePage();
		}

		private unsafe bool FindCodePage(int codePage)
		{
			byte[] array = new byte[sizeof(CodePageIndex)];
			lock (s_streamLock)
			{
				s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin);
				int codePageCount;
				fixed (byte* ptr = &s_codePagesDataHeader[0])
				{
					CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr;
					codePageCount = ptr2->CodePageCount;
				}
				fixed (byte* ptr3 = &array[0])
				{
					CodePageIndex* ptr4 = (CodePageIndex*)ptr3;
					for (int i = 0; i < codePageCount; i++)
					{
						ReadCodePageIndex(s_codePagesEncodingDataStream, array);
						if (ptr4->CodePage == codePage)
						{
							long position = s_codePagesEncodingDataStream.Position;
							s_codePagesEncodingDataStream.Seek(ptr4->Offset, SeekOrigin.Begin);
							ReadCodePageHeader(s_codePagesEncodingDataStream, m_codePageHeader);
							m_firstDataWordOffset = (int)s_codePagesEncodingDataStream.Position;
							if (i == codePageCount - 1)
							{
								m_dataSize = (int)(s_codePagesEncodingDataStream.Length - ptr4->Offset - m_codePageHeader.Length);
							}
							else
							{
								s_codePagesEncodingDataStream.Seek(position, SeekOrigin.Begin);
								int offset = ptr4->Offset;
								ReadCodePageIndex(s_codePagesEncodingDataStream, array);
								m_dataSize = ptr4->Offset - offset - m_codePageHeader.Length;
							}
							return true;
						}
					}
				}
			}
			return false;
		}

		internal unsafe static int GetCodePageByteSize(int codePage)
		{
			byte[] array = new byte[sizeof(CodePageIndex)];
			lock (s_streamLock)
			{
				s_codePagesEncodingDataStream.Seek(44L, SeekOrigin.Begin);
				int codePageCount;
				fixed (byte* ptr = &s_codePagesDataHeader[0])
				{
					CodePageDataFileHeader* ptr2 = (CodePageDataFileHeader*)ptr;
					codePageCount = ptr2->CodePageCount;
				}
				fixed (byte* ptr3 = &array[0])
				{
					CodePageIndex* ptr4 = (CodePageIndex*)ptr3;
					for (int i = 0; i < codePageCount; i++)
					{
						ReadCodePageIndex(s_codePagesEncodingDataStream, array);
						if (ptr4->CodePage == codePage)
						{
							return ptr4->ByteCount;
						}
					}
				}
			}
			return 0;
		}

		protected abstract void LoadManagedCodePage();

		protected unsafe byte* GetNativeMemory(int iSize)
		{
			if (safeNativeMemoryHandle == null)
			{
				byte* ptr = (byte*)(void*)Marshal.AllocHGlobal(iSize);
				safeNativeMemoryHandle = new SafeAllocHHandle((IntPtr)ptr);
			}
			return (byte*)(void*)safeNativeMemoryHandle.DangerousGetHandle();
		}

		protected abstract void ReadBestFitTable();

		internal char[] GetBestFitUnicodeToBytesData()
		{
			if (arrayUnicodeBestFit == null)
			{
				ReadBestFitTable();
			}
			return arrayUnicodeBestFit;
		}

		internal char[] GetBestFitBytesToUnicodeData()
		{
			if (arrayBytesBestFit == null)
			{
				ReadBestFitTable();
			}
			return arrayBytesBestFit;
		}

		internal void CheckMemorySection()
		{
			if (safeNativeMemoryHandle != null && safeNativeMemoryHandle.DangerousGetHandle() == IntPtr.Zero)
			{
				LoadManagedCodePage();
			}
		}
	}
	public sealed class CodePagesEncodingProvider : EncodingProvider
	{
		private static readonly EncodingProvider s_singleton = new CodePagesEncodingProvider();

		private readonly Dictionary<int, Encoding> _encodings = new Dictionary<int, Encoding>();

		private readonly ReaderWriterLockSlim _cacheLock = new ReaderWriterLockSlim();

		private const int ISCIIAssemese = 57006;

		private const int ISCIIBengali = 57003;

		private const int ISCIIDevanagari = 57002;

		private const int ISCIIGujarathi = 57010;

		private const int ISCIIKannada = 57008;

		private const int ISCIIMalayalam = 57009;

		private const int ISCIIOriya = 57007;

		private const int ISCIIPanjabi = 57011;

		private const int ISCIITamil = 57004;

		private const int ISCIITelugu = 57005;

		private const int ISOKorean = 50225;

		private const int ChineseHZ = 52936;

		private const int ISO2022JP = 50220;

		private const int ISO2022JPESC = 50221;

		private const int ISO2022JPSISO = 50222;

		private const int ISOSimplifiedCN = 50227;

		private const int EUCJP = 51932;

		private const int CodePageMacGB2312 = 10008;

		private const int CodePageMacKorean = 10003;

		private const int CodePageGB2312 = 20936;

		private const int CodePageDLLKorean = 20949;

		private const int GB18030 = 54936;

		private const int DuplicateEUCCN = 51936;

		private const int EUCKR = 51949;

		private const int EUCCN = 936;

		private const int ISO_8859_8I = 38598;

		private const int ISO_8859_8_Visual = 28598;

		public static EncodingProvider Instance => s_singleton;

		private static int SystemDefaultCodePage => 0;

		internal CodePagesEncodingProvider()
		{
		}

		public override Encoding? GetEncoding(int codepage)
		{
			if (codepage < 0 || codepage > 65535)
			{
				return null;
			}
			if (codepage == 0)
			{
				int systemDefaultCodePage = SystemDefaultCodePage;
				if (systemDefaultCodePage == 0)
				{
					return null;
				}
				return GetEncoding(systemDefaultCodePage);
			}
			Encoding value = null;
			_cacheLock.EnterUpgradeableReadLock();
			try
			{
				if (_encodings.TryGetValue(codepage, out value))
				{
					return value;
				}
				switch (BaseCodePageEncoding.GetCodePageByteSize(codepage))
				{
				case 1:
					value = new SBCSCodePageEncoding(codepage);
					break;
				case 2:
					value = new DBCSCodePageEncoding(codepage);
					break;
				default:
					value = GetEncodingRare(codepage);
					if (value == null)
					{
						return null;
					}
					break;
				}
				_cacheLock.EnterWriteLock();
				try
				{
					if (_encodings.TryGetValue(codepage, out var value2))
					{
						return value2;
					}
					_encodings.Add(codepage, value);
					return value;
				}
				finally
				{
					_cacheLock.ExitWriteLock();
				}
			}
			finally
			{
				_cacheLock.ExitUpgradeableReadLock();
			}
		}

		public override Encoding? GetEncoding(string name)
		{
			int codePageFromName = System.Text.EncodingTable.GetCodePageFromName(name);
			if (codePageFromName == 0)
			{
				return null;
			}
			return GetEncoding(codePageFromName);
		}

		private static Encoding GetEncodingRare(int codepage)
		{
			Encoding result = null;
			switch (codepage)
			{
			case 57002:
			case 57003:
			case 57004:
			case 57005:
			case 57006:
			case 57007:
			case 57008:
			case 57009:
			case 57010:
			case 57011:
				result = new ISCIIEncoding(codepage);
				break;
			case 10008:
				result = new DBCSCodePageEncoding(10008, 20936);
				break;
			case 10003:
				result = new DBCSCodePageEncoding(10003, 20949);
				break;
			case 54936:
				result = new GB18030Encoding();
				break;
			case 50220:
			case 50221:
			case 50222:
			case 50225:
			case 52936:
				result = new ISO2022Encoding(codepage);
				break;
			case 50227:
			case 51936:
				result = new DBCSCodePageEncoding(codepage, 936);
				break;
			case 51932:
				result = new EUCJPEncoding();
				break;
			case 51949:
				result = new DBCSCodePageEncoding(codepage, 20949);
				break;
			case 38598:
				result = new SBCSCodePageEncoding(codepage, 28598);
				break;
			}
			return result;
		}
	}
	internal class DBCSCodePageEncoding : BaseCodePageEncoding
	{
		internal sealed class DBCSDecoder : System.Text.DecoderNLS
		{
			internal byte bLeftOver;

			internal override bool HasState => bLeftOver != 0;

			public DBCSDecoder(DBCSCodePageEncoding encoding)
				: base(encoding)
			{
			}

			public override void Reset()
			{
				bLeftOver = 0;
				m_fallbackBuffer?.Reset();
			}
		}

		protected unsafe char* mapBytesToUnicode = null;

		protected unsafe ushort* mapUnicodeToBytes = null;

		protected const char UNKNOWN_CHAR_FLAG = '\0';

		protected const char UNICODE_REPLACEMENT_CHAR = '\ufffd';

		protected const char LEAD_BYTE_CHAR = '\ufffe';

		private ushort _bytesUnknown;

		private int _byteCountUnknown;

		protected char charUnknown;

		private static object s_InternalSyncObject;

		private static object InternalSyncObject
		{
			get
			{
				if (s_InternalSyncObject == null)
				{
					object value = new object();
					Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null);
				}
				return s_InternalSyncObject;
			}
		}

		public DBCSCodePageEncoding(int codePage)
			: this(codePage, codePage)
		{
		}

		internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage)
			: base(codePage, dataCodePage)
		{
		}

		internal unsafe DBCSCodePageEncoding(int codePage, int dataCodePage, EncoderFallback enc, DecoderFallback dec)
			: base(codePage, dataCodePage, enc, dec)
		{
		}

		internal unsafe static char ReadChar(char* pChar)
		{
			if (BitConverter.IsLittleEndian)
			{
				return *pChar;
			}
			return (char)BinaryPrimitives.ReverseEndianness(*pChar);
		}

		protected unsafe override void LoadManagedCodePage()
		{
			fixed (byte* ptr = &m_codePageHeader[0])
			{
				CodePageHeader* ptr2 = (CodePageHeader*)ptr;
				if (ptr2->ByteCount != 2)
				{
					throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage));
				}
				_bytesUnknown = ptr2->ByteReplace;
				charUnknown = ptr2->UnicodeReplace;
				if (base.DecoderFallback is InternalDecoderBestFitFallback)
				{
					((InternalDecoderBestFitFallback)base.DecoderFallback).cReplacement = charUnknown;
				}
				_byteCountUnknown = 1;
				if (_bytesUnknown > 255)
				{
					_byteCountUnknown++;
				}
				int num = 262148 + iExtraBytes;
				byte* nativeMemory = GetNativeMemory(num);
				Unsafe.InitBlockUnaligned(nativeMemory, 0, (uint)num);
				mapBytesToUnicode = (char*)nativeMemory;
				mapUnicodeToBytes = (ushort*)(nativeMemory + 131072);
				byte[] array = new byte[m_dataSize];
				lock (BaseCodePageEncoding.s_streamLock)
				{
					BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
					int num2 = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize);
				}
				fixed (byte* ptr3 = array)
				{
					char* ptr4 = (char*)ptr3;
					int num3 = 0;
					int num4 = 0;
					while (num3 < 65536)
					{
						char c = ReadChar(ptr4);
						ptr4++;
						switch (c)
						{
						case '\u0001':
							num3 = ReadChar(ptr4);
							ptr4++;
							continue;
						case '\u0002':
						case '\u0003':
						case '\u0004':
						case '\u0005':
						case '\u0006':
						case '\a':
						case '\b':
						case '\t':
						case '\n':
						case '\v':
						case '\f':
						case '\r':
						case '\u000e':
						case '\u000f':
						case '\u0010':
						case '\u0011':
						case '\u0012':
						case '\u0013':
						case '\u0014':
						case '\u0015':
						case '\u0016':
						case '\u0017':
						case '\u0018':
						case '\u0019':
						case '\u001a':
						case '\u001b':
						case '\u001c':
						case '\u001d':
						case '\u001e':
						case '\u001f':
							num3 += c;
							continue;
						}
						switch (c)
						{
						case '\uffff':
							num4 = num3;
							c = (char)num3;
							break;
						case '\ufffe':
							num4 = num3;
							break;
						case '\ufffd':
							num3++;
							continue;
						default:
							num4 = num3;
							break;
						}
						if (CleanUpBytes(ref num4))
						{
							if (c != '\ufffe')
							{
								mapUnicodeToBytes[(int)c] = (ushort)num4;
							}
							mapBytesToUnicode[num4] = c;
						}
						num3++;
					}
				}
				CleanUpEndBytes(mapBytesToUnicode);
			}
		}

		protected virtual bool CleanUpBytes(ref int bytes)
		{
			return true;
		}

		protected unsafe virtual void CleanUpEndBytes(char* chars)
		{
		}

		protected unsafe override void ReadBestFitTable()
		{
			lock (InternalSyncObject)
			{
				if (arrayUnicodeBestFit != null)
				{
					return;
				}
				byte[] array = new byte[m_dataSize];
				lock (BaseCodePageEncoding.s_streamLock)
				{
					BaseCodePageEncoding.s_codePagesEncodingDataStream.Seek(m_firstDataWordOffset, SeekOrigin.Begin);
					int num = BaseCodePageEncoding.s_codePagesEncodingDataStream.Read(array, 0, m_dataSize);
				}
				fixed (byte* ptr = array)
				{
					char* ptr2 = (char*)ptr;
					int num2 = 0;
					while (num2 < 65536)
					{
						char c = ReadChar(ptr2);
						ptr2++;
						switch (c)
						{
						case '\u0001':
							num2 = ReadChar(ptr2);
							ptr2++;
							break;
						case '\u0002':
						case '\u0003':
						case '\u0004':
						case '\u0005':
						case '\u0006':
						case '\a':
						case '\b':
						case '\t':
						case '\n':
						case '\v':
						case '\f':
						case '\r':
						case '\u000e':
						case '\u000f':
						case '\u0010':
						case '\u0011':
						case '\u0012':
						case '\u0013':
						case '\u0014':
						case '\u0015':
						case '\u0016':
						case '\u0017':
						case '\u0018':
						case '\u0019':
						case '\u001a':
						case '\u001b':
						case '\u001c':
						case '\u001d':
						case '\u001e':
						case '\u001f':
							num2 += c;
							break;
						default:
							num2++;
							break;
						}
					}
					char* ptr3 = ptr2;
					int num3 = 0;
					num2 = ReadChar(ptr2);
					ptr2++;
					while (num2 < 65536)
					{
						char c2 = ReadChar(ptr2);
						ptr2++;
						switch (c2)
						{
						case '\u0001':
							num2 = ReadChar(ptr2);
							ptr2++;
							continue;
						case '\u0002':
						case '\u0003':
						case '\u0004':
						case '\u0005':
						case '\u0006':
						case '\a':
						case '\b':
						case '\t':
						case '\n':
						case '\v':
						case '\f':
						case '\r':
						case '\u000e':
						case '\u000f':
						case '\u0010':
						case '\u0011':
						case '\u0012':
						case '\u0013':
						case '\u0014':
						case '\u0015':
						case '\u0016':
						case '\u0017':
						case '\u0018':
						case '\u0019':
						case '\u001a':
						case '\u001b':
						case '\u001c':
						case '\u001d':
						case '\u001e':
						case '\u001f':
							num2 += c2;
							continue;
						}
						if (c2 != '\ufffd')
						{
							int bytes = num2;
							if (CleanUpBytes(ref bytes) && mapBytesToUnicode[bytes] != c2)
							{
								num3++;
							}
						}
						num2++;
					}
					char[] array2 = new char[num3 * 2];
					num3 = 0;
					ptr2 = ptr3;
					num2 = ReadChar(ptr2);
					ptr2++;
					bool flag = false;
					while (num2 < 65536)
					{
						char c3 = ReadChar(ptr2);
						ptr2++;
						switch (c3)
						{
						case '\u0001':
							num2 = ReadChar(ptr2);
							ptr2++;
							continue;
						case '\u0002':
						case '\u0003':
						case '\u0004':
						case '\u0005':
						case '\u0006':
						case '\a':
						case '\b':
						case '\t':
						case '\n':
						case '\v':
						case '\f':
						case '\r':
						case '\u000e':
						case '\u000f':
						case '\u0010':
						case '\u0011':
						case '\u0012':
						case '\u0013':
						case '\u0014':
						case '\u0015':
						case '\u0016':
						case '\u0017':
						case '\u0018':
						case '\u0019':
						case '\u001a':
						case '\u001b':
						case '\u001c':
						case '\u001d':
						case '\u001e':
						case '\u001f':
							num2 += c3;
							continue;
						}
						if (c3 != '\ufffd')
						{
							int bytes2 = num2;
							if (CleanUpBytes(ref bytes2) && mapBytesToUnicode[bytes2] != c3)
							{
								if (bytes2 != num2)
								{
									flag = true;
								}
								array2[num3++] = (char)bytes2;
								array2[num3++] = c3;
							}
						}
						num2++;
					}
					if (flag)
					{
						for (int i = 0; i < array2.Length - 2; i += 2)
						{
							int num4 = i;
							char c4 = array2[i];
							for (int j = i + 2; j < array2.Length; j += 2)
							{
								if (c4 > array2[j])
								{
									c4 = array2[j];
									num4 = j;
								}
							}
							if (num4 != i)
							{
								char c5 = array2[num4];
								array2[num4] = array2[i];
								array2[i] = c5;
								c5 = array2[num4 + 1];
								array2[num4 + 1] = array2[i + 1];
								array2[i + 1] = c5;
							}
						}
					}
					arrayBytesBestFit = array2;
					char* ptr4 = ptr2;
					int num5 = ReadChar(ptr2++);
					num3 = 0;
					while (num5 < 65536)
					{
						char c6 = ReadChar(ptr2);
						ptr2++;
						switch (c6)
						{
						case '\u0001':
							num5 = ReadChar(ptr2);
							ptr2++;
							continue;
						case '\u0002':
						case '\u0003':
						case '\u0004':
						case '\u0005':
						case '\u0006':
						case '\a':
						case '\b':
						case '\t':
						case '\n':
						case '\v':
						case '\f':
						case '\r':
						case '\u000e':
						case '\u000f':
						case '\u0010':
						case '\u0011':
						case '\u0012':
						case '\u0013':
						case '\u0014':
						case '\u0015':
						case '\u0016':
						case '\u0017':
						case '\u0018':
						case '\u0019':
						case '\u001a':
						case '\u001b':
						case '\u001c':
						case '\u001d':
						case '\u001e':
						case '\u001f':
							num5 += c6;
							continue;
						}
						if (c6 > '\0')
						{
							num3++;
						}
						num5++;
					}
					array2 = new char[num3 * 2];
					ptr2 = ptr4;
					num5 = ReadChar(ptr2++);
					num3 = 0;
					while (num5 < 65536)
					{
						char c7 = ReadChar(ptr2);
						ptr2++;
						switch (c7)
						{
						case '\u0001':
							num5 = ReadChar(ptr2);
							ptr2++;
							continue;
						case '\u0002':
						case '\u0003':
						case '\u0004':
						case '\u0005':
						case '\u0006':
						case '\a':
						case '\b':
						case '\t':
						case '\n':
						case '\v':
						case '\f':
						case '\r':
						case '\u000e':
						case '\u000f':
						case '\u0010':
						case '\u0011':
						case '\u0012':
						case '\u0013':
						case '\u0014':
						case '\u0015':
						case '\u0016':
						case '\u0017':
						case '\u0018':
						case '\u0019':
						case '\u001a':
						case '\u001b':
						case '\u001c':
						case '\u001d':
						case '\u001e':
						case '\u001f':
							num5 += c7;
							continue;
						}
						if (c7 > '\0')
						{
							int bytes3 = c7;
							if (CleanUpBytes(ref bytes3))
							{
								array2[num3++] = (char)num5;
								array2[num3++] = mapBytesToUnicode[bytes3];
							}
						}
						num5++;
					}
					arrayUnicodeBestFit = array2;
				}
			}
		}

		public unsafe override int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder)
		{
			CheckMemorySection();
			char c = '\0';
			if (encoder != null)
			{
				c = encoder.charLeftOver;
				if (encoder.InternalHasFallbackBuffer && encoder.FallbackBuffer.Remaining > 0)
				{
					throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType()));
				}
			}
			int num = 0;
			char* ptr = chars + count;
			EncoderFallbackBuffer encoderFallbackBuffer = null;
			EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer);
			if (c > '\0')
			{
				encoderFallbackBuffer = encoder.FallbackBuffer;
				encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer);
				encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: false);
				encoderFallbackBufferHelper.InternalFallback(c, ref chars);
			}
			char c2;
			while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr)
			{
				if (c2 == '\0')
				{
					c2 = *chars;
					chars++;
				}
				ushort num2 = mapUnicodeToBytes[(int)c2];
				if (num2 == 0 && c2 != 0)
				{
					if (encoderFallbackBuffer == null)
					{
						encoderFallbackBuffer = ((encoder != null) ? encoder.FallbackBuffer : base.EncoderFallback.CreateFallbackBuffer());
						encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer);
						encoderFallbackBufferHelper.InternalInitialize(ptr - count, ptr, encoder, _setEncoder: false);
					}
					encoderFallbackBufferHelper.InternalFallback(c2, ref chars);
				}
				else
				{
					num++;
					if (num2 >= 256)
					{
						num++;
					}
				}
			}
			return num;
		}

		public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder)
		{
			CheckMemorySection();
			EncoderFallbackBuffer encoderFallbackBuffer = null;
			char* ptr = chars + charCount;
			char* ptr2 = chars;
			byte* ptr3 = bytes;
			byte* ptr4 = bytes + byteCount;
			EncoderFallbackBufferHelper encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer);
			char c = '\0';
			if (encoder != null)
			{
				c = encoder.charLeftOver;
				encoderFallbackBuffer = encoder.FallbackBuffer;
				encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer);
				encoderFallbackBufferHelper.InternalInitialize(chars, ptr, encoder, _setEncoder: true);
				if (encoder.m_throwOnOverflow && encoderFallbackBuffer.Remaining > 0)
				{
					throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, EncodingName, encoder.Fallback.GetType()));
				}
				if (c > '\0')
				{
					encoderFallbackBufferHelper.InternalFallback(c, ref chars);
				}
			}
			char c2;
			while ((c2 = ((encoderFallbackBuffer != null) ? encoderFallbackBufferHelper.InternalGetNextChar() : '\0')) != 0 || chars < ptr)
			{
				if (c2 == '\0')
				{
					c2 = *chars;
					chars++;
				}
				ushort num = mapUnicodeToBytes[(int)c2];
				if (num == 0 && c2 != 0)
				{
					if (encoderFallbackBuffer == null)
					{
						encoderFallbackBuffer = base.EncoderFallback.CreateFallbackBuffer();
						encoderFallbackBufferHelper = new EncoderFallbackBufferHelper(encoderFallbackBuffer);
						encoderFallbackBufferHelper.InternalInitialize(ptr - charCount, ptr, encoder, _setEncoder: true);
					}
					encoderFallbackBufferHelper.InternalFallback(c2, ref chars);
					continue;
				}
				if (num >= 256)
				{
					if (bytes + 1 >= ptr4)
					{
						if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack)
						{
							chars--;
						}
						else
						{
							encoderFallbackBuffer.MovePrevious();
						}
						ThrowBytesOverflow(encoder, chars == ptr2);
						break;
					}
					*bytes = (byte)(num >> 8);
					bytes++;
				}
				else if (bytes >= ptr4)
				{
					if (encoderFallbackBuffer == null || !encoderFallbackBufferHelper.bFallingBack)
					{
						chars--;
					}
					else
					{
						encoderFallbackBuffer.MovePrevious();
					}
					ThrowBytesOverflow(encoder, chars == ptr2);
					break;
				}
				*bytes = (byte)(num & 0xFFu);
				bytes++;
			}
			if (encoder != null)
			{
				if (encoderFallbackBuffer != null && !encoderFallbackBufferHelper.bUsedEncoder)
				{
					encoder.charLeftOver = '\0';
				}
				encoder.m_charsUsed = (int)(chars - ptr2);
			}
			return (int)(bytes - ptr3);
		}

		public unsafe override int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS baseDecoder)
		{
			CheckMemorySection();
			DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder;
			DecoderFallbackBuffer decoderFallbackBuffer = null;
			byte* ptr = bytes + count;
			int num = count;
			DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer);
			if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0)
			{
				if (count == 0)
				{
					if (!dBCSDecoder.MustFlush)
					{
						return 0;
					}
					decoderFallbackBuffer = dBCSDecoder.FallbackBuffer;
					decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer);
					decoderFallbackBufferHelper.InternalInitialize(bytes, null);
					byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver };
					return decoderFallbackBufferHelper.InternalFallback(bytes2, bytes);
				}
				int num2 = dBCSDecoder.bLeftOver << 8;
				num2 |= *bytes;
				bytes++;
				if (mapBytesToUnicode[num2] == '\0' && num2 != 0)
				{
					num--;
					decoderFallbackBuffer = dBCSDecoder.FallbackBuffer;
					decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer);
					decoderFallbackBufferHelper.InternalInitialize(ptr - count, null);
					byte[] bytes3 = new byte[2]
					{
						(byte)(num2 >> 8),
						(byte)num2
					};
					num += decoderFallbackBufferHelper.InternalFallback(bytes3, bytes);
				}
			}
			while (bytes < ptr)
			{
				int num3 = *bytes;
				bytes++;
				char c = mapBytesToUnicode[num3];
				if (c == '\ufffe')
				{
					num--;
					if (bytes < ptr)
					{
						num3 <<= 8;
						num3 |= *bytes;
						bytes++;
						c = mapBytesToUnicode[num3];
					}
					else
					{
						if (dBCSDecoder != null && !dBCSDecoder.MustFlush)
						{
							break;
						}
						num++;
						c = '\0';
					}
				}
				if (c == '\0' && num3 != 0)
				{
					if (decoderFallbackBuffer == null)
					{
						decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer());
						decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer);
						decoderFallbackBufferHelper.InternalInitialize(ptr - count, null);
					}
					num--;
					byte[] bytes4 = ((num3 >= 256) ? new byte[2]
					{
						(byte)(num3 >> 8),
						(byte)num3
					} : new byte[1] { (byte)num3 });
					num += decoderFallbackBufferHelper.InternalFallback(bytes4, bytes);
				}
			}
			return num;
		}

		public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS baseDecoder)
		{
			CheckMemorySection();
			DBCSDecoder dBCSDecoder = (DBCSDecoder)baseDecoder;
			byte* ptr = bytes;
			byte* ptr2 = bytes + byteCount;
			char* ptr3 = chars;
			char* ptr4 = chars + charCount;
			bool flag = false;
			DecoderFallbackBuffer decoderFallbackBuffer = null;
			DecoderFallbackBufferHelper decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer);
			if (dBCSDecoder != null && dBCSDecoder.bLeftOver > 0)
			{
				if (byteCount == 0)
				{
					if (!dBCSDecoder.MustFlush)
					{
						return 0;
					}
					decoderFallbackBuffer = dBCSDecoder.FallbackBuffer;
					decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer);
					decoderFallbackBufferHelper.InternalInitialize(bytes, ptr4);
					byte[] bytes2 = new byte[1] { dBCSDecoder.bLeftOver };
					if (!decoderFallbackBufferHelper.InternalFallback(bytes2, bytes, ref chars))
					{
						ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true);
					}
					dBCSDecoder.bLeftOver = 0;
					return (int)(chars - ptr3);
				}
				int num = dBCSDecoder.bLeftOver << 8;
				num |= *bytes;
				bytes++;
				char c = mapBytesToUnicode[num];
				if (c == '\0' && num != 0)
				{
					decoderFallbackBuffer = dBCSDecoder.FallbackBuffer;
					decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer);
					decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4);
					byte[] bytes3 = new byte[2]
					{
						(byte)(num >> 8),
						(byte)num
					};
					if (!decoderFallbackBufferHelper.InternalFallback(bytes3, bytes, ref chars))
					{
						ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true);
					}
				}
				else
				{
					if (chars >= ptr4)
					{
						ThrowCharsOverflow(dBCSDecoder, nothingDecoded: true);
					}
					*(chars++) = c;
				}
			}
			while (bytes < ptr2)
			{
				int num2 = *bytes;
				bytes++;
				char c2 = mapBytesToUnicode[num2];
				if (c2 == '\ufffe')
				{
					if (bytes < ptr2)
					{
						num2 <<= 8;
						num2 |= *bytes;
						bytes++;
						c2 = mapBytesToUnicode[num2];
					}
					else
					{
						if (dBCSDecoder != null && !dBCSDecoder.MustFlush)
						{
							flag = true;
							dBCSDecoder.bLeftOver = (byte)num2;
							break;
						}
						c2 = '\0';
					}
				}
				if (c2 == '\0' && num2 != 0)
				{
					if (decoderFallbackBuffer == null)
					{
						decoderFallbackBuffer = ((dBCSDecoder != null) ? dBCSDecoder.FallbackBuffer : base.DecoderFallback.CreateFallbackBuffer());
						decoderFallbackBufferHelper = new DecoderFallbackBufferHelper(decoderFallbackBuffer);
						decoderFallbackBufferHelper.InternalInitialize(ptr2 - byteCount, ptr4);
					}
					byte[] array = ((num2 >= 256) ? new byte[2]
					{
						(byte)(num2 >> 8),
						(byte)num2
					} : new byte[1] { (byte)num2 });
					if (!decoderFallbackBufferHelper.InternalFallback(array, bytes, ref chars))
					{
						bytes -= array.Length;
						decoderFallbackBufferHelper.InternalReset();
						ThrowCharsOverflow(dBCSDecoder, bytes == ptr);
						break;
					}
					continue;
				}
				if (chars >= ptr4)
				{
					bytes--;
					if (num2 >= 256)
					{
						bytes--;
					}
					ThrowCharsOverflow(dBCSDecoder, bytes == ptr);
					break;
				}
				*(chars++) = c2;
			}
			if (dBCSDecoder != null)
			{
				if (!flag)
				{
					dBCSDecoder.bLeftOver = 0;
				}
				dBCSDecoder.m_bytesUsed = (int)(bytes - ptr);
			}
			return (int)(chars - ptr3);
		}

		public override int GetMaxByteCount(int charCount)
		{
			if (charCount < 0)
			{
				throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			long num = (long)charCount + 1L;
			if (base.EncoderFallback.MaxCharCount > 1)
			{
				num *= base.EncoderFallback.MaxCharCount;
			}
			num *= 2;
			if (num > int.MaxValue)
			{
				throw new ArgumentOutOfRangeException("charCount", System.SR.ArgumentOutOfRange_GetByteCountOverflow);
			}
			return (int)num;
		}

		public override int GetMaxCharCount(int byteCount)
		{
			if (byteCount < 0)
			{
				throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			long num = (long)byteCount + 1L;
			if (base.DecoderFallback.MaxCharCount > 1)
			{
				num *= base.DecoderFallback.MaxCharCount;
			}
			if (num > int.MaxValue)
			{
				throw new ArgumentOutOfRangeException("byteCount", System.SR.ArgumentOutOfRange_GetCharCountOverflow);
			}
			return (int)num;
		}

		public override Decoder GetDecoder()
		{
			return new DBCSDecoder(this);
		}
	}
	internal sealed class InternalDecoderBestFitFallback : DecoderFallback
	{
		internal BaseCodePageEncoding encoding;

		internal char[] arrayBestFit;

		internal char cReplacement = '?';

		public override int MaxCharCount => 1;

		internal InternalDecoderBestFitFallback(BaseCodePageEncoding _encoding)
		{
			encoding = _encoding;
		}

		public override DecoderFallbackBuffer CreateFallbackBuffer()
		{
			return new InternalDecoderBestFitFallbackBuffer(this);
		}

		public override bool Equals([NotNullWhen(true)] object value)
		{
			if (value is InternalDecoderBestFitFallback internalDecoderBestFitFallback)
			{
				return encoding.CodePage == internalDecoderBestFitFallback.encoding.CodePage;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return encoding.CodePage;
		}
	}
	internal sealed class InternalDecoderBestFitFallbackBuffer : DecoderFallbackBuffer
	{
		internal char cBestFit;

		internal int iCount = -1;

		internal int iSize;

		private readonly InternalDecoderBestFitFallback _oFallback;

		private static object s_InternalSyncObject;

		private static object InternalSyncObject
		{
			get
			{
				if (s_InternalSyncObject == null)
				{
					object value = new object();
					Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null);
				}
				return s_InternalSyncObject;
			}
		}

		public override int Remaining
		{
			get
			{
				if (iCount <= 0)
				{
					return 0;
				}
				return iCount;
			}
		}

		public InternalDecoderBestFitFallbackBuffer(InternalDecoderBestFitFallback fallback)
		{
			_oFallback = fallback;
			if (_oFallback.arrayBestFit != null)
			{
				return;
			}
			lock (InternalSyncObject)
			{
				InternalDecoderBestFitFallback oFallback = _oFallback;
				if (oFallback.arrayBestFit == null)
				{
					oFallback.arrayBestFit = fallback.encoding.GetBestFitBytesToUnicodeData();
				}
			}
		}

		public override bool Fallback(byte[] bytesUnknown, int index)
		{
			cBestFit = TryBestFit(bytesUnknown);
			if (cBestFit == '\0')
			{
				cBestFit = _oFallback.cReplacement;
			}
			iCount = (iSize = 1);
			return true;
		}

		public override char GetNextChar()
		{
			iCount--;
			if (iCount < 0)
			{
				return '\0';
			}
			if (iCount == int.MaxValue)
			{
				iCount = -1;
				return '\0';
			}
			return cBestFit;
		}

		public override bool MovePrevious()
		{
			if (iCount >= 0)
			{
				iCount++;
			}
			if (iCount >= 0)
			{
				return iCount <= iSize;
			}
			return false;
		}

		public override void Reset()
		{
			iCount = -1;
		}

		internal unsafe static int InternalFallback(byte[] bytes, byte* pBytes)
		{
			return 1;
		}

		private char TryBestFit(byte[] bytesCheck)
		{
			int num = 0;
			int num2 = _oFallback.arrayBestFit.Length;
			if (num2 == 0)
			{
				return '\0';
			}
			if (bytesCheck.Length == 0 || bytesCheck.Length > 2)
			{
				return '\0';
			}
			char c = ((bytesCheck.Length != 1) ? ((char)((bytesCheck[0] << 8) + bytesCheck[1])) : ((char)bytesCheck[0]));
			if (c < _oFallback.arrayBestFit[0] || c > _oFallback.arrayBestFit[num2 - 2])
			{
				return '\0';
			}
			int num3;
			while ((num3 = num2 - num) > 6)
			{
				int num4 = (num3 / 2 + num) & 0xFFFE;
				char c2 = _oFallback.arrayBestFit[num4];
				if (c2 == c)
				{
					return _oFallback.arrayBestFit[num4 + 1];
				}
				if (c2 < c)
				{
					num = num4;
				}
				else
				{
					num2 = num4;
				}
			}
			for (int num4 = num; num4 < num2; num4 += 2)
			{
				if (_oFallback.arrayBestFit[num4] == c)
				{
					return _oFallback.arrayBestFit[num4 + 1];
				}
			}
			return '\0';
		}
	}
	internal struct DecoderFallbackBufferHelper
	{
		internal unsafe byte* byteStart;

		internal unsafe char* charEnd;

		private readonly DecoderFallbackBuffer _fallbackBuffer;

		public unsafe DecoderFallbackBufferHelper(DecoderFallbackBuffer fallbackBuffer)
		{
			_fallbackBuffer = fallbackBuffer;
			byteStart = null;
			charEnd = null;
		}

		internal unsafe void InternalReset()
		{
			byteStart = null;
			_fallbackBuffer.Reset();
		}

		internal unsafe void InternalInitialize(byte* _byteStart, char* _charEnd)
		{
			byteStart = _byteStart;
			charEnd = _charEnd;
		}

		internal unsafe bool InternalFallback(byte[] bytes, byte* pBytes, ref char* chars)
		{
			if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
			{
				char* ptr = chars;
				bool flag = false;
				char nextChar;
				while ((nextChar = _fallbackBuffer.GetNextChar()) != 0)
				{
					if (char.IsSurrogate(nextChar))
					{
						if (char.IsHighSurrogate(nextChar))
						{
							if (flag)
							{
								throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex);
							}
							flag = true;
						}
						else
						{
							if (!flag)
							{
								throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex);
							}
							flag = false;
						}
					}
					if (ptr >= charEnd)
					{
						return false;
					}
					*(ptr++) = nextChar;
				}
				if (flag)
				{
					throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex);
				}
				chars = ptr;
			}
			return true;
		}

		internal unsafe int InternalFallback(byte[] bytes, byte* pBytes)
		{
			if (_fallbackBuffer.Fallback(bytes, (int)(pBytes - byteStart - bytes.Length)))
			{
				int num = 0;
				bool flag = false;
				char nextChar;
				while ((nextChar = _fallbackBuffer.GetNextChar()) != 0)
				{
					if (char.IsSurrogate(nextChar))
					{
						if (char.IsHighSurrogate(nextChar))
						{
							if (flag)
							{
								throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex);
							}
							flag = true;
						}
						else
						{
							if (!flag)
							{
								throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex);
							}
							flag = false;
						}
					}
					num++;
				}
				if (flag)
				{
					throw new ArgumentException(System.SR.Argument_InvalidCharSequenceNoIndex);
				}
				return num;
			}
			return 0;
		}
	}
	internal class DecoderNLS : Decoder, ISerializable
	{
		protected EncodingNLS m_encoding;

		protected bool m_mustFlush;

		internal bool m_throwOnOverflow;

		internal int m_bytesUsed;

		internal DecoderFallback m_fallback;

		internal DecoderFallbackBuffer m_fallbackBuffer;

		internal new DecoderFallback Fallback => m_fallback;

		internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null;

		public new DecoderFallbackBuffer FallbackBuffer
		{
			get
			{
				if (m_fallbackBuffer == null)
				{
					m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : DecoderFallback.ReplacementFallback.CreateFallbackBuffer());
				}
				return m_fallbackBuffer;
			}
		}

		public bool MustFlush => m_mustFlush;

		internal virtual bool HasState => false;

		internal DecoderNLS(EncodingNLS encoding)
		{
			m_encoding = encoding;
			m_fallback = m_encoding.DecoderFallback;
			Reset();
		}

		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			throw new PlatformNotSupportedException();
		}

		public override void Reset()
		{
			m_fallbackBuffer?.Reset();
		}

		public override int GetCharCount(byte[] bytes, int index, int count)
		{
			return GetCharCount(bytes, index, count, flush: false);
		}

		public unsafe override int GetCharCount(byte[] bytes, int index, int count, bool flush)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (index < 0 || count < 0)
			{
				throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (bytes.Length - index < count)
			{
				throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (bytes.Length == 0)
			{
				bytes = new byte[1];
			}
			fixed (byte* ptr = &bytes[0])
			{
				return GetCharCount(ptr + index, count, flush);
			}
		}

		public unsafe override int GetCharCount(byte* bytes, int count, bool flush)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			m_mustFlush = flush;
			m_throwOnOverflow = true;
			return m_encoding.GetCharCount(bytes, count, this);
		}

		public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
		{
			return GetChars(bytes, byteIndex, byteCount, chars, charIndex, flush: false);
		}

		public unsafe override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (byteIndex < 0 || byteCount < 0)
			{
				throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (bytes.Length - byteIndex < byteCount)
			{
				throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (charIndex < 0 || charIndex > chars.Length)
			{
				throw new ArgumentOutOfRangeException("charIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
			}
			if (bytes.Length == 0)
			{
				bytes = new byte[1];
			}
			int charCount = chars.Length - charIndex;
			if (chars.Length == 0)
			{
				chars = new char[1];
			}
			fixed (byte* ptr = &bytes[0])
			{
				fixed (char* ptr2 = &chars[0])
				{
					return GetChars(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush);
				}
			}
		}

		public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (byteCount < 0 || charCount < 0)
			{
				throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			m_mustFlush = flush;
			m_throwOnOverflow = true;
			return m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
		}

		public unsafe override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (byteIndex < 0 || byteCount < 0)
			{
				throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (charIndex < 0 || charCount < 0)
			{
				throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (bytes.Length - byteIndex < byteCount)
			{
				throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (chars.Length - charIndex < charCount)
			{
				throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (bytes.Length == 0)
			{
				bytes = new byte[1];
			}
			if (chars.Length == 0)
			{
				chars = new char[1];
			}
			fixed (byte* ptr = &bytes[0])
			{
				fixed (char* ptr2 = &chars[0])
				{
					Convert(ptr + byteIndex, byteCount, ptr2 + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed);
				}
			}
		}

		public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed)
		{
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (byteCount < 0 || charCount < 0)
			{
				throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			m_mustFlush = flush;
			m_throwOnOverflow = false;
			m_bytesUsed = 0;
			charsUsed = m_encoding.GetChars(bytes, byteCount, chars, charCount, this);
			bytesUsed = m_bytesUsed;
			completed = bytesUsed == byteCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
		}

		internal void ClearMustFlush()
		{
			m_mustFlush = false;
		}
	}
	internal sealed class InternalEncoderBestFitFallback : EncoderFallback
	{
		internal BaseCodePageEncoding encoding;

		internal char[] arrayBestFit;

		public override int MaxCharCount => 1;

		internal InternalEncoderBestFitFallback(BaseCodePageEncoding _encoding)
		{
			encoding = _encoding;
		}

		public override EncoderFallbackBuffer CreateFallbackBuffer()
		{
			return new InternalEncoderBestFitFallbackBuffer(this);
		}

		public override bool Equals([NotNullWhen(true)] object value)
		{
			if (value is InternalEncoderBestFitFallback internalEncoderBestFitFallback)
			{
				return encoding.CodePage == internalEncoderBestFitFallback.encoding.CodePage;
			}
			return false;
		}

		public override int GetHashCode()
		{
			return encoding.CodePage;
		}
	}
	internal sealed class InternalEncoderBestFitFallbackBuffer : EncoderFallbackBuffer
	{
		private char _cBestFit;

		private readonly InternalEncoderBestFitFallback _oFallback;

		private int _iCount = -1;

		private int _iSize;

		private static object s_InternalSyncObject;

		private static object InternalSyncObject
		{
			get
			{
				if (s_InternalSyncObject == null)
				{
					object value = new object();
					Interlocked.CompareExchange<object>(ref s_InternalSyncObject, value, (object)null);
				}
				return s_InternalSyncObject;
			}
		}

		public override int Remaining
		{
			get
			{
				if (_iCount <= 0)
				{
					return 0;
				}
				return _iCount;
			}
		}

		public InternalEncoderBestFitFallbackBuffer(InternalEncoderBestFitFallback fallback)
		{
			_oFallback = fallback;
			if (_oFallback.arrayBestFit != null)
			{
				return;
			}
			lock (InternalSyncObject)
			{
				InternalEncoderBestFitFallback oFallback = _oFallback;
				if (oFallback.arrayBestFit == null)
				{
					oFallback.arrayBestFit = fallback.encoding.GetBestFitUnicodeToBytesData();
				}
			}
		}

		public override bool Fallback(char charUnknown, int index)
		{
			_iCount = (_iSize = 1);
			_cBestFit = TryBestFit(charUnknown);
			if (_cBestFit == '\0')
			{
				_cBestFit = '?';
			}
			return true;
		}

		public override bool Fallback(char charUnknownHigh, char charUnknownLow, int index)
		{
			if (!char.IsHighSurrogate(charUnknownHigh))
			{
				throw new ArgumentOutOfRangeException("charUnknownHigh", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 55296, 56319));
			}
			if (!char.IsLowSurrogate(charUnknownLow))
			{
				throw new ArgumentOutOfRangeException("charUnknownLow", System.SR.Format(System.SR.ArgumentOutOfRange_Range, 56320, 57343));
			}
			_cBestFit = '?';
			_iCount = (_iSize = 2);
			return true;
		}

		public override char GetNextChar()
		{
			_iCount--;
			if (_iCount < 0)
			{
				return '\0';
			}
			if (_iCount == int.MaxValue)
			{
				_iCount = -1;
				return '\0';
			}
			return _cBestFit;
		}

		public override bool MovePrevious()
		{
			if (_iCount >= 0)
			{
				_iCount++;
			}
			if (_iCount >= 0)
			{
				return _iCount <= _iSize;
			}
			return false;
		}

		public override void Reset()
		{
			_iCount = -1;
		}

		private char TryBestFit(char cUnknown)
		{
			int num = 0;
			int num2 = _oFallback.arrayBestFit.Length;
			int num3;
			while ((num3 = num2 - num) > 6)
			{
				int num4 = (num3 / 2 + num) & 0xFFFE;
				char c = _oFallback.arrayBestFit[num4];
				if (c == cUnknown)
				{
					return _oFallback.arrayBestFit[num4 + 1];
				}
				if (c < cUnknown)
				{
					num = num4;
				}
				else
				{
					num2 = num4;
				}
			}
			for (int num4 = num; num4 < num2; num4 += 2)
			{
				if (_oFallback.arrayBestFit[num4] == cUnknown)
				{
					return _oFallback.arrayBestFit[num4 + 1];
				}
			}
			return '\0';
		}
	}
	internal struct EncoderFallbackBufferHelper
	{
		internal unsafe char* charStart;

		internal unsafe char* charEnd;

		internal System.Text.EncoderNLS encoder;

		internal bool setEncoder;

		internal bool bUsedEncoder;

		internal bool bFallingBack;

		internal int iRecursionCount;

		private const int iMaxRecursion = 250;

		private readonly EncoderFallbackBuffer _fallbackBuffer;

		public unsafe EncoderFallbackBufferHelper(EncoderFallbackBuffer fallbackBuffer)
		{
			_fallbackBuffer = fallbackBuffer;
			bFallingBack = (bUsedEncoder = (setEncoder = false));
			iRecursionCount = 0;
			charEnd = (charStart = null);
			encoder = null;
		}

		internal unsafe void InternalReset()
		{
			charStart = null;
			bFallingBack = false;
			iRecursionCount = 0;
			_fallbackBuffer.Reset();
		}

		internal unsafe void InternalInitialize(char* _charStart, char* _charEnd, System.Text.EncoderNLS _encoder, bool _setEncoder)
		{
			charStart = _charStart;
			charEnd = _charEnd;
			encoder = _encoder;
			setEncoder = _setEncoder;
			bUsedEncoder = false;
			bFallingBack = false;
			iRecursionCount = 0;
		}

		internal char InternalGetNextChar()
		{
			char nextChar = _fallbackBuffer.GetNextChar();
			bFallingBack = nextChar != '\0';
			if (nextChar == '\0')
			{
				iRecursionCount = 0;
			}
			return nextChar;
		}

		internal unsafe bool InternalFallback(char ch, ref char* chars)
		{
			int index = (int)(chars - charStart) - 1;
			if (char.IsHighSurrogate(ch))
			{
				if (chars >= charEnd)
				{
					if (encoder != null && !encoder.MustFlush)
					{
						if (setEncoder)
						{
							bUsedEncoder = true;
							encoder.charLeftOver = ch;
						}
						bFallingBack = false;
						return false;
					}
				}
				else
				{
					char c = *chars;
					if (char.IsLowSurrogate(c))
					{
						if (bFallingBack && iRecursionCount++ > 250)
						{
							ThrowLastCharRecursive(char.ConvertToUtf32(ch, c));
						}
						chars++;
						bFallingBack = _fallbackBuffer.Fallback(ch, c, index);
						return bFallingBack;
					}
				}
			}
			if (bFallingBack && iRecursionCount++ > 250)
			{
				ThrowLastCharRecursive(ch);
			}
			bFallingBack = _fallbackBuffer.Fallback(ch, index);
			return bFallingBack;
		}

		internal static void ThrowLastCharRecursive(int charRecursive)
		{
			throw new ArgumentException(System.SR.Format(System.SR.Argument_RecursiveFallback, charRecursive), "chars");
		}
	}
	internal class EncoderNLS : Encoder, ISerializable
	{
		internal char charLeftOver;

		protected EncodingNLS m_encoding;

		protected bool m_mustFlush;

		internal bool m_throwOnOverflow;

		internal int m_charsUsed;

		internal EncoderFallback m_fallback;

		internal EncoderFallbackBuffer m_fallbackBuffer;

		internal new EncoderFallback Fallback => m_fallback;

		internal bool InternalHasFallbackBuffer => m_fallbackBuffer != null;

		public new EncoderFallbackBuffer FallbackBuffer
		{
			get
			{
				if (m_fallbackBuffer == null)
				{
					m_fallbackBuffer = ((m_fallback != null) ? m_fallback.CreateFallbackBuffer() : EncoderFallback.ReplacementFallback.CreateFallbackBuffer());
				}
				return m_fallbackBuffer;
			}
		}

		public Encoding Encoding => m_encoding;

		public bool MustFlush => m_mustFlush;

		internal virtual bool HasState => charLeftOver != '\0';

		internal EncoderNLS(EncodingNLS encoding)
		{
			m_encoding = encoding;
			m_fallback = m_encoding.EncoderFallback;
			Reset();
		}

		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			throw new PlatformNotSupportedException();
		}

		public override void Reset()
		{
			charLeftOver = '\0';
			m_fallbackBuffer?.Reset();
		}

		public unsafe override int GetByteCount(char[] chars, int index, int count, bool flush)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (index < 0 || count < 0)
			{
				throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (chars.Length - index < count)
			{
				throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (chars.Length == 0)
			{
				chars = new char[1];
			}
			int num = -1;
			fixed (char* ptr = &chars[0])
			{
				num = GetByteCount(ptr + index, count, flush);
			}
			return num;
		}

		public unsafe override int GetByteCount(char* chars, int count, bool flush)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			m_mustFlush = flush;
			m_throwOnOverflow = true;
			return m_encoding.GetByteCount(chars, count, this);
		}

		public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, bool flush)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (charIndex < 0 || charCount < 0)
			{
				throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (chars.Length - charIndex < charCount)
			{
				throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (byteIndex < 0 || byteIndex > bytes.Length)
			{
				throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
			}
			if (chars.Length == 0)
			{
				chars = new char[1];
			}
			int byteCount = bytes.Length - byteIndex;
			if (bytes.Length == 0)
			{
				bytes = new byte[1];
			}
			fixed (char* ptr = &chars[0])
			{
				fixed (byte* ptr2 = &bytes[0])
				{
					return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush);
				}
			}
		}

		public unsafe override int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, bool flush)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (byteCount < 0 || charCount < 0)
			{
				throw new ArgumentOutOfRangeException((byteCount < 0) ? "byteCount" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			m_mustFlush = flush;
			m_throwOnOverflow = true;
			return m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
		}

		public unsafe override void Convert(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (charIndex < 0 || charCount < 0)
			{
				throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (byteIndex < 0 || byteCount < 0)
			{
				throw new ArgumentOutOfRangeException((byteIndex < 0) ? "byteIndex" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (chars.Length - charIndex < charCount)
			{
				throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (bytes.Length - byteIndex < byteCount)
			{
				throw new ArgumentOutOfRangeException("bytes", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (chars.Length == 0)
			{
				chars = new char[1];
			}
			if (bytes.Length == 0)
			{
				bytes = new byte[1];
			}
			fixed (char* ptr = &chars[0])
			{
				fixed (byte* ptr2 = &bytes[0])
				{
					Convert(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, flush, out charsUsed, out bytesUsed, out completed);
				}
			}
		}

		public unsafe override void Convert(char* chars, int charCount, byte* bytes, int byteCount, bool flush, out int charsUsed, out int bytesUsed, out bool completed)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (charCount < 0 || byteCount < 0)
			{
				throw new ArgumentOutOfRangeException((charCount < 0) ? "charCount" : "byteCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			m_mustFlush = flush;
			m_throwOnOverflow = false;
			m_charsUsed = 0;
			bytesUsed = m_encoding.GetBytes(chars, charCount, bytes, byteCount, this);
			charsUsed = m_charsUsed;
			completed = charsUsed == charCount && (!flush || !HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0);
		}

		internal void ClearMustFlush()
		{
			m_mustFlush = false;
		}
	}
	internal sealed class EncodingByteBuffer
	{
		private unsafe byte* _bytes;

		private unsafe readonly byte* _byteStart;

		private unsafe readonly byte* _byteEnd;

		private unsafe char* _chars;

		private unsafe readonly char* _charStart;

		private unsafe readonly char* _charEnd;

		private int _byteCountResult;

		private readonly EncodingNLS _enc;

		private readonly System.Text.EncoderNLS _encoder;

		internal EncoderFallbackBuffer fallbackBuffer;

		internal EncoderFallbackBufferHelper fallbackBufferHelper;

		internal unsafe bool MoreData
		{
			get
			{
				if (fallbackBuffer.Remaining <= 0)
				{
					return _chars < _charEnd;
				}
				return true;
			}
		}

		internal unsafe int CharsUsed => (int)(_chars - _charStart);

		internal int Count => _byteCountResult;

		internal unsafe EncodingByteBuffer(EncodingNLS inEncoding, System.Text.EncoderNLS inEncoder, byte* inByteStart, int inByteCount, char* inCharStart, int inCharCount)
		{
			_enc = inEncoding;
			_encoder = inEncoder;
			_charStart = inCharStart;
			_chars = inCharStart;
			_charEnd = inCharStart + inCharCount;
			_bytes = inByteStart;
			_byteStart = inByteStart;
			_byteEnd = inByteStart + inByteCount;
			if (_encoder == null)
			{
				fallbackBuffer = _enc.EncoderFallback.CreateFallbackBuffer();
			}
			else
			{
				fallbackBuffer = _encoder.FallbackBuffer;
				if (_encoder.m_throwOnOverflow && _encoder.InternalHasFallbackBuffer && fallbackBuffer.Remaining > 0)
				{
					throw new ArgumentException(System.SR.Format(System.SR.Argument_EncoderFallbackNotEmpty, _encoder.Encoding.EncodingName, _encoder.Fallback.GetType()));
				}
			}
			fallbackBufferHelper = new EncoderFallbackBufferHelper(fallbackBuffer);
			fallbackBufferHelper.InternalInitialize(_chars, _charEnd, _encoder, _bytes != null);
		}

		internal unsafe bool AddByte(byte b, int moreBytesExpected)
		{
			if (_bytes != null)
			{
				if (_bytes >= _byteEnd - moreBytesExpected)
				{
					MovePrevious(bThrow: true);
					return false;
				}
				*(_bytes++) = b;
			}
			_byteCountResult++;
			return true;
		}

		internal bool AddByte(byte b1)
		{
			return AddByte(b1, 0);
		}

		internal bool AddByte(byte b1, byte b2)
		{
			return AddByte(b1, b2, 0);
		}

		internal bool AddByte(byte b1, byte b2, int moreBytesExpected)
		{
			if (AddByte(b1, 1 + moreBytesExpected))
			{
				return AddByte(b2, moreBytesExpected);
			}
			return false;
		}

		internal bool AddByte(byte b1, byte b2, byte b3)
		{
			return AddByte(b1, b2, b3, 0);
		}

		internal bool AddByte(byte b1, byte b2, byte b3, int moreBytesExpected)
		{
			if (AddByte(b1, 2 + moreBytesExpected) && AddByte(b2, 1 + moreBytesExpected))
			{
				return AddByte(b3, moreBytesExpected);
			}
			return false;
		}

		internal bool AddByte(byte b1, byte b2, byte b3, byte b4)
		{
			if (AddByte(b1, 3) && AddByte(b2, 2) && AddByte(b3, 1))
			{
				return AddByte(b4, 0);
			}
			return false;
		}

		internal unsafe void MovePrevious(bool bThrow)
		{
			if (fallbackBufferHelper.bFallingBack)
			{
				fallbackBuffer.MovePrevious();
			}
			else if (_chars > _charStart)
			{
				_chars--;
			}
			if (bThrow)
			{
				_enc.ThrowBytesOverflow(_encoder, _bytes == _byteStart);
			}
		}

		internal unsafe bool Fallback(char charFallback)
		{
			return fallbackBufferHelper.InternalFallback(charFallback, ref _chars);
		}

		internal unsafe char GetNextChar()
		{
			char c = fallbackBufferHelper.InternalGetNextChar();
			if (c == '\0' && _chars < _charEnd)
			{
				c = *(_chars++);
			}
			return c;
		}
	}
	internal sealed class EncodingCharBuffer
	{
		private unsafe char* _chars;

		private unsafe readonly char* _charStart;

		private unsafe readonly char* _charEnd;

		private int _charCountResult;

		private readonly EncodingNLS _enc;

		private readonly System.Text.DecoderNLS _decoder;

		private unsafe readonly byte* _byteStart;

		private unsafe readonly byte* _byteEnd;

		private unsafe byte* _bytes;

		private readonly DecoderFallbackBuffer _fallbackBuffer;

		private DecoderFallbackBufferHelper _fallbackBufferHelper;

		internal unsafe bool MoreData => _bytes < _byteEnd;

		internal unsafe int BytesUsed => (int)(_bytes - _byteStart);

		internal int Count => _charCountResult;

		internal unsafe EncodingCharBuffer(EncodingNLS enc, System.Text.DecoderNLS decoder, char* charStart, int charCount, byte* byteStart, int byteCount)
		{
			_enc = enc;
			_decoder = decoder;
			_chars = charStart;
			_charStart = charStart;
			_charEnd = charStart + charCount;
			_byteStart = byteStart;
			_bytes = byteStart;
			_byteEnd = byteStart + byteCount;
			if (_decoder == null)
			{
				_fallbackBuffer = enc.DecoderFallback.CreateFallbackBuffer();
			}
			else
			{
				_fallbackBuffer = _decoder.FallbackBuffer;
			}
			_fallbackBufferHelper = new DecoderFallbackBufferHelper(_fallbackBuffer);
			_fallbackBufferHelper.InternalInitialize(_bytes, _charEnd);
		}

		internal unsafe bool AddChar(char ch, int numBytes)
		{
			if (_chars != null)
			{
				if (_chars >= _charEnd)
				{
					_bytes -= numBytes;
					_enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart);
					return false;
				}
				*(_chars++) = ch;
			}
			_charCountResult++;
			return true;
		}

		internal bool AddChar(char ch)
		{
			return AddChar(ch, 1);
		}

		internal unsafe bool AddChar(char ch1, char ch2, int numBytes)
		{
			if (_chars >= _charEnd - 1)
			{
				_bytes -= numBytes;
				_enc.ThrowCharsOverflow(_decoder, _bytes <= _byteStart);
				return false;
			}
			if (AddChar(ch1, numBytes))
			{
				return AddChar(ch2, numBytes);
			}
			return false;
		}

		internal unsafe void AdjustBytes(int count)
		{
			_bytes += count;
		}

		internal unsafe bool EvenMoreData(int count)
		{
			return _bytes <= _byteEnd - count;
		}

		internal unsafe byte GetNextByte()
		{
			if (_bytes >= _byteEnd)
			{
				return 0;
			}
			return *(_bytes++);
		}

		internal bool Fallback(byte fallbackByte)
		{
			byte[] byteBuffer = new byte[1] { fallbackByte };
			return Fallback(byteBuffer);
		}

		internal bool Fallback(byte byte1, byte byte2)
		{
			byte[] byteBuffer = new byte[2] { byte1, byte2 };
			return Fallback(byteBuffer);
		}

		internal bool Fallback(byte byte1, byte byte2, byte byte3, byte byte4)
		{
			byte[] byteBuffer = new byte[4] { byte1, byte2, byte3, byte4 };
			return Fallback(byteBuffer);
		}

		internal unsafe bool Fallback(byte[] byteBuffer)
		{
			if (_chars != null)
			{
				char* chars = _chars;
				if (!_fallbackBufferHelper.InternalFallback(byteBuffer, _bytes, ref _chars))
				{
					_bytes -= byteBuffer.Length;
					_fallbackBufferHelper.InternalReset();
					_enc.ThrowCharsOverflow(_decoder, _chars == _charStart);
					return false;
				}
				_charCountResult += (int)(_chars - chars);
			}
			else
			{
				_charCountResult += _fallbackBufferHelper.InternalFallback(byteBuffer, _bytes);
			}
			return true;
		}
	}
	internal abstract class EncodingNLS : Encoding
	{
		private string _encodingName;

		private string _webName;

		public override string EncodingName
		{
			get
			{
				if (_encodingName == null)
				{
					_encodingName = GetLocalizedEncodingNameResource(CodePage);
					if (_encodingName == null)
					{
						throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage));
					}
					if (_encodingName.StartsWith("Globalization_cp_", StringComparison.OrdinalIgnoreCase))
					{
						_encodingName = System.Text.EncodingTable.GetEnglishNameFromCodePage(CodePage);
						if (_encodingName == null)
						{
							throw new NotSupportedException(System.SR.Format(System.SR.MissingEncodingNameResource, WebName, CodePage));
						}
					}
				}
				return _encodingName;
			}
		}

		public override string WebName
		{
			get
			{
				if (_webName == null)
				{
					_webName = System.Text.EncodingTable.GetWebNameFromCodePage(CodePage);
					if (_webName == null)
					{
						throw new NotSupportedException(System.SR.Format(System.SR.NotSupported_NoCodepageData, CodePage));
					}
				}
				return _webName;
			}
		}

		public override string HeaderName => CodePage switch
		{
			932 => "iso-2022-jp", 
			50221 => "iso-2022-jp", 
			50225 => "euc-kr", 
			_ => WebName, 
		};

		public override string BodyName => CodePage switch
		{
			932 => "iso-2022-jp", 
			1250 => "iso-8859-2", 
			1251 => "koi8-r", 
			1252 => "iso-8859-1", 
			1253 => "iso-8859-7", 
			1254 => "iso-8859-9", 
			50221 => "iso-2022-jp", 
			50225 => "iso-2022-kr", 
			_ => WebName, 
		};

		protected EncodingNLS(int codePage)
			: base(codePage)
		{
		}

		protected EncodingNLS(int codePage, EncoderFallback enc, DecoderFallback dec)
			: base(codePage, enc, dec)
		{
		}

		public unsafe abstract int GetByteCount(char* chars, int count, System.Text.EncoderNLS encoder);

		public unsafe abstract int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, System.Text.EncoderNLS encoder);

		public unsafe abstract int GetCharCount(byte* bytes, int count, System.Text.DecoderNLS decoder);

		public unsafe abstract int GetChars(byte* bytes, int byteCount, char* chars, int charCount, System.Text.DecoderNLS decoder);

		public unsafe override int GetByteCount(char[] chars, int index, int count)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (index < 0 || count < 0)
			{
				throw new ArgumentOutOfRangeException((index < 0) ? "index" : "count", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (chars.Length - index < count)
			{
				throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (chars.Length == 0)
			{
				return 0;
			}
			fixed (char* ptr = &chars[0])
			{
				return GetByteCount(ptr + index, count, null);
			}
		}

		public unsafe override int GetByteCount(string s)
		{
			if (s == null)
			{
				throw new ArgumentNullException("s");
			}
			fixed (char* chars = s)
			{
				return GetByteCount(chars, s.Length, null);
			}
		}

		public unsafe override int GetByteCount(char* chars, int count)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (count < 0)
			{
				throw new ArgumentOutOfRangeException("count", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			return GetByteCount(chars, count, null);
		}

		public unsafe override int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			if (s == null)
			{
				throw new ArgumentNullException("s");
			}
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (charIndex < 0 || charCount < 0)
			{
				throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (s.Length - charIndex < charCount)
			{
				throw new ArgumentOutOfRangeException("s", System.SR.ArgumentOutOfRange_IndexCount);
			}
			if (byteIndex < 0 || byteIndex > bytes.Length)
			{
				throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
			}
			int byteCount = bytes.Length - byteIndex;
			if (bytes.Length == 0)
			{
				bytes = new byte[1];
			}
			fixed (char* ptr = s)
			{
				fixed (byte* ptr2 = &bytes[0])
				{
					return GetBytes(ptr + charIndex, charCount, ptr2 + byteIndex, byteCount, null);
				}
			}
		}

		public unsafe override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
		{
			if (chars == null)
			{
				throw new ArgumentNullException("chars");
			}
			if (bytes == null)
			{
				throw new ArgumentNullException("bytes");
			}
			if (charIndex < 0 || charCount < 0)
			{
				throw new ArgumentOutOfRangeException((charIndex < 0) ? "charIndex" : "charCount", System.SR.ArgumentOutOfRange_NeedNonNegNum);
			}
			if (chars.Length - charIndex < charCount)
			{
				throw new ArgumentOutOfRangeException("chars", System.SR.ArgumentOutOfRange_IndexCountBuffer);
			}
			if (byteIndex < 0 || byteIndex > bytes.Length)
			{
				throw new ArgumentOutOfRangeException("byteIndex", System.SR.ArgumentOutOfRange_IndexMustBeLessOrEqual);
			}
			if (chars.Length == 0)
			{
				return 0;
			}
			int byteCount = bytes.Length - byteIndex;
			if (bytes.Length == 0)
			{
				bytes = new byte[1];
			}
			fixed (char* ptr = &chars[0])
			{
				fixed (byte* ptr2 

BepInEx/core/System.Text.Encodings.Web.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.Unicode;
using System.Threading;
using FxResources.System.Text.Encodings.Web;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Text.Encodings.Web")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides types for encoding and escaping strings for use in JavaScript, HyperText Markup Language (HTML), and uniform resource locators (URL).\r\n\r\nCommonly Used Types:\r\nSystem.Text.Encodings.Web.HtmlEncoder\r\nSystem.Text.Encodings.Web.UrlEncoder\r\nSystem.Text.Encodings.Web.JavaScriptEncoder")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Text.Encodings.Web")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("10.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NativeIntegerAttribute : Attribute
	{
		public readonly bool[] TransformFlags;

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

		public NativeIntegerAttribute(bool[] P_0)
		{
			TransformFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.System.Text.Encodings.Web
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		private ref struct SpanCasingPair
		{
			public ReadOnlySpan<byte> Bytes { get; set; }

			public Casing Casing { get; set; }
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf8(ReadOnlySpan<byte> source, Span<byte> utf8Destination, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < source.Length; i++)
			{
				ToBytesBuffer(source[i], utf8Destination, i * 2, casing);
			}
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> source, Span<char> destination, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < source.Length; i++)
			{
				ToCharsBuffer(source[i], destination, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf8(ReadOnlySpan<byte> utf8Source, Span<byte> destination, out int bytesProcessed)
		{
			return TryDecodeFromUtf8_Scalar(utf8Source, destination, out bytesProcessed);
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> source, Span<byte> destination, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(source, destination, out charsProcessed);
		}

		private static bool TryDecodeFromUtf8_Scalar(ReadOnlySpan<byte> utf8Source, Span<byte> destination, out int bytesProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < destination.Length)
			{
				num3 = FromChar(utf8Source[num + 1]);
				num4 = FromChar(utf8Source[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				destination[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			bytesProcessed = num;
			return (num3 | num4) != 255;
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> source, Span<byte> destination, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < destination.Length)
			{
				num3 = FromChar(source[num + 1]);
				num4 = FromChar(source[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				destination[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class ThrowHelper
	{
		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException()
		{
			throw new ArgumentOutOfRangeException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_DestinationTooShort()
		{
			throw new ArgumentException(System.SR.Argument_DestinationTooShort, "destination");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_CannotExtractScalar(System.ExceptionArgument argument)
		{
			throw GetArgumentException(System.ExceptionResource.Argument_CannotExtractScalar, argument);
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRange_IndexMustBeLessException()
		{
			throw GetArgumentOutOfRangeException(System.ExceptionArgument.index, System.ExceptionResource.ArgumentOutOfRange_IndexMustBeLess);
		}

		[DoesNotReturn]
		internal static void ThrowArgumentNullException(System.ExceptionArgument argument)
		{
			throw new ArgumentNullException(GetArgumentName(argument));
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			throw new ArgumentOutOfRangeException(GetArgumentName(argument));
		}

		private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(System.ExceptionArgument argument, System.ExceptionResource resource)
		{
			return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource));
		}

		private static ArgumentException GetArgumentException(System.ExceptionResource resource, System.ExceptionArgument argument)
		{
			return new ArgumentException(GetResourceString(resource), GetArgumentName(argument));
		}

		private static string GetArgumentName(System.ExceptionArgument argument)
		{
			return argument switch
			{
				System.ExceptionArgument.ch => "ch", 
				System.ExceptionArgument.culture => "culture", 
				System.ExceptionArgument.index => "index", 
				System.ExceptionArgument.input => "input", 
				System.ExceptionArgument.value => "value", 
				_ => "", 
			};
		}

		private static string GetResourceString(System.ExceptionResource resource)
		{
			return resource switch
			{
				System.ExceptionResource.ArgumentOutOfRange_IndexMustBeLess => System.SR.ArgumentOutOfRange_IndexMustBeLess, 
				System.ExceptionResource.Argument_CannotExtractScalar => System.SR.Argument_CannotExtractScalar, 
				_ => "", 
			};
		}
	}
	internal enum ExceptionArgument
	{
		ch,
		culture,
		index,
		input,
		value
	}
	internal enum ExceptionResource
	{
		Argument_CannotExtractScalar,
		ArgumentOutOfRange_IndexMustBeLess
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess");

		internal static string Argument_CannotExtractScalar => GetResourceString("Argument_CannotExtractScalar");

		internal static string Argument_DestinationTooShort => GetResourceString("Argument_DestinationTooShort");

		internal static string Arg_MustBeRune => GetResourceString("Arg_MustBeRune");

		internal static string TextEncoderDoesNotImplementMaxOutputCharsPerInputChar => GetResourceString("TextEncoderDoesNotImplementMaxOutputCharsPerInputChar");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Numerics
{
	internal static class BitOperations
	{
		private static ReadOnlySpan<byte> Log2DeBruijn => new byte[32]
		{
			0, 9, 1, 10, 13, 21, 2, 29, 11, 14,
			16, 18, 22, 25, 3, 30, 8, 12, 20, 28,
			15, 17, 24, 7, 19, 27, 23, 6, 26, 5,
			4, 31
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int Log2(uint value)
		{
			return Log2SoftwareFallback(value | 1u);
		}

		private static int Log2SoftwareFallback(uint value)
		{
			value |= value >> 1;
			value |= value >> 2;
			value |= value >> 4;
			value |= value >> 8;
			value |= value >> 16;
			return Unsafe.AddByteOffset(ref MemoryMarshal.GetReference(Log2DeBruijn), (nint)(value * 130329821 >> 27));
		}
	}
}
namespace System.Text
{
	internal static class UnicodeDebug
	{
		[Conditional("DEBUG")]
		internal static void AssertIsBmpCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsBmpCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsHighSurrogateCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsHighSurrogateCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsLowSurrogateCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsLowSurrogateCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidCodePoint(uint codePoint)
		{
			System.Text.UnicodeUtility.IsValidCodePoint(codePoint);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidScalar(uint scalarValue)
		{
			System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue);
		}

		[Conditional("DEBUG")]
		internal static void AssertIsValidSupplementaryPlaneScalar(uint scalarValue)
		{
			if (System.Text.UnicodeUtility.IsValidUnicodeScalar(scalarValue))
			{
				System.Text.UnicodeUtility.IsBmpCodePoint(scalarValue);
			}
		}

		private static string ToHexString(uint codePoint)
		{
			return FormattableString.Invariant($"U+{codePoint:X4}");
		}
	}
	internal static class UnicodeUtility
	{
		public const uint ReplacementChar = 65533u;

		public static int GetPlane(uint codePoint)
		{
			return (int)(codePoint >> 16);
		}

		public static uint GetScalarFromUtf16SurrogatePair(uint highSurrogateCodePoint, uint lowSurrogateCodePoint)
		{
			return (highSurrogateCodePoint << 10) + lowSurrogateCodePoint - 56613888;
		}

		public static int GetUtf16SequenceLength(uint value)
		{
			value -= 65536;
			value += 33554432;
			value >>= 24;
			return (int)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void GetUtf16SurrogatesFromSupplementaryPlaneScalar(uint value, out char highSurrogateCodePoint, out char lowSurrogateCodePoint)
		{
			highSurrogateCodePoint = (char)(value + 56557568 >> 10);
			lowSurrogateCodePoint = (char)((value & 0x3FF) + 56320);
		}

		public static int GetUtf8SequenceLength(uint value)
		{
			int num = (int)(value - 2048) >> 31;
			value ^= 0xF800u;
			value -= 63616;
			value += 67108864;
			value >>= 24;
			return (int)value + num * 2;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsAsciiCodePoint(uint value)
		{
			return value <= 127;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsBmpCodePoint(uint value)
		{
			return value <= 65535;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHighSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 55296u, 56319u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsInRangeInclusive(uint value, uint lowerBound, uint upperBound)
		{
			return value - lowerBound <= upperBound - lowerBound;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsLowSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 56320u, 57343u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsSurrogateCodePoint(uint value)
		{
			return IsInRangeInclusive(value, 55296u, 57343u);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsValidCodePoint(uint codePoint)
		{
			return codePoint <= 1114111;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsValidUnicodeScalar(uint value)
		{
			return ((value - 1114112) ^ 0xD800) >= 4293855232u;
		}
	}
	internal ref struct ValueStringBuilder
	{
		private char[] _arrayToReturnToPool;

		private Span<char> _chars;

		private int _pos;

		public int Length
		{
			get
			{
				return _pos;
			}
			set
			{
				_pos = value;
			}
		}

		public int Capacity => _chars.Length;

		public ref char this[int index] => ref _chars[index];

		public Span<char> RawChars => _chars;

		public ValueStringBuilder(Span<char> initialBuffer)
		{
			_arrayToReturnToPool = null;
			_chars = initialBuffer;
			_pos = 0;
		}

		public ValueStringBuilder(int initialCapacity)
		{
			_arrayToReturnToPool = ArrayPool<char>.Shared.Rent(initialCapacity);
			_chars = _arrayToReturnToPool;
			_pos = 0;
		}

		public void EnsureCapacity(int capacity)
		{
			if ((uint)capacity > (uint)_chars.Length)
			{
				Grow(capacity - _pos);
			}
		}

		public ref char GetPinnableReference()
		{
			return ref MemoryMarshal.GetReference(_chars);
		}

		public ref char GetPinnableReference(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return ref MemoryMarshal.GetReference(_chars);
		}

		public override string ToString()
		{
			string result = _chars.Slice(0, _pos).ToString();
			Dispose();
			return result;
		}

		public ReadOnlySpan<char> AsSpan(bool terminate)
		{
			if (terminate)
			{
				EnsureCapacity(Length + 1);
				_chars[Length] = '\0';
			}
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan()
		{
			return _chars.Slice(0, _pos);
		}

		public ReadOnlySpan<char> AsSpan(int start)
		{
			return _chars.Slice(start, _pos - start);
		}

		public ReadOnlySpan<char> AsSpan(int start, int length)
		{
			return _chars.Slice(start, length);
		}

		public bool TryCopyTo(Span<char> destination, out int charsWritten)
		{
			if (_chars.Slice(0, _pos).TryCopyTo(destination))
			{
				charsWritten = _pos;
				Dispose();
				return true;
			}
			charsWritten = 0;
			Dispose();
			return false;
		}

		public void Insert(int index, char value, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			int length = _pos - index;
			_chars.Slice(index, length).CopyTo(_chars.Slice(index + count));
			_chars.Slice(index, count).Fill(value);
			_pos += count;
		}

		public void Insert(int index, string s)
		{
			if (s != null)
			{
				int length = s.Length;
				if (_pos > _chars.Length - length)
				{
					Grow(length);
				}
				int length2 = _pos - index;
				_chars.Slice(index, length2).CopyTo(_chars.Slice(index + length));
				s.AsSpan().CopyTo(_chars.Slice(index));
				_pos += length;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(char c)
		{
			int pos = _pos;
			Span<char> chars = _chars;
			if ((uint)pos < (uint)chars.Length)
			{
				chars[pos] = c;
				_pos = pos + 1;
			}
			else
			{
				GrowAndAppend(c);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Append(string s)
		{
			if (s != null)
			{
				int pos = _pos;
				if (s.Length == 1 && (uint)pos < (uint)_chars.Length)
				{
					_chars[pos] = s[0];
					_pos = pos + 1;
				}
				else
				{
					AppendSlow(s);
				}
			}
		}

		private void AppendSlow(string s)
		{
			int pos = _pos;
			if (pos > _chars.Length - s.Length)
			{
				Grow(s.Length);
			}
			s.AsSpan().CopyTo(_chars.Slice(pos));
			_pos += s.Length;
		}

		public void Append(char c, int count)
		{
			if (_pos > _chars.Length - count)
			{
				Grow(count);
			}
			Span<char> span = _chars.Slice(_pos, count);
			for (int i = 0; i < span.Length; i++)
			{
				span[i] = c;
			}
			_pos += count;
		}

		public void Append(scoped ReadOnlySpan<char> value)
		{
			if (_pos > _chars.Length - value.Length)
			{
				Grow(value.Length);
			}
			value.CopyTo(_chars.Slice(_pos));
			_pos += value.Length;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public Span<char> AppendSpan(int length)
		{
			int pos = _pos;
			if (pos > _chars.Length - length)
			{
				Grow(length);
			}
			_pos = pos + length;
			return _chars.Slice(pos, length);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void GrowAndAppend(char c)
		{
			Grow(1);
			Append(c);
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private void Grow(int additionalCapacityBeyondPos)
		{
			int minimumLength = (int)Math.Max((uint)(_pos + additionalCapacityBeyondPos), Math.Min((uint)(_chars.Length * 2), 2147483591u));
			char[] array = ArrayPool<char>.Shared.Rent(minimumLength);
			_chars.Slice(0, _pos).CopyTo(array);
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			_chars = (_arrayToReturnToPool = array);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public void Dispose()
		{
			char[] arrayToReturnToPool = _arrayToReturnToPool;
			this = default(System.Text.ValueStringBuilder);
			if (arrayToReturnToPool != null)
			{
				ArrayPool<char>.Shared.Return(arrayToReturnToPool);
			}
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	internal readonly struct Rune : IComparable, IComparable<Rune>, IEquatable<Rune>
	{
		internal const int MaxUtf16CharsPerRune = 2;

		internal const int MaxUtf8BytesPerRune = 4;

		private const char HighSurrogateStart = '\ud800';

		private const char LowSurrogateStart = '\udc00';

		private const int HighSurrogateRange = 1023;

		private const byte IsWhiteSpaceFlag = 128;

		private const byte IsLetterOrDigitFlag = 64;

		private const byte UnicodeCategoryMask = 31;

		private readonly uint _value;

		private static ReadOnlySpan<byte> AsciiCharInfo => new byte[128]
		{
			14, 14, 14, 14, 14, 14, 14, 14, 14, 142,
			142, 142, 142, 142, 14, 14, 14, 14, 14, 14,
			14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
			14, 14, 139, 24, 24, 24, 26, 24, 24, 24,
			20, 21, 24, 25, 24, 19, 24, 24, 72, 72,
			72, 72, 72, 72, 72, 72, 72, 72, 24, 24,
			25, 25, 25, 24, 24, 64, 64, 64, 64, 64,
			64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
			64, 64, 64, 64, 64, 64, 64, 64, 64, 64,
			64, 20, 24, 21, 27, 18, 27, 65, 65, 65,
			65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
			65, 65, 65, 65, 65, 65, 65, 65, 65, 65,
			65, 65, 65, 20, 25, 21, 25, 14
		};

		private string DebuggerDisplay => FormattableString.Invariant(FormattableStringFactory.Create("U+{0:X4} '{1}'", _value, IsValid(_value) ? ToString() : "\ufffd"));

		public bool IsAscii => System.Text.UnicodeUtility.IsAsciiCodePoint(_value);

		public bool IsBmp => System.Text.UnicodeUtility.IsBmpCodePoint(_value);

		public int Plane => System.Text.UnicodeUtility.GetPlane(_value);

		public static Rune ReplacementChar => UnsafeCreate(65533u);

		public int Utf16SequenceLength => System.Text.UnicodeUtility.GetUtf16SequenceLength(_value);

		public int Utf8SequenceLength => System.Text.UnicodeUtility.GetUtf8SequenceLength(_value);

		public int Value => (int)_value;

		public Rune(char ch)
		{
			if (System.Text.UnicodeUtility.IsSurrogateCodePoint(ch))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.ch);
			}
			_value = ch;
		}

		public Rune(char highSurrogate, char lowSurrogate)
			: this((uint)char.ConvertToUtf32(highSurrogate, lowSurrogate), _: false)
		{
		}

		public Rune(int value)
			: this((uint)value)
		{
		}

		[CLSCompliant(false)]
		public Rune(uint value)
		{
			if (!System.Text.UnicodeUtility.IsValidUnicodeScalar(value))
			{
				System.ThrowHelper.ThrowArgumentOutOfRangeException(System.ExceptionArgument.value);
			}
			_value = value;
		}

		private Rune(uint scalarValue, bool _)
		{
			_value = scalarValue;
		}

		public static bool operator ==(Rune left, Rune right)
		{
			return left._value == right._value;
		}

		public static bool operator !=(Rune left, Rune right)
		{
			return left._value != right._value;
		}

		public static bool operator <(Rune left, Rune right)
		{
			return left._value < right._value;
		}

		public static bool operator <=(Rune left, Rune right)
		{
			return left._value <= right._value;
		}

		public static bool operator >(Rune left, Rune right)
		{
			return left._value > right._value;
		}

		public static bool operator >=(Rune left, Rune right)
		{
			return left._value >= right._value;
		}

		public static explicit operator Rune(char ch)
		{
			return new Rune(ch);
		}

		[CLSCompliant(false)]
		public static explicit operator Rune(uint value)
		{
			return new Rune(value);
		}

		public static explicit operator Rune(int value)
		{
			return new Rune(value);
		}

		private static Rune ChangeCaseCultureAware(Rune rune, CultureInfo culture, bool toUpper)
		{
			Span<char> span = stackalloc char[2];
			Span<char> destination = stackalloc char[2];
			int length = rune.EncodeToUtf16(span);
			span = span.Slice(0, length);
			destination = destination.Slice(0, length);
			if (toUpper)
			{
				MemoryExtensions.ToUpper(span, destination, culture);
			}
			else
			{
				MemoryExtensions.ToLower(span, destination, culture);
			}
			if (rune.IsBmp)
			{
				return UnsafeCreate(destination[0]);
			}
			return UnsafeCreate(System.Text.UnicodeUtility.GetScalarFromUtf16SurrogatePair(destination[0], destination[1]));
		}

		public int CompareTo(Rune other)
		{
			return Value - other.Value;
		}

		public static OperationStatus DecodeFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed)
		{
			if (!source.IsEmpty)
			{
				char c = source[0];
				if (TryCreate(c, out result))
				{
					charsConsumed = 1;
					return OperationStatus.Done;
				}
				if (source.Length > 1)
				{
					char lowSurrogate = source[1];
					if (TryCreate(c, lowSurrogate, out result))
					{
						charsConsumed = 2;
						return OperationStatus.Done;
					}
				}
				else if (char.IsHighSurrogate(c))
				{
					goto IL_004c;
				}
				charsConsumed = 1;
				result = ReplacementChar;
				return OperationStatus.InvalidData;
			}
			goto IL_004c;
			IL_004c:
			charsConsumed = source.Length;
			result = ReplacementChar;
			return OperationStatus.NeedMoreData;
		}

		public static OperationStatus DecodeFromUtf8(ReadOnlySpan<byte> source, out Rune result, out int bytesConsumed)
		{
			int num = 0;
			if (source.IsEmpty)
			{
				goto IL_0153;
			}
			uint num2 = source[0];
			if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2))
			{
				bytesConsumed = 1;
				result = UnsafeCreate(num2);
				return OperationStatus.Done;
			}
			num = 1;
			if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 194u, 244u))
			{
				num2 = num2 - 194 << 6;
				if (source.Length <= 1)
				{
					goto IL_0153;
				}
				int num3 = (sbyte)source[1];
				if (num3 < -64)
				{
					num2 += (uint)num3;
					num2 += 128;
					num2 += 128;
					if (num2 < 2048)
					{
						goto IL_0140;
					}
					if (System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2080u, 3343u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 2912u, 2943u) && !System.Text.UnicodeUtility.IsInRangeInclusive(num2, 3072u, 3087u))
					{
						num = 2;
						if (source.Length <= 2)
						{
							goto IL_0153;
						}
						num3 = (sbyte)source[2];
						if (num3 < -64)
						{
							num2 <<= 6;
							num2 += (uint)num3;
							num2 += 128;
							num2 -= 131072;
							if (num2 > 65535)
							{
								num = 3;
								if (source.Length <= 3)
								{
									goto IL_0153;
								}
								num3 = (sbyte)source[3];
								if (num3 >= -64)
								{
									goto IL_0163;
								}
								num2 <<= 6;
								num2 += (uint)num3;
								num2 += 128;
								num2 -= 4194304;
							}
							goto IL_0140;
						}
					}
				}
			}
			goto IL_0163;
			IL_0140:
			bytesConsumed = num + 1;
			result = UnsafeCreate(num2);
			return OperationStatus.Done;
			IL_0163:
			bytesConsumed = num;
			result = ReplacementChar;
			return OperationStatus.InvalidData;
			IL_0153:
			bytesConsumed = num;
			result = ReplacementChar;
			return OperationStatus.NeedMoreData;
		}

		public static OperationStatus DecodeLastFromUtf16(ReadOnlySpan<char> source, out Rune result, out int charsConsumed)
		{
			int num = source.Length - 1;
			if ((uint)num < (uint)source.Length)
			{
				char c = source[num];
				if (TryCreate(c, out result))
				{
					charsConsumed = 1;
					return OperationStatus.Done;
				}
				if (char.IsLowSurrogate(c))
				{
					num--;
					if ((uint)num < (uint)source.Length && TryCreate(source[num], c, out result))
					{
						charsConsumed = 2;
						return OperationStatus.Done;
					}
					charsConsumed = 1;
					result = ReplacementChar;
					return OperationStatus.InvalidData;
				}
			}
			charsConsumed = -source.Length >>> 31;
			result = ReplacementChar;
			return OperationStatus.NeedMoreData;
		}

		public static OperationStatus DecodeLastFromUtf8(ReadOnlySpan<byte> source, out Rune value, out int bytesConsumed)
		{
			int num = source.Length - 1;
			if ((uint)num < (uint)source.Length)
			{
				uint num2 = source[num];
				if (System.Text.UnicodeUtility.IsAsciiCodePoint(num2))
				{
					bytesConsumed = 1;
					value = UnsafeCreate(num2);
					return OperationStatus.Done;
				}
				if (((byte)num2 & 0x40u) != 0)
				{
					return DecodeFromUtf8(source.Slice(num), out value, out bytesConsumed);
				}
				int num3 = 3;
				OperationStatus result2;
				Rune result;
				int bytesConsumed2;
				while (true)
				{
					if (num3 > 0)
					{
						num--;
						if ((uint)num < (uint)source.Length)
						{
							if ((sbyte)source[num] < -64)
							{
								num3--;
								continue;
							}
							source = source.Slice(num);
							result2 = DecodeFromUtf8(source, out result, out bytesConsumed2);
							if (bytesConsumed2 == source.Length)
							{
								break;
							}
						}
					}
					value = ReplacementChar;
					bytesConsumed = 1;
					return OperationStatus.InvalidData;
				}
				bytesConsumed = bytesConsumed2;
				value = result;
				return result2;
			}
			value = ReplacementChar;
			bytesConsumed = 0;
			return OperationStatus.NeedMoreData;
		}

		public int EncodeToUtf16(Span<char> destination)
		{
			if (!TryEncodeToUtf16(destination, out var charsWritten))
			{
				System.ThrowHelper.ThrowArgumentException_DestinationTooShort();
			}
			return charsWritten;
		}

		public int EncodeToUtf8(Span<byte> destination)
		{
			if (!TryEncodeToUtf8(destination, out var bytesWritten))
			{
				System.ThrowHelper.ThrowArgumentException_DestinationTooShort();
			}
			return bytesWritten;
		}

		public override bool Equals([NotNullWhen(true)] object obj)
		{
			if (obj is Rune other)
			{
				return Equals(other);
			}
			return false;
		}

		public bool Equals(Rune other)
		{
			return this == other;
		}

		public override int GetHashCode()
		{
			return Value;
		}

		public static bool IsValid(int value)
		{
			return IsValid((uint)value);
		}

		[CLSCompliant(false)]
		public static bool IsValid(uint value)
		{
			return System.Text.UnicodeUtility.IsValidUnicodeScalar(value);
		}

		internal static int ReadFirstRuneFromUtf16Buffer(ReadOnlySpan<char> input)
		{
			if (input.IsEmpty)
			{
				return -1;
			}
			uint num = input[0];
			if (System.Text.UnicodeUtility.IsSurrogateCodePoint(num))
			{
				if (!System.Text.UnicodeUtility.IsHighSurrogateCodePoint(num))
				{
					return -1;
				}
				if (input.Length <= 1)
				{
					return -1;
				}
				uint num2 = input[1];
				if (!System.Text.UnicodeUtility.IsLowSurrogateCodePoint(num2))
				{
					return -1;
				}
				num = System.Text.UnicodeUtility.GetScalarFromUtf16SurrogatePair(num, num2);
			}
			return (int)num;
		}

		public override string ToString()
		{
			if (IsBmp)
			{
				return ((char)_value).ToString();
			}
			Span<char> span = stackalloc char[2];
			System.Text.UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(_value, out span[0], out span[1]);
			return span.ToString();
		}

		public static bool TryCreate(char ch, out Rune result)
		{
			if (!System.Text.UnicodeUtility.IsSurrogateCodePoint(ch))
			{
				result = UnsafeCreate(ch);
				return true;
			}
			result = default(Rune);
			return false;
		}

		public static bool TryCreate(char highSurrogate, char lowSurrogate, out Rune result)
		{
			uint num = (uint)(highSurrogate - 55296);
			uint num2 = (uint)(lowSurrogate - 56320);
			if ((num | num2) <= 1023)
			{
				result = UnsafeCreate((uint)((int)(num << 10) + (lowSurrogate - 56320) + 65536));
				return true;
			}
			result = default(Rune);
			return false;
		}

		public static bool TryCreate(int value, out Rune result)
		{
			return TryCreate((uint)value, out result);
		}

		[CLSCompliant(false)]
		public static bool TryCreate(uint value, out Rune result)
		{
			if (System.Text.UnicodeUtility.IsValidUnicodeScalar(value))
			{
				result = UnsafeCreate(value);
				return true;
			}
			result = default(Rune);
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool TryEncodeToUtf16(Span<char> destination, out int charsWritten)
		{
			return TryEncodeToUtf16(this, destination, out charsWritten);
		}

		private static bool TryEncodeToUtf16(Rune value, Span<char> destination, out int charsWritten)
		{
			if (!destination.IsEmpty)
			{
				if (value.IsBmp)
				{
					destination[0] = (char)value._value;
					charsWritten = 1;
					return true;
				}
				if (destination.Length > 1)
				{
					System.Text.UnicodeUtility.GetUtf16SurrogatesFromSupplementaryPlaneScalar(value._value, out destination[0], out destination[1]);
					charsWritten = 2;
					return true;
				}
			}
			charsWritten = 0;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public bool TryEncodeToUtf8(Span<byte> destination, out int bytesWritten)
		{
			return TryEncodeToUtf8(this, destination, out bytesWritten);
		}

		private static bool TryEncodeToUtf8(Rune value, Span<byte> destination, out int bytesWritten)
		{
			if (!destination.IsEmpty)
			{
				if (value.IsAscii)
				{
					destination[0] = (byte)value._value;
					bytesWritten = 1;
					return true;
				}
				if (destination.Length > 1)
				{
					if ((long)value.Value <= 2047L)
					{
						destination[0] = (byte)(value._value + 12288 >> 6);
						destination[1] = (byte)((value._value & 0x3F) + 128);
						bytesWritten = 2;
						return true;
					}
					if (destination.Length > 2)
					{
						if ((long)value.Value <= 65535L)
						{
							destination[0] = (byte)(value._value + 917504 >> 12);
							destination[1] = (byte)(((value._value & 0xFC0) >> 6) + 128);
							destination[2] = (byte)((value._value & 0x3F) + 128);
							bytesWritten = 3;
							return true;
						}
						if (destination.Length > 3)
						{
							destination[0] = (byte)(value._value + 62914560 >> 18);
							destination[1] = (byte)(((value._value & 0x3F000) >> 12) + 128);
							destination[2] = (byte)(((value._value & 0xFC0) >> 6) + 128);
							destination[3] = (byte)((value._value & 0x3F) + 128);
							bytesWritten = 4;
							return true;
						}
					}
				}
			}
			bytesWritten = 0;
			return false;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static Rune UnsafeCreate(uint scalarValue)
		{
			return new Rune(scalarValue, _: false);
		}

		public static double GetNumericValue(Rune value)
		{
			if (value.IsAscii)
			{
				uint num = value._value - 48;
				if (num > 9)
				{
					return -1.0;
				}
				return num;
			}
			if (value.IsBmp)
			{
				return CharUnicodeInfo.GetNumericValue((char)value._value);
			}
			return CharUnicodeInfo.GetNumericValue(value.ToString(), 0);
		}

		public static UnicodeCategory GetUnicodeCategory(Rune value)
		{
			if (value.IsAscii)
			{
				return (UnicodeCategory)(AsciiCharInfo[value.Value] & 0x1F);
			}
			return GetUnicodeCategoryNonAscii(value);
		}

		private static UnicodeCategory GetUnicodeCategoryNonAscii(Rune value)
		{
			if (value.IsBmp)
			{
				return CharUnicodeInfo.GetUnicodeCategory((char)value._value);
			}
			return CharUnicodeInfo.GetUnicodeCategory(value.ToString(), 0);
		}

		private static bool IsCategoryLetter(UnicodeCategory category)
		{
			return System.Text.UnicodeUtility.IsInRangeInclusive((uint)category, 0u, 4u);
		}

		private static bool IsCategoryLetterOrDecimalDigit(UnicodeCategory category)
		{
			if (!System.Text.UnicodeUtility.IsInRangeInclusive((uint)category, 0u, 4u))
			{
				return category == UnicodeCategory.DecimalDigitNumber;
			}
			return true;
		}

		private static bool IsCategoryNumber(UnicodeCategory category)
		{
			return System.Text.UnicodeUtility.IsInRangeInclusive((uint)category, 8u, 10u);
		}

		private static bool IsCategoryPunctuation(UnicodeCategory category)
		{
			return System.Text.UnicodeUtility.IsInRangeInclusive((uint)category, 18u, 24u);
		}

		private static bool IsCategorySeparator(UnicodeCategory category)
		{
			return System.Text.UnicodeUtility.IsInRangeInclusive((uint)category, 11u, 13u);
		}

		private static bool IsCategorySymbol(UnicodeCategory category)
		{
			return System.Text.UnicodeUtility.IsInRangeInclusive((uint)category, 25u, 28u);
		}

		public static bool IsControl(Rune value)
		{
			return ((value._value + 1) & 0xFFFFFF7Fu) <= 32;
		}

		public static bool IsDigit(Rune value)
		{
			if (value.IsAscii)
			{
				return System.Text.UnicodeUtility.IsInRangeInclusive(value._value, 48u, 57u);
			}
			return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.DecimalDigitNumber;
		}

		public static bool IsLetter(Rune value)
		{
			if (value.IsAscii)
			{
				return ((value._value - 65) & 0xFFFFFFDFu) <= 25;
			}
			return IsCategoryLetter(GetUnicodeCategoryNonAscii(value));
		}

		public static bool IsLetterOrDigit(Rune value)
		{
			if (value.IsAscii)
			{
				return (AsciiCharInfo[value.Value] & 0x40) != 0;
			}
			return IsCategoryLetterOrDecimalDigit(GetUnicodeCategoryNonAscii(value));
		}

		public static bool IsLower(Rune value)
		{
			if (value.IsAscii)
			{
				return System.Text.UnicodeUtility.IsInRangeInclusive(value._value, 97u, 122u);
			}
			return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.LowercaseLetter;
		}

		public static bool IsNumber(Rune value)
		{
			if (value.IsAscii)
			{
				return System.Text.UnicodeUtility.IsInRangeInclusive(value._value, 48u, 57u);
			}
			return IsCategoryNumber(GetUnicodeCategoryNonAscii(value));
		}

		public static bool IsPunctuation(Rune value)
		{
			return IsCategoryPunctuation(GetUnicodeCategory(value));
		}

		public static bool IsSeparator(Rune value)
		{
			return IsCategorySeparator(GetUnicodeCategory(value));
		}

		public static bool IsSymbol(Rune value)
		{
			return IsCategorySymbol(GetUnicodeCategory(value));
		}

		public static bool IsUpper(Rune value)
		{
			if (value.IsAscii)
			{
				return System.Text.UnicodeUtility.IsInRangeInclusive(value._value, 65u, 90u);
			}
			return GetUnicodeCategoryNonAscii(value) == UnicodeCategory.UppercaseLetter;
		}

		public static bool IsWhiteSpace(Rune value)
		{
			if (value.IsAscii)
			{
				return (AsciiCharInfo[value.Value] & 0x80) != 0;
			}
			if (value.IsBmp)
			{
				return char.IsWhiteSpace((char)value._value);
			}
			return false;
		}

		public static Rune ToLower(Rune value, CultureInfo culture)
		{
			if (culture == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture);
			}
			return ChangeCaseCultureAware(value, culture, toUpper: false);
		}

		public static Rune ToLowerInvariant(Rune value)
		{
			if (value.IsAscii)
			{
				return UnsafeCreate(System.Text.Unicode.Utf16Utility.ConvertAllAsciiCharsInUInt32ToLowercase(value._value));
			}
			return ChangeCaseCultureAware(value, CultureInfo.InvariantCulture, toUpper: false);
		}

		public static Rune ToUpper(Rune value, CultureInfo culture)
		{
			if (culture == null)
			{
				System.ThrowHelper.ThrowArgumentNullException(System.ExceptionArgument.culture);
			}
			return ChangeCaseCultureAware(value, culture, toUpper: true);
		}

		public static Rune ToUpperInvariant(Rune value)
		{
			if (value.IsAscii)
			{
				return UnsafeCreate(System.Text.Unicode.Utf16Utility.ConvertAllAsciiCharsInUInt32ToUppercase(value._value));
			}
			return ChangeCaseCultureAware(value, CultureInfo.InvariantCulture, toUpper: true);
		}

		int IComparable.CompareTo(object obj)
		{
			if (obj == null)
			{
				return 1;
			}
			if (obj is Rune other)
			{
				return CompareTo(other);
			}
			throw new ArgumentException();
		}
	}
}
namespace System.Text.Unicode
{
	internal static class UnicodeHelpers
	{
		internal const int UNICODE_LAST_CODEPOINT = 1114111;

		private static ReadOnlySpan<byte> DefinedCharsBitmapSpan => new byte[8192]
		{
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 127, 0, 0, 0, 0,
			254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 252, 240, 215, 255, 255, 251, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 254, 255, 255, 255,
			127, 254, 255, 255, 255, 255, 255, 231, 254, 255,
			255, 255, 255, 255, 255, 0, 255, 255, 255, 135,
			31, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 191, 255, 255, 255, 255,
			255, 255, 255, 231, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 3, 0, 255, 255,
			255, 255, 255, 255, 255, 231, 255, 255, 255, 255,
			255, 63, 255, 127, 255, 255, 255, 79, 255, 7,
			255, 255, 255, 127, 131, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 239, 159, 249, 255, 255, 253,
			197, 243, 159, 121, 128, 176, 207, 255, 255, 127,
			238, 135, 249, 255, 255, 253, 109, 211, 135, 57,
			2, 94, 192, 255, 127, 0, 238, 191, 251, 255,
			255, 253, 237, 243, 191, 59, 1, 0, 207, 255,
			3, 254, 238, 159, 249, 255, 255, 253, 237, 243,
			159, 57, 224, 176, 207, 255, 255, 0, 236, 199,
			61, 214, 24, 199, 255, 195, 199, 61, 129, 0,
			192, 255, 255, 7, 255, 223, 253, 255, 255, 253,
			255, 243, 223, 61, 96, 39, 207, 255, 128, 255,
			255, 223, 253, 255, 255, 253, 239, 243, 223, 61,
			96, 96, 207, 255, 14, 0, 255, 223, 253, 255,
			255, 255, 255, 255, 223, 253, 240, 255, 207, 255,
			255, 255, 238, 255, 127, 252, 255, 255, 251, 47,
			127, 132, 95, 255, 192, 255, 28, 0, 254, 255,
			255, 255, 255, 255, 255, 135, 255, 255, 255, 15,
			0, 0, 0, 0, 214, 247, 255, 255, 175, 255,
			255, 63, 95, 127, 255, 243, 0, 0, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 254,
			255, 255, 255, 31, 254, 255, 255, 255, 255, 254,
			255, 255, 255, 223, 255, 223, 255, 7, 0, 0,
			0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 191, 32, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 61, 127, 61, 255, 255,
			255, 255, 255, 61, 255, 255, 255, 255, 61, 127,
			61, 255, 127, 255, 255, 255, 255, 255, 255, 255,
			61, 255, 255, 255, 255, 255, 255, 255, 255, 231,
			255, 255, 255, 31, 255, 255, 255, 3, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 63, 63,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			254, 255, 255, 31, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 1, 255, 255, 63, 128,
			255, 255, 127, 0, 255, 255, 15, 0, 255, 223,
			13, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 255, 3, 255, 3, 255, 255,
			255, 3, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 1, 255, 255, 255, 255, 255, 7,
			255, 255, 255, 255, 255, 255, 255, 255, 63, 0,
			255, 255, 255, 127, 255, 15, 255, 15, 241, 255,
			255, 255, 255, 63, 31, 0, 255, 255, 255, 255,
			255, 15, 255, 255, 255, 3, 255, 199, 255, 255,
			255, 255, 255, 255, 255, 207, 255, 255, 255, 255,
			255, 255, 255, 127, 255, 255, 255, 159, 255, 3,
			255, 3, 255, 63, 255, 255, 255, 127, 0, 0,
			0, 0, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 223, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 15, 240, 255, 255, 255, 255,
			255, 255, 255, 248, 255, 227, 255, 255, 255, 255,
			255, 255, 255, 7, 255, 255, 255, 255, 255, 231,
			255, 0, 255, 255, 255, 255, 255, 7, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 63, 63, 255, 255, 255, 255,
			63, 63, 255, 170, 255, 255, 255, 63, 255, 255,
			255, 255, 255, 255, 223, 255, 223, 255, 207, 239,
			255, 255, 220, 127, 0, 248, 255, 255, 255, 124,
			255, 255, 255, 255, 255, 127, 223, 255, 243, 255,
			255, 127, 255, 31, 255, 255, 255, 255, 1, 0,
			255, 255, 255, 255, 1, 0, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 15, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 3, 0, 0,
			255, 7, 0, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			207, 255, 255, 255, 191, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 15, 254,
			255, 255, 255, 255, 191, 32, 255, 255, 255, 255,
			255, 255, 255, 128, 1, 128, 255, 255, 127, 0,
			127, 127, 127, 127, 127, 127, 127, 127, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 0, 0, 0, 0, 255, 255,
			255, 251, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 15, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			63, 0, 0, 0, 255, 255, 254, 255, 255, 255,
			255, 255, 255, 255, 254, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 127, 254, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 224, 255,
			255, 255, 255, 255, 254, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 127, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 63, 128, 255, 255,
			255, 255, 255, 127, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 31, 255, 255, 255, 255,
			255, 255, 127, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 15, 0, 0,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 0, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 63,
			235, 31, 0, 0, 252, 255, 255, 255, 255, 255,
			255, 31, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 0, 255, 255, 255, 255, 255, 255, 255, 255,
			63, 192, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 15, 128,
			255, 255, 255, 31, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 191, 255, 195, 255, 255, 255, 127,
			255, 255, 255, 255, 255, 255, 127, 0, 255, 63,
			255, 243, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 7, 0, 0, 248, 255, 255,
			127, 0, 126, 126, 126, 0, 127, 127, 255, 255,
			255, 255, 255, 255, 255, 15, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 63, 255, 3, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			15, 0, 255, 255, 127, 248, 255, 255, 255, 255,
			255, 15, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
			0, 0, 0, 0, 0, 0, 0, 0, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 63, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 3, 0, 0,
			0, 0, 127, 0, 248, 224, 255, 255, 127, 95,
			219, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 7, 0, 248, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 252, 255, 255, 255, 255, 255,
			255, 128, 0, 0, 0, 0, 255, 255, 255, 255,
			255, 3, 255, 255, 255, 255, 255, 255, 247, 255,
			127, 15, 223, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 31,
			254, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 127, 252, 252, 252, 28, 127, 127,
			0, 62
		};

		internal static ReadOnlySpan<byte> GetDefinedBmpCodePointsBitmapLittleEndian()
		{
			return DefinedCharsBitmapSpan;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static void GetUtf16SurrogatePairFromAstralScalarValue(uint scalar, out char highSurrogate, out char lowSurrogate)
		{
			highSurrogate = (char)(scalar + 56557568 >> 10);
			lowSurrogate = (char)((scalar & 0x3FF) + 56320);
		}

		internal static int GetUtf8RepresentationForScalarValue(uint scalar)
		{
			if (scalar <= 127)
			{
				return (byte)scalar;
			}
			if (scalar <= 2047)
			{
				byte b = (byte)(0xC0u | (scalar >> 6));
				return ((byte)(0x80 | (scalar & 0x3F)) << 8) | b;
			}
			if (scalar <= 65535)
			{
				byte b2 = (byte)(0xE0u | (scalar >> 12));
				byte b3 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu));
				return ((((byte)(0x80 | (scalar & 0x3F)) << 8) | b3) << 8) | b2;
			}
			byte b4 = (byte)(0xF0u | (scalar >> 18));
			byte b5 = (byte)(0x80u | ((scalar >> 12) & 0x3Fu));
			byte b6 = (byte)(0x80u | ((scalar >> 6) & 0x3Fu));
			return ((((((byte)(0x80 | (scalar & 0x3F)) << 8) | b6) << 8) | b5) << 8) | b4;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		internal static bool IsSupplementaryCodePoint(int scalar)
		{
			return (scalar & -65536) != 0;
		}
	}
	public sealed class UnicodeRange
	{
		public int FirstCodePoint { get; }

		public int Length { get; }

		public UnicodeRange(int firstCodePoint, int length)
		{
			if (firstCodePoint < 0 || firstCodePoint > 65535)
			{
				throw new ArgumentOutOfRangeException("firstCodePoint");
			}
			if (length < 0 || (long)firstCodePoint + (long)length > 65536)
			{
				throw new ArgumentOutOfRangeException("length");
			}
			FirstCodePoint = firstCodePoint;
			Length = length;
		}

		public static UnicodeRange Create(char firstCharacter, char lastCharacter)
		{
			if (lastCharacter < firstCharacter)
			{
				throw new ArgumentOutOfRangeException("lastCharacter");
			}
			return new UnicodeRange(firstCharacter, 1 + (lastCharacter - firstCharacter));
		}
	}
	public static class UnicodeRanges
	{
		private static UnicodeRange _none;

		private static UnicodeRange _all;

		private static UnicodeRange _u0000;

		private static UnicodeRange _u0080;

		private static UnicodeRange _u0100;

		private static UnicodeRange _u0180;

		private static UnicodeRange _u0250;

		private static UnicodeRange _u02B0;

		private static UnicodeRange _u0300;

		private static UnicodeRange _u0370;

		private static UnicodeRange _u0400;

		private static UnicodeRange _u0500;

		private static UnicodeRange _u0530;

		private static UnicodeRange _u0590;

		private static UnicodeRange _u0600;

		private static UnicodeRange _u0700;

		private static UnicodeRange _u0750;

		private static UnicodeRange _u0780;

		private static UnicodeRange _u07C0;

		private static UnicodeRange _u0800;

		private static UnicodeRange _u0840;

		private static UnicodeRange _u0860;

		private static UnicodeRange _u0870;

		private static UnicodeRange _u08A0;

		private static UnicodeRange _u0900;

		private static UnicodeRange _u0980;

		private static UnicodeRange _u0A00;

		private static UnicodeRange _u0A80;

		private static UnicodeRange _u0B00;

		private static UnicodeRange _u0B80;

		private static UnicodeRange _u0C00;

		private static UnicodeRange _u0C80;

		private static UnicodeRange _u0D00;

		private static UnicodeRange _u0D80;

		private static UnicodeRange _u0E00;

		private static UnicodeRange _u0E80;

		private static UnicodeRange _u0F00;

		private static UnicodeRange _u1000;

		private static UnicodeRange _u10A0;

		private static UnicodeRange _u1100;

		private static UnicodeRange _u1200;

		private static UnicodeRange _u1380;

		private static UnicodeRange _u13A0;

		private static UnicodeRange _u1400;

		private static UnicodeRange _u1680;

		private static UnicodeRange _u16A0;

		private static UnicodeRange _u1700;

		private static UnicodeRange _u1720;

		private static UnicodeRange _u1740;

		private static UnicodeRange _u1760;

		private static UnicodeRange _u1780;

		private static UnicodeRange _u1800;

		private static UnicodeRange _u18B0;

		private static UnicodeRange _u1900;

		private static UnicodeRange _u1950;

		private static UnicodeRange _u1980;

		private static UnicodeRange _u19E0;

		private static UnicodeRange _u1A00;

		private static UnicodeRange _u1A20;

		private static UnicodeRange _u1AB0;

		private static UnicodeRange _u1B00;

		private static UnicodeRange _u1B80;

		private static UnicodeRange _u1BC0;

		private static UnicodeRange _u1C00;

		private static UnicodeRange _u1C50;

		private static UnicodeRange _u1C80;

		private static UnicodeRange _u1C90;

		private static UnicodeRange _u1CC0;

		private static UnicodeRange _u1CD0;

		private static UnicodeRange _u1D00;

		private static UnicodeRange _u1D80;

		private static UnicodeRange _u1DC0;

		private static UnicodeRange _u1E00;

		private static UnicodeRange _u1F00;

		private static UnicodeRange _u2000;

		private static UnicodeRange _u2070;

		private static UnicodeRange _u20A0;

		private static UnicodeRange _u20D0;

		private static UnicodeRange _u2100;

		private static UnicodeRange _u2150;

		private static UnicodeRange _u2190;

		private static UnicodeRange _u2200;

		private static UnicodeRange _u2300;

		private static UnicodeRange _u2400;

		private static UnicodeRange _u2440;

		private static UnicodeRange _u2460;

		private static UnicodeRange _u2500;

		private static UnicodeRange _u2580;

		private static UnicodeRange _u25A0;

		private static UnicodeRange _u2600;

		private static UnicodeRange _u2700;

		private static UnicodeRange _u27C0;

		private static UnicodeRange _u27F0;

		private static UnicodeRange _u2800;

		private static UnicodeRange _u2900;

		private static UnicodeRange _u2980;

		private static UnicodeRange _u2A00;

		private static UnicodeRange _u2B00;

		private static UnicodeRange _u2C00;

		private static UnicodeRange _u2C60;

		private static UnicodeRange _u2C80;

		private static UnicodeRange _u2D00;

		private static UnicodeRange _u2D30;

		private static UnicodeRange _u2D80;

		private static UnicodeRange _u2DE0;

		private static UnicodeRange _u2E00;

		private static UnicodeRange _u2E80;

		private static UnicodeRange _u2F00;

		private static UnicodeRange _u2FF0;

		private static UnicodeRange _u3000;

		private static UnicodeRange _u3040;

		private static UnicodeRange _u30A0;

		private static UnicodeRange _u3100;

		private static UnicodeRange _u3130;

		private static UnicodeRange _u3190;

		private static UnicodeRange _u31A0;

		private static UnicodeRange _u31C0;

		private static UnicodeRange _u31F0;

		private static UnicodeRange _u3200;

		private static UnicodeRange _u3300;

		private static UnicodeRange _u3400;

		private static UnicodeRange _u4DC0;

		private static UnicodeRange _u4E00;

		private static UnicodeRange _uA000;

		private static UnicodeRange _uA490;

		private static UnicodeRange _uA4D0;

		private static UnicodeRange _uA500;

		private static UnicodeRange _uA640;

		private static UnicodeRange _uA6A0;

		private static UnicodeRange _uA700;

		private static UnicodeRange _uA720;

		private static UnicodeRange _uA800;

		private static UnicodeRange _uA830;

		private static UnicodeRange _uA840;

		private static UnicodeRange _uA880;

		private static UnicodeRange _uA8E0;

		private static UnicodeRange _uA900;

		private static UnicodeRange _uA930;

		private static UnicodeRange _uA960;

		private static UnicodeRange _uA980;

		private static UnicodeRange _uA9E0;

		private static UnicodeRange _uAA00;

		private static UnicodeRange _uAA60;

		priva

BepInEx/core/System.Text.Json.dll

Decompiled 2 weeks ago
using System;
using System.Buffers;
using System.Buffers.Text;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Pipelines;
using System.Net;
using System.Numerics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Reflection;
using System.Text.Json.Schema;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Converters;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;
using System.Text.Unicode;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using FxResources.System.Text.Json;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.0", FrameworkDisplayName = ".NET Standard 2.0")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Text.Json")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides high-performance and low-allocating types that serialize objects to JavaScript Object Notation (JSON) text and deserialize JSON text to objects, with UTF-8 support built-in. Also provides types to read and write JSON text encoded as UTF-8, and to create an in-memory document object model (DOM), that is read-only, for random access of the JSON elements within a structured view of the data.\r\n\r\nThe System.Text.Json library is built-in as part of the shared framework in .NET Runtime. The package can be installed when you need to use it in other target frameworks.")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Text.Json")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("10.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsReadOnlyAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class RequiresLocationAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class ParamCollectionAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsUnmanagedAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class IsByRefLikeAttribute : Attribute
	{
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class ScopedRefAttribute : Attribute
	{
	}
	[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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.System.Text.Json
{
	internal static class SR
	{
	}
}
namespace System
{
	internal static class HexConverter
	{
		public enum Casing : uint
		{
			Upper = 0u,
			Lower = 8224u
		}

		private ref struct SpanCasingPair
		{
			public ReadOnlySpan<byte> Bytes { get; set; }

			public Casing Casing { get; set; }
		}

		public static ReadOnlySpan<byte> CharToHexLookup => new byte[256]
		{
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 0, 1,
			2, 3, 4, 5, 6, 7, 8, 9, 255, 255,
			255, 255, 255, 255, 255, 10, 11, 12, 13, 14,
			15, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 10, 11, 12,
			13, 14, 15, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
			255, 255, 255, 255, 255, 255
		};

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToBytesBuffer(byte value, Span<byte> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (byte)num2;
			buffer[startingIndex] = (byte)(num2 >> 8);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static void ToCharsBuffer(byte value, Span<char> buffer, int startingIndex = 0, Casing casing = Casing.Upper)
		{
			uint num = (uint)(((value & 0xF0) << 4) + (value & 0xF) - 35209);
			uint num2 = ((((0 - num) & 0x7070) >> 4) + num + 47545) | (uint)casing;
			buffer[startingIndex + 1] = (char)(num2 & 0xFFu);
			buffer[startingIndex] = (char)(num2 >> 8);
		}

		public static void EncodeToUtf8(ReadOnlySpan<byte> source, Span<byte> utf8Destination, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < source.Length; i++)
			{
				ToBytesBuffer(source[i], utf8Destination, i * 2, casing);
			}
		}

		public static void EncodeToUtf16(ReadOnlySpan<byte> source, Span<char> destination, Casing casing = Casing.Upper)
		{
			for (int i = 0; i < source.Length; i++)
			{
				ToCharsBuffer(source[i], destination, i * 2, casing);
			}
		}

		public static string ToString(ReadOnlySpan<byte> bytes, Casing casing = Casing.Upper)
		{
			Span<char> span = ((bytes.Length <= 16) ? stackalloc char[bytes.Length * 2] : new char[bytes.Length * 2].AsSpan());
			Span<char> buffer = span;
			int num = 0;
			ReadOnlySpan<byte> readOnlySpan = bytes;
			for (int i = 0; i < readOnlySpan.Length; i++)
			{
				ToCharsBuffer(readOnlySpan[i], buffer, num, casing);
				num += 2;
			}
			return buffer.ToString();
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharUpper(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 7;
			}
			return (char)value;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static char ToCharLower(int value)
		{
			value &= 0xF;
			value += 48;
			if (value > 57)
			{
				value += 39;
			}
			return (char)value;
		}

		public static bool TryDecodeFromUtf8(ReadOnlySpan<byte> utf8Source, Span<byte> destination, out int bytesProcessed)
		{
			return TryDecodeFromUtf8_Scalar(utf8Source, destination, out bytesProcessed);
		}

		public static bool TryDecodeFromUtf16(ReadOnlySpan<char> source, Span<byte> destination, out int charsProcessed)
		{
			return TryDecodeFromUtf16_Scalar(source, destination, out charsProcessed);
		}

		private static bool TryDecodeFromUtf8_Scalar(ReadOnlySpan<byte> utf8Source, Span<byte> destination, out int bytesProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < destination.Length)
			{
				num3 = FromChar(utf8Source[num + 1]);
				num4 = FromChar(utf8Source[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				destination[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			bytesProcessed = num;
			return (num3 | num4) != 255;
		}

		private static bool TryDecodeFromUtf16_Scalar(ReadOnlySpan<char> source, Span<byte> destination, out int charsProcessed)
		{
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int num4 = 0;
			while (num2 < destination.Length)
			{
				num3 = FromChar(source[num + 1]);
				num4 = FromChar(source[num]);
				if ((num3 | num4) == 255)
				{
					break;
				}
				destination[num2++] = (byte)((num4 << 4) | num3);
				num += 2;
			}
			if (num3 == 255)
			{
				num++;
			}
			charsProcessed = num;
			return (num3 | num4) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromChar(int c)
		{
			if (c < CharToHexLookup.Length)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromUpperChar(int c)
		{
			if (c <= 71)
			{
				return CharToHexLookup[c];
			}
			return 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int FromLowerChar(int c)
		{
			switch (c)
			{
			case 48:
			case 49:
			case 50:
			case 51:
			case 52:
			case 53:
			case 54:
			case 55:
			case 56:
			case 57:
				return c - 48;
			case 97:
			case 98:
			case 99:
			case 100:
			case 101:
			case 102:
				return c - 97 + 10;
			default:
				return 255;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexChar(int c)
		{
			if (IntPtr.Size == 8)
			{
				ulong num = (uint)(c - 48);
				long num2 = -17875860044349952L << (int)num;
				ulong num3 = num - 64;
				return (long)((ulong)num2 & num3) < 0L;
			}
			return FromChar(c) != 255;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexUpperChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 65) <= 5u;
			}
			return true;
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsHexLowerChar(int c)
		{
			if ((uint)(c - 48) > 9u)
			{
				return (uint)(c - 97) <= 5u;
			}
			return true;
		}
	}
	internal static class Obsoletions
	{
		internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}";

		internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.";

		internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001";

		internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used.";

		internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002";

		internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime.";

		internal const string CodeAccessSecurityDiagId = "SYSLIB0003";

		internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported.";

		internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004";

		internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported.";

		internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005";

		internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadAbortDiagId = "SYSLIB0006";

		internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported.";

		internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007";

		internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException.";

		internal const string CreatePdbGeneratorDiagId = "SYSLIB0008";

		internal const string AuthenticationManagerMessage = "AuthenticationManager is not supported. Methods will no-op or throw PlatformNotSupportedException.";

		internal const string AuthenticationManagerDiagId = "SYSLIB0009";

		internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException.";

		internal const string RemotingApisDiagId = "SYSLIB0010";

		internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.";

		internal const string BinaryFormatterDiagId = "SYSLIB0011";

		internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead.";

		internal const string CodeBaseDiagId = "SYSLIB0012";

		internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead.";

		internal const string EscapeUriStringDiagId = "SYSLIB0013";

		internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.";

		internal const string WebRequestDiagId = "SYSLIB0014";

		internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+.";

		internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015";

		internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations.";

		internal const string GetContextInfoDiagId = "SYSLIB0016";

		internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException.";

		internal const string StrongNameKeyPairDiagId = "SYSLIB0017";

		internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException.";

		internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018";

		internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException.";

		internal const string RuntimeEnvironmentDiagId = "SYSLIB0019";

		internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull.";

		internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020";

		internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead.";

		internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021";

		internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead.";

		internal const string RijndaelDiagId = "SYSLIB0022";

		internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.";

		internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023";

		internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception.";

		internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024";

		internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+.";

		internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025";

		internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use X509CertificateLoader to create a new certificate.";

		internal const string X509CertificateImmutableDiagId = "SYSLIB0026";

		internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey.";

		internal const string PublicKeyPropertyDiagId = "SYSLIB0027";

		internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.";

		internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028";

		internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported.";

		internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029";

		internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter.";

		internal const string UseManagedSha1DiagId = "SYSLIB0030";

		internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1.";

		internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031";

		internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored.";

		internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032";

		internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead.";

		internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033";

		internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead.";

		internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034";

		internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner.";

		internal const string SignerInfoCounterSigDiagId = "SYSLIB0035";

		internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.";

		internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036";

		internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported.";

		internal const string AssemblyNameMembersDiagId = "SYSLIB0037";

		internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information.";

		internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038";

		internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults.";

		internal const string TlsVersion10and11DiagId = "SYSLIB0039";

		internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code.";

		internal const string EncryptionPolicyDiagId = "SYSLIB0040";

		internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys.";

		internal const string EccXmlExportImportDiagId = "SYSLIB0042";

		internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead.";

		internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043";

		internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.";

		internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044";

		internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead.";

		internal const string CryptoStringFactoryDiagId = "SYSLIB0045";

		internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code.";

		internal const string ControlledExecutionRunDiagId = "SYSLIB0046";

		internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution.";

		internal const string XmlSecureResolverDiagId = "SYSLIB0047";

		internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead.";

		internal const string RsaEncryptDecryptDiagId = "SYSLIB0048";

		internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties.";

		internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049";

		internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used.";

		internal const string LegacyFormatterDiagId = "SYSLIB0050";

		internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code.";

		internal const string LegacyFormatterImplDiagId = "SYSLIB0051";

		internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported.";

		internal const string RegexExtensibilityDiagId = "SYSLIB0052";

		internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size.";

		internal const string AesGcmTagConstructorDiagId = "SYSLIB0053";

		internal const string ThreadVolatileReadWriteMessage = "Thread.VolatileRead and Thread.VolatileWrite are obsolete. Use Volatile.Read or Volatile.Write respectively instead.";

		internal const string ThreadVolatileReadWriteDiagId = "SYSLIB0054";

		internal const string ArmIntrinsicPerformsUnsignedOperationMessage = "The underlying hardware instruction does not perform a signed saturate narrowing operation, and it always returns an unsigned result. Use the unsigned overload instead.";

		internal const string ArmIntrinsicPerformsUnsignedOperationDiagId = "SYSLIB0055";

		internal const string LoadFromHashAlgorithmMessage = "LoadFrom with a custom AssemblyHashAlgorithm is obsolete. Use overloads without an AssemblyHashAlgorithm.";

		internal const string LoadFromHashAlgorithmDiagId = "SYSLIB0056";

		internal const string X509CtorCertDataObsoleteMessage = "Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates.";

		internal const string X509CtorCertDataObsoleteDiagId = "SYSLIB0057";

		internal const string TlsCipherAlgorithmEnumsMessage = "KeyExchangeAlgorithm, KeyExchangeStrength, CipherAlgorithm, CipherStrength, HashAlgorithm and HashStrength properties of SslStream are obsolete. Use NegotiatedCipherSuite instead.";

		internal const string TlsCipherAlgorithmEnumsDiagId = "SYSLIB0058";

		internal const string SystemEventsEventsThreadShutdownMessage = "SystemEvents.EventsThreadShutdown callbacks are not run before the process exits. Use AppDomain.ProcessExit instead.";

		internal const string SystemEventsEventsThreadShutdownDiagId = "SYSLIB0059";

		internal const string Rfc2898DeriveBytesCtorMessage = "The constructors on Rfc2898DeriveBytes are obsolete. Use the static Pbkdf2 method instead.";

		internal const string Rfc2898DeriveBytesCtorDiagId = "SYSLIB0060";

		internal const string QueryableMinByMaxByTSourceObsoleteMessage = "The Queryable MinBy and MaxBy taking an IComparer<TSource> are obsolete. Use the new ones that take an IComparer<TKey>.";

		internal const string QueryableMinByMaxByTSourceObsoleteDiagId = "SYSLIB0061";

		internal const string XsltSettingsEnableScriptMessage = "XSLT Script blocks are not supported.";

		internal const string XsltSettingsEnableScriptDiagId = "SYSLIB0062";
	}
	internal static class ThrowHelper
	{
		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException()
		{
			throw new ArgumentOutOfRangeException();
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_DestinationTooShort()
		{
			throw new ArgumentException(System.SR.Argument_DestinationTooShort, "destination");
		}

		[DoesNotReturn]
		internal static void ThrowArgumentException_CannotExtractScalar(System.ExceptionArgument argument)
		{
			throw GetArgumentException(System.ExceptionResource.Argument_CannotExtractScalar, argument);
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRange_IndexMustBeLessException()
		{
			throw GetArgumentOutOfRangeException(System.ExceptionArgument.index, System.ExceptionResource.ArgumentOutOfRange_IndexMustBeLess);
		}

		[DoesNotReturn]
		internal static void ThrowArgumentNullException(System.ExceptionArgument argument)
		{
			throw new ArgumentNullException(GetArgumentName(argument));
		}

		[DoesNotReturn]
		internal static void ThrowArgumentOutOfRangeException(System.ExceptionArgument argument)
		{
			throw new ArgumentOutOfRangeException(GetArgumentName(argument));
		}

		private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(System.ExceptionArgument argument, System.ExceptionResource resource)
		{
			return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource));
		}

		private static ArgumentException GetArgumentException(System.ExceptionResource resource, System.ExceptionArgument argument)
		{
			return new ArgumentException(GetResourceString(resource), GetArgumentName(argument));
		}

		private static string GetArgumentName(System.ExceptionArgument argument)
		{
			return argument switch
			{
				System.ExceptionArgument.ch => "ch", 
				System.ExceptionArgument.culture => "culture", 
				System.ExceptionArgument.index => "index", 
				System.ExceptionArgument.input => "input", 
				System.ExceptionArgument.value => "value", 
				_ => "", 
			};
		}

		private static string GetResourceString(System.ExceptionResource resource)
		{
			return resource switch
			{
				System.ExceptionResource.ArgumentOutOfRange_IndexMustBeLess => System.SR.ArgumentOutOfRange_IndexMustBeLess, 
				System.ExceptionResource.Argument_CannotExtractScalar => System.SR.Argument_CannotExtractScalar, 
				_ => "", 
			};
		}
	}
	internal enum ExceptionArgument
	{
		ch,
		culture,
		index,
		input,
		value
	}
	internal enum ExceptionResource
	{
		Argument_CannotExtractScalar,
		ArgumentOutOfRange_IndexMustBeLess
	}
	internal static class Marvin
	{
		public static ulong DefaultSeed { get; } = GenerateSeed();


		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static int ComputeHash32(ReadOnlySpan<byte> data, ulong seed)
		{
			return ComputeHash32(ref MemoryMarshal.GetReference(data), (uint)data.Length, (uint)seed, (uint)(seed >> 32));
		}

		public static int ComputeHash32(ref byte data, uint count, uint p0, uint p1)
		{
			uint num;
			if (count < 8)
			{
				if (count < 4)
				{
					num = ((!BitConverter.IsLittleEndian) ? 2147483648u : 128u);
					if ((count & (true ? 1u : 0u)) != 0)
					{
						num = Unsafe.AddByteOffset(ref data, (nuint)count & (nuint)2u);
						if (BitConverter.IsLittleEndian)
						{
							num |= 0x8000u;
						}
						else
						{
							num <<= 24;
							num |= 0x800000u;
						}
					}
					if ((count & 2u) != 0)
					{
						if (BitConverter.IsLittleEndian)
						{
							num <<= 16;
							num |= Unsafe.ReadUnaligned<ushort>(ref data);
						}
						else
						{
							num |= Unsafe.ReadUnaligned<ushort>(ref data);
							num = RotateLeft(num, 16);
						}
					}
					goto IL_00bd;
				}
			}
			else
			{
				uint num2 = count / 8;
				do
				{
					p0 += Unsafe.ReadUnaligned<uint>(ref data);
					uint num3 = Unsafe.ReadUnaligned<uint>(ref Unsafe.AddByteOffset(ref data, 4u));
					Block(ref p0, ref p1);
					p0 += num3;
					Block(ref p0, ref p1);
					data = ref Unsafe.AddByteOffset(ref data, 8u);
				}
				while (--num2 != 0);
				if ((count & 4) == 0)
				{
					goto IL_006a;
				}
			}
			p0 += Unsafe.ReadUnaligned<uint>(ref data);
			Block(ref p0, ref p1);
			goto IL_006a;
			IL_006a:
			num = Unsafe.ReadUnaligned<uint>(ref Unsafe.Add(ref Unsafe.AddByteOffset(ref data, (nuint)count & (nuint)7u), -4));
			count = ~count << 3;
			if (BitConverter.IsLittleEndian)
			{
				num >>= 8;
				num |= 0x80000000u;
				num >>= (int)(count & 0x1F);
			}
			else
			{
				num <<= 8;
				num |= 0x80u;
				num <<= (int)(count & 0x1F);
			}
			goto IL_00bd;
			IL_00bd:
			p0 += num;
			Block(ref p0, ref p1);
			Block(ref p0, ref p1);
			return (int)(p1 ^ p0);
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static void Block(ref uint rp0, ref uint rp1)
		{
			uint num = rp0;
			uint num2 = rp1;
			num2 ^= num;
			num = RotateLeft(num, 20);
			num += num2;
			num2 = RotateLeft(num2, 9);
			num2 ^= num;
			num = RotateLeft(num, 27);
			num += num2;
			num2 = RotateLeft(num2, 19);
			rp0 = num;
			rp1 = num2;
		}

		private unsafe static ulong GenerateSeed()
		{
			byte[] array = new byte[8];
			using RandomNumberGenerator randomNumberGenerator = RandomNumberGenerator.Create();
			randomNumberGenerator.GetBytes(array);
			fixed (byte* ptr = array)
			{
				return *(ulong*)ptr;
			}
		}

		[MethodImpl(MethodImplOptions.AggressiveInlining)]
		private static uint RotateLeft(uint value, int shift)
		{
			return (value << shift) | (value >> 32 - shift);
		}
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ArrayDepthTooLarge => GetResourceString("ArrayDepthTooLarge");

		internal static string CallFlushToAvoidDataLoss => GetResourceString("CallFlushToAvoidDataLoss");

		internal static string CannotReadIncompleteUTF16 => GetResourceString("CannotReadIncompleteUTF16");

		internal static string CannotReadInvalidUTF16 => GetResourceString("CannotReadInvalidUTF16");

		internal static string CannotStartObjectArrayAfterPrimitiveOrClose => GetResourceString("CannotStartObjectArrayAfterPrimitiveOrClose");

		internal static string CannotStartObjectArrayWithoutProperty => GetResourceString("CannotStartObjectArrayWithoutProperty");

		internal static string CannotTranscodeInvalidUtf8 => GetResourceString("CannotTranscodeInvalidUtf8");

		internal static string CannotDecodeInvalidBase64 => GetResourceString("CannotDecodeInvalidBase64");

		internal static string CannotTranscodeInvalidUtf16 => GetResourceString("CannotTranscodeInvalidUtf16");

		internal static string CannotEncodeInvalidUTF16 => GetResourceString("CannotEncodeInvalidUTF16");

		internal static string CannotEncodeInvalidUTF8 => GetResourceString("CannotEncodeInvalidUTF8");

		internal static string CannotWritePropertyWithinArray => GetResourceString("CannotWritePropertyWithinArray");

		internal static string CannotWritePropertyAfterProperty => GetResourceString("CannotWritePropertyAfterProperty");

		internal static string CannotWriteValueAfterPrimitiveOrClose => GetResourceString("CannotWriteValueAfterPrimitiveOrClose");

		internal static string CannotWriteValueWithinObject => GetResourceString("CannotWriteValueWithinObject");

		internal static string DepthTooLarge => GetResourceString("DepthTooLarge");

		internal static string DestinationTooShort => GetResourceString("DestinationTooShort");

		internal static string EmptyJsonIsInvalid => GetResourceString("EmptyJsonIsInvalid");

		internal static string EndOfCommentNotFound => GetResourceString("EndOfCommentNotFound");

		internal static string EndOfStringNotFound => GetResourceString("EndOfStringNotFound");

		internal static string ExpectedEndAfterSingleJson => GetResourceString("ExpectedEndAfterSingleJson");

		internal static string ExpectedEndOfDigitNotFound => GetResourceString("ExpectedEndOfDigitNotFound");

		internal static string ExpectedFalse => GetResourceString("ExpectedFalse");

		internal static string ExpectedJsonTokens => GetResourceString("ExpectedJsonTokens");

		internal static string ExpectedOneCompleteToken => GetResourceString("ExpectedOneCompleteToken");

		internal static string ExpectedNextDigitEValueNotFound => GetResourceString("ExpectedNextDigitEValueNotFound");

		internal static string ExpectedNull => GetResourceString("ExpectedNull");

		internal static string ExpectedSeparatorAfterPropertyNameNotFound => GetResourceString("ExpectedSeparatorAfterPropertyNameNotFound");

		internal static string ExpectedStartOfPropertyNotFound => GetResourceString("ExpectedStartOfPropertyNotFound");

		internal static string ExpectedStartOfPropertyOrValueNotFound => GetResourceString("ExpectedStartOfPropertyOrValueNotFound");

		internal static string ExpectedStartOfValueNotFound => GetResourceString("ExpectedStartOfValueNotFound");

		internal static string ExpectedTrue => GetResourceString("ExpectedTrue");

		internal static string ExpectedValueAfterPropertyNameNotFound => GetResourceString("ExpectedValueAfterPropertyNameNotFound");

		internal static string FailedToGetLargerSpan => GetResourceString("FailedToGetLargerSpan");

		internal static string FoundInvalidCharacter => GetResourceString("FoundInvalidCharacter");

		internal static string InvalidCast => GetResourceString("InvalidCast");

		internal static string InvalidCharacterAfterEscapeWithinString => GetResourceString("InvalidCharacterAfterEscapeWithinString");

		internal static string InvalidCharacterWithinString => GetResourceString("InvalidCharacterWithinString");

		internal static string UnsupportedEnumIdentifier => GetResourceString("UnsupportedEnumIdentifier");

		internal static string InvalidEndOfJsonNonPrimitive => GetResourceString("InvalidEndOfJsonNonPrimitive");

		internal static string InvalidHexCharacterWithinString => GetResourceString("InvalidHexCharacterWithinString");

		internal static string JsonDocumentDoesNotSupportComments => GetResourceString("JsonDocumentDoesNotSupportComments");

		internal static string JsonElementHasWrongType => GetResourceString("JsonElementHasWrongType");

		internal static string JsonElementDeepEqualsInsufficientExecutionStack => GetResourceString("JsonElementDeepEqualsInsufficientExecutionStack");

		internal static string JsonNumberExponentTooLarge => GetResourceString("JsonNumberExponentTooLarge");

		internal static string DefaultTypeInfoResolverImmutable => GetResourceString("DefaultTypeInfoResolverImmutable");

		internal static string TypeInfoResolverChainImmutable => GetResourceString("TypeInfoResolverChainImmutable");

		internal static string TypeInfoImmutable => GetResourceString("TypeInfoImmutable");

		internal static string MaxDepthMustBePositive => GetResourceString("MaxDepthMustBePositive");

		internal static string CommentHandlingMustBeValid => GetResourceString("CommentHandlingMustBeValid");

		internal static string MismatchedObjectArray => GetResourceString("MismatchedObjectArray");

		internal static string CannotWriteEndAfterProperty => GetResourceString("CannotWriteEndAfterProperty");

		internal static string ObjectDepthTooLarge => GetResourceString("ObjectDepthTooLarge");

		internal static string PropertyNameTooLarge => GetResourceString("PropertyNameTooLarge");

		internal static string FormatDecimal => GetResourceString("FormatDecimal");

		internal static string FormatDouble => GetResourceString("FormatDouble");

		internal static string FormatInt32 => GetResourceString("FormatInt32");

		internal static string FormatInt64 => GetResourceString("FormatInt64");

		internal static string FormatSingle => GetResourceString("FormatSingle");

		internal static string FormatUInt32 => GetResourceString("FormatUInt32");

		internal static string FormatUInt64 => GetResourceString("FormatUInt64");

		internal static string RequiredDigitNotFoundAfterDecimal => GetResourceString("RequiredDigitNotFoundAfterDecimal");

		internal static string RequiredDigitNotFoundAfterSign => GetResourceString("RequiredDigitNotFoundAfterSign");

		internal static string RequiredDigitNotFoundEndOfData => GetResourceString("RequiredDigitNotFoundEndOfData");

		internal static string SpecialNumberValuesNotSupported => GetResourceString("SpecialNumberValuesNotSupported");

		internal static string ValueTooLarge => GetResourceString("ValueTooLarge");

		internal static string ZeroDepthAtEnd => GetResourceString("ZeroDepthAtEnd");

		internal static string DeserializeUnableToConvertValue => GetResourceString("DeserializeUnableToConvertValue");

		internal static string DeserializeWrongType => GetResourceString("DeserializeWrongType");

		internal static string SerializationInvalidBufferSize => GetResourceString("SerializationInvalidBufferSize");

		internal static string BufferWriterAdvancedTooFar => GetResourceString("BufferWriterAdvancedTooFar");

		internal static string InvalidComparison => GetResourceString("InvalidComparison");

		internal static string UnsupportedFormat => GetResourceString("UnsupportedFormat");

		internal static string ExpectedStartOfPropertyOrValueAfterComment => GetResourceString("ExpectedStartOfPropertyOrValueAfterComment");

		internal static string TrailingCommaNotAllowedBeforeArrayEnd => GetResourceString("TrailingCommaNotAllowedBeforeArrayEnd");

		internal static string TrailingCommaNotAllowedBeforeObjectEnd => GetResourceString("TrailingCommaNotAllowedBeforeObjectEnd");

		internal static string SerializerOptionsReadOnly => GetResourceString("SerializerOptionsReadOnly");

		internal static string SerializerOptions_InvalidChainedResolver => GetResourceString("SerializerOptions_InvalidChainedResolver");

		internal static string StreamNotWritable => GetResourceString("StreamNotWritable");

		internal static string CannotWriteCommentWithEmbeddedDelimiter => GetResourceString("CannotWriteCommentWithEmbeddedDelimiter");

		internal static string SerializerPropertyNameConflict => GetResourceString("SerializerPropertyNameConflict");

		internal static string SerializerPropertyNameNull => GetResourceString("SerializerPropertyNameNull");

		internal static string SerializationDataExtensionPropertyInvalid => GetResourceString("SerializationDataExtensionPropertyInvalid");

		internal static string PropertyTypeNotNullable => GetResourceString("PropertyTypeNotNullable");

		internal static string SerializationDuplicateTypeAttribute => GetResourceString("SerializationDuplicateTypeAttribute");

		internal static string ExtensionDataConflictsWithUnmappedMemberHandling => GetResourceString("ExtensionDataConflictsWithUnmappedMemberHandling");

		internal static string SerializationNotSupportedType => GetResourceString("SerializationNotSupportedType");

		internal static string TypeRequiresAsyncSerialization => GetResourceString("TypeRequiresAsyncSerialization");

		internal static string InvalidCharacterAtStartOfComment => GetResourceString("InvalidCharacterAtStartOfComment");

		internal static string UnexpectedEndOfDataWhileReadingComment => GetResourceString("UnexpectedEndOfDataWhileReadingComment");

		internal static string CannotSkip => GetResourceString("CannotSkip");

		internal static string NotEnoughData => GetResourceString("NotEnoughData");

		internal static string UnexpectedEndOfLineSeparator => GetResourceString("UnexpectedEndOfLineSeparator");

		internal static string JsonSerializerDoesNotSupportComments => GetResourceString("JsonSerializerDoesNotSupportComments");

		internal static string DeserializeNoConstructor => GetResourceString("DeserializeNoConstructor");

		internal static string DeserializeInterfaceOrAbstractType => GetResourceString("DeserializeInterfaceOrAbstractType");

		internal static string DeserializationMustSpecifyTypeDiscriminator => GetResourceString("DeserializationMustSpecifyTypeDiscriminator");

		internal static string SerializationConverterOnAttributeNotCompatible => GetResourceString("SerializationConverterOnAttributeNotCompatible");

		internal static string SerializationConverterOnAttributeInvalid => GetResourceString("SerializationConverterOnAttributeInvalid");

		internal static string SerializationConverterRead => GetResourceString("SerializationConverterRead");

		internal static string SerializationConverterNotCompatible => GetResourceString("SerializationConverterNotCompatible");

		internal static string ResolverTypeNotCompatible => GetResourceString("ResolverTypeNotCompatible");

		internal static string ResolverTypeInfoOptionsNotCompatible => GetResourceString("ResolverTypeInfoOptionsNotCompatible");

		internal static string SerializationConverterWrite => GetResourceString("SerializationConverterWrite");

		internal static string NamingPolicyReturnNull => GetResourceString("NamingPolicyReturnNull");

		internal static string SerializationDuplicateAttribute => GetResourceString("SerializationDuplicateAttribute");

		internal static string SerializeUnableToSerialize => GetResourceString("SerializeUnableToSerialize");

		internal static string FormatByte => GetResourceString("FormatByte");

		internal static string FormatInt16 => GetResourceString("FormatInt16");

		internal static string FormatSByte => GetResourceString("FormatSByte");

		internal static string FormatUInt16 => GetResourceString("FormatUInt16");

		internal static string SerializerCycleDetected => GetResourceString("SerializerCycleDetected");

		internal static string InvalidLeadingZeroInNumber => GetResourceString("InvalidLeadingZeroInNumber");

		internal static string MetadataCannotParsePreservedObjectToImmutable => GetResourceString("MetadataCannotParsePreservedObjectToImmutable");

		internal static string MetadataDuplicateIdFound => GetResourceString("MetadataDuplicateIdFound");

		internal static string MetadataIdCannotBeCombinedWithRef => GetResourceString("MetadataIdCannotBeCombinedWithRef");

		internal static string MetadataInvalidReferenceToValueType => GetResourceString("MetadataInvalidReferenceToValueType");

		internal static string MetadataInvalidTokenAfterValues => GetResourceString("MetadataInvalidTokenAfterValues");

		internal static string MetadataPreservedArrayFailed => GetResourceString("MetadataPreservedArrayFailed");

		internal static string MetadataInvalidPropertyInArrayMetadata => GetResourceString("MetadataInvalidPropertyInArrayMetadata");

		internal static string MetadataStandaloneValuesProperty => GetResourceString("MetadataStandaloneValuesProperty");

		internal static string MetadataReferenceCannotContainOtherProperties => GetResourceString("MetadataReferenceCannotContainOtherProperties");

		internal static string MetadataReferenceNotFound => GetResourceString("MetadataReferenceNotFound");

		internal static string MetadataValueWasNotString => GetResourceString("MetadataValueWasNotString");

		internal static string MetadataInvalidPropertyWithLeadingDollarSign => GetResourceString("MetadataInvalidPropertyWithLeadingDollarSign");

		internal static string MetadataUnexpectedProperty => GetResourceString("MetadataUnexpectedProperty");

		internal static string UnmappedJsonProperty => GetResourceString("UnmappedJsonProperty");

		internal static string DuplicateMetadataProperty => GetResourceString("DuplicateMetadataProperty");

		internal static string MultipleMembersBindWithConstructorParameter => GetResourceString("MultipleMembersBindWithConstructorParameter");

		internal static string ConstructorParamIncompleteBinding => GetResourceString("ConstructorParamIncompleteBinding");

		internal static string ObjectWithParameterizedCtorRefMetadataNotSupported => GetResourceString("ObjectWithParameterizedCtorRefMetadataNotSupported");

		internal static string SerializerConverterFactoryReturnsNull => GetResourceString("SerializerConverterFactoryReturnsNull");

		internal static string SerializationNotSupportedParentType => GetResourceString("SerializationNotSupportedParentType");

		internal static string ExtensionDataCannotBindToCtorParam => GetResourceString("ExtensionDataCannotBindToCtorParam");

		internal static string BufferMaximumSizeExceeded => GetResourceString("BufferMaximumSizeExceeded");

		internal static string CannotSerializeInvalidType => GetResourceString("CannotSerializeInvalidType");

		internal static string SerializeTypeInstanceNotSupported => GetResourceString("SerializeTypeInstanceNotSupported");

		internal static string JsonIncludeOnInaccessibleProperty => GetResourceString("JsonIncludeOnInaccessibleProperty");

		internal static string CannotSerializeInvalidMember => GetResourceString("CannotSerializeInvalidMember");

		internal static string CannotPopulateCollection => GetResourceString("CannotPopulateCollection");

		internal static string ConstructorContainsNullParameterNames => GetResourceString("ConstructorContainsNullParameterNames");

		internal static string DefaultIgnoreConditionAlreadySpecified => GetResourceString("DefaultIgnoreConditionAlreadySpecified");

		internal static string DefaultIgnoreConditionInvalid => GetResourceString("DefaultIgnoreConditionInvalid");

		internal static string DictionaryKeyTypeNotSupported => GetResourceString("DictionaryKeyTypeNotSupported");

		internal static string IgnoreConditionOnValueTypeInvalid => GetResourceString("IgnoreConditionOnValueTypeInvalid");

		internal static string NumberHandlingOnPropertyInvalid => GetResourceString("NumberHandlingOnPropertyInvalid");

		internal static string ConverterCanConvertMultipleTypes => GetResourceString("ConverterCanConvertMultipleTypes");

		internal static string MetadataReferenceOfTypeCannotBeAssignedToType => GetResourceString("MetadataReferenceOfTypeCannotBeAssignedToType");

		internal static string DeserializeUnableToAssignValue => GetResourceString("DeserializeUnableToAssignValue");

		internal static string DeserializeUnableToAssignNull => GetResourceString("DeserializeUnableToAssignNull");

		internal static string SerializerConverterFactoryReturnsJsonConverterFactory => GetResourceString("SerializerConverterFactoryReturnsJsonConverterFactory");

		internal static string SerializerConverterFactoryInvalidArgument => GetResourceString("SerializerConverterFactoryInvalidArgument");

		internal static string NodeElementWrongType => GetResourceString("NodeElementWrongType");

		internal static string NodeElementCannotBeObjectOrArray => GetResourceString("NodeElementCannotBeObjectOrArray");

		internal static string NodeAlreadyHasParent => GetResourceString("NodeAlreadyHasParent");

		internal static string NodeCycleDetected => GetResourceString("NodeCycleDetected");

		internal static string NodeUnableToConvert => GetResourceString("NodeUnableToConvert");

		internal static string NodeUnableToConvertElement => GetResourceString("NodeUnableToConvertElement");

		internal static string NodeValueNotAllowed => GetResourceString("NodeValueNotAllowed");

		internal static string NodeWrongType => GetResourceString("NodeWrongType");

		internal static string NodeParentWrongType => GetResourceString("NodeParentWrongType");

		internal static string NodeDuplicateKey => GetResourceString("NodeDuplicateKey");

		internal static string SerializerContextOptionsReadOnly => GetResourceString("SerializerContextOptionsReadOnly");

		internal static string ConverterForPropertyMustBeValid => GetResourceString("ConverterForPropertyMustBeValid");

		internal static string NoMetadataForType => GetResourceString("NoMetadataForType");

		internal static string AmbiguousMetadataForType => GetResourceString("AmbiguousMetadataForType");

		internal static string CollectionIsReadOnly => GetResourceString("CollectionIsReadOnly");

		internal static string ArrayIndexNegative => GetResourceString("ArrayIndexNegative");

		internal static string ArrayTooSmall => GetResourceString("ArrayTooSmall");

		internal static string NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty => GetResourceString("NodeJsonObjectCustomConverterNotAllowedOnExtensionProperty");

		internal static string NoMetadataForTypeProperties => GetResourceString("NoMetadataForTypeProperties");

		internal static string FieldCannotBeVirtual => GetResourceString("FieldCannotBeVirtual");

		internal static string MissingFSharpCoreMember => GetResourceString("MissingFSharpCoreMember");

		internal static string FSharpDiscriminatedUnionsNotSupported => GetResourceString("FSharpDiscriminatedUnionsNotSupported");

		internal static string Polymorphism_BaseConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_BaseConverterDoesNotSupportMetadata");

		internal static string Polymorphism_DerivedConverterDoesNotSupportMetadata => GetResourceString("Polymorphism_DerivedConverterDoesNotSupportMetadata");

		internal static string Polymorphism_TypeDoesNotSupportPolymorphism => GetResourceString("Polymorphism_TypeDoesNotSupportPolymorphism");

		internal static string Polymorphism_DerivedTypeIsNotSupported => GetResourceString("Polymorphism_DerivedTypeIsNotSupported");

		internal static string Polymorphism_DerivedTypeIsAlreadySpecified => GetResourceString("Polymorphism_DerivedTypeIsAlreadySpecified");

		internal static string Polymorphism_TypeDicriminatorIdIsAlreadySpecified => GetResourceString("Polymorphism_TypeDicriminatorIdIsAlreadySpecified");

		internal static string Polymorphism_InvalidCustomTypeDiscriminatorPropertyName => GetResourceString("Polymorphism_InvalidCustomTypeDiscriminatorPropertyName");

		internal static string Polymorphism_PropertyConflictsWithMetadataPropertyName => GetResourceString("Polymorphism_PropertyConflictsWithMetadataPropertyName");

		internal static string Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes => GetResourceString("Polymorphism_ConfigurationDoesNotSpecifyDerivedTypes");

		internal static string Polymorphism_UnrecognizedTypeDiscriminator => GetResourceString("Polymorphism_UnrecognizedTypeDiscriminator");

		internal static string Polymorphism_RuntimeTypeNotSupported => GetResourceString("Polymorphism_RuntimeTypeNotSupported");

		internal static string Polymorphism_RuntimeTypeDiamondAmbiguity => GetResourceString("Polymorphism_RuntimeTypeDiamondAmbiguity");

		internal static string InvalidJsonTypeInfoOperationForKind => GetResourceString("InvalidJsonTypeInfoOperationForKind");

		internal static string OnDeserializingCallbacksNotSupported => GetResourceString("OnDeserializingCallbacksNotSupported");

		internal static string CreateObjectConverterNotCompatible => GetResourceString("CreateObjectConverterNotCompatible");

		internal static string JsonPropertyInfoBoundToDifferentParent => GetResourceString("JsonPropertyInfoBoundToDifferentParent");

		internal static string JsonSerializerOptionsNoTypeInfoResolverSpecified => GetResourceString("JsonSerializerOptionsNoTypeInfoResolverSpecified");

		internal static string JsonSerializerIsReflectionDisabled => GetResourceString("JsonSerializerIsReflectionDisabled");

		internal static string JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo => GetResourceString("JsonPolymorphismOptionsAssociatedWithDifferentJsonTypeInfo");

		internal static string JsonPropertyRequiredAndNotDeserializable => GetResourceString("JsonPropertyRequiredAndNotDeserializable");

		internal static string JsonPropertyRequiredAndExtensionData => GetResourceString("JsonPropertyRequiredAndExtensionData");

		internal static string JsonRequiredPropertiesMissing => GetResourceString("JsonRequiredPropertiesMissing");

		internal static string ObjectCreationHandlingPopulateNotSupportedByConverter => GetResourceString("ObjectCreationHandlingPopulateNotSupportedByConverter");

		internal static string ObjectCreationHandlingPropertyMustHaveAGetter => GetResourceString("ObjectCreationHandlingPropertyMustHaveAGetter");

		internal static string ObjectCreationHandlingPropertyValueTypeMustHaveASetter => GetResourceString("ObjectCreationHandlingPropertyValueTypeMustHaveASetter");

		internal static string ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization => GetResourceString("ObjectCreationHandlingPropertyCannotAllowPolymorphicDeserialization");

		internal static string ObjectCreationHandlingPropertyCannotAllowReadOnlyMember => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReadOnlyMember");

		internal static string ObjectCreationHandlingPropertyCannotAllowReferenceHandling => GetResourceString("ObjectCreationHandlingPropertyCannotAllowReferenceHandling");

		internal static string ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors => GetResourceString("ObjectCreationHandlingPropertyDoesNotSupportParameterizedConstructors");

		internal static string FormatInt128 => GetResourceString("FormatInt128");

		internal static string FormatUInt128 => GetResourceString("FormatUInt128");

		internal static string FormatHalf => GetResourceString("FormatHalf");

		internal static string InvalidIndentCharacter => GetResourceString("InvalidIndentCharacter");

		internal static string InvalidIndentSize => GetResourceString("InvalidIndentSize");

		internal static string PipeWriterCanceled => GetResourceString("PipeWriterCanceled");

		internal static string PipeWriter_DoesNotImplementUnflushedBytes => GetResourceString("PipeWriter_DoesNotImplementUnflushedBytes");

		internal static string InvalidNewLine => GetResourceString("InvalidNewLine");

		internal static string PropertyGetterDisallowNull => GetResourceString("PropertyGetterDisallowNull");

		internal static string PropertySetterDisallowNull => GetResourceString("PropertySetterDisallowNull");

		internal static string ConstructorParameterDisallowNull => GetResourceString("ConstructorParameterDisallowNull");

		internal static string JsonSchemaExporter_ReferenceHandlerPreserve_NotSupported => GetResourceString("JsonSchemaExporter_ReferenceHandlerPreserve_NotSupported");

		internal static string JsonSchemaExporter_DepthTooLarge => GetResourceString("JsonSchemaExporter_DepthTooLarge");

		internal static string Arg_WrongType => GetResourceString("Arg_WrongType");

		internal static string Arg_ArrayPlusOffTooSmall => GetResourceString("Arg_ArrayPlusOffTooSmall");

		internal static string Arg_RankMultiDimNotSupported => GetResourceString("Arg_RankMultiDimNotSupported");

		internal static string Arg_NonZeroLowerBound => GetResourceString("Arg_NonZeroLowerBound");

		internal static string Argument_IncompatibleArrayType => GetResourceString("Argument_IncompatibleArrayType");

		internal static string Arg_KeyNotFoundWithKey => GetResourceString("Arg_KeyNotFoundWithKey");

		internal static string Argument_AddingDuplicate => GetResourceString("Argument_AddingDuplicate");

		internal static string InvalidOperation_ConcurrentOperationsNotSupported => GetResourceString("InvalidOperation_ConcurrentOperationsNotSupported");

		internal static string InvalidOperation_EnumFailedVersion => GetResourceString("InvalidOperation_EnumFailedVersion");

		internal static string ArgumentOutOfRange_Generic_MustBeNonNegative => GetResourceString("ArgumentOutOfRange_Generic_MustBeNonNegative");

		internal static string ArgumentOutOfRange_Generic_MustBeGreaterOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeGreaterOrEqual");

		internal static string ArgumentOutOfRange_Generic_MustBeLessOrEqual => GetResourceString("ArgumentOutOfRange_Generic_MustBeLessOrEqual");

		internal static string Arg_HTCapacityOverflow => GetResourceString("Arg_HTCapacityOverflow");

		internal static string Argument_InvalidOffLen => GetResourceString("Argument_InvalidOffLen");

		internal static string CannotWriteWithinString => GetResourceString("CannotWriteWithinString");

		internal static string Arg_MustBeRune => GetResourceString("Arg_MustBeRune");

		internal static string ArgumentOutOfRange_IndexMustBeLess => GetResourceString("ArgumentOutOfRange_IndexMustBeLess");

		internal static string Argument_DestinationTooShort => GetResourceString("Argument_DestinationTooShort");

		internal static string Argument_CannotExtractScalar => GetResourceString("Argument_CannotExtractScalar");

		internal static string CannotMixEncodings => GetResourceString("CannotMixEncodings");

		internal static string DuplicatePropertiesNotAllowed_JsonPropertyInfo => GetResourceString("DuplicatePropertiesNotAllowed_JsonPropertyInfo");

		internal static string DuplicatePropertiesNotAllowed_NameSpan => GetResourceString("DuplicatePropertiesNotAllowed_NameSpan");

		internal static string DuplicatePropertiesNotAllowed => GetResourceString("DuplicatePropertiesNotAllowed");

		internal static string PipeReaderCanceled => GetResourceString("PipeReaderCanceled");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, Inherited = false)]
	internal sealed class ObsoleteAttribute : Attribute
	{
		public string Message { get; }

		public bool IsError { get; }

		public string DiagnosticId { get; set; }

		public string UrlFormat { get; set; }

		public ObsoleteAttribute()
		{
		}

		public ObsoleteAttribute(string message)
		{
			Message = message;
		}

		public ObsoleteAttribute(string message, bool error)
		{
			Message = message;
			IsError = error;
		}
	}
}
namespace System.Buffers
{
	internal sealed class ArrayBufferWriter<T> : IBufferWriter<T>
	{
		private const int ArrayMaxLength = 2147483591;

		private const int DefaultInitialBufferSize = 256;

		private T[] _buffer;

		private int _index;

		public ReadOnlyMemory<T> WrittenMemory => _buffer.AsMemory(0, _index);

		public ReadOnlySpan<T> WrittenSpan => _buffer.AsSpan(0, _index);

		public int WrittenCount => _index;

		public int Capacity => _buffer.Length;

		public int FreeCapacity => _buffer.Length - _index;

		public ArrayBufferWriter()
		{
			_buffer = Array.Empty<T>();
			_index = 0;
		}

		public ArrayBufferWriter(int initialCapacity)
		{
			if (initialCapacity <= 0)
			{
				throw new ArgumentException(null, "initialCapacity");
			}
			_buffer = new T[initialCapacity];
			_index = 0;
		}

		public void Clear()
		{
			_buffer.AsSpan(0, _index).Clear();
			_index = 0;
		}

		public void ResetWrittenCount()
		{
			_index = 0;
		}

		public void Advance(int count)
		{
			if (count < 0)
			{
				throw new ArgumentException(null, "count");
			}
			if (_index > _buffer.Length - count)
			{
				ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length);
			}
			_index += count;
		}

		public Memory<T> GetMemory(int sizeHint = 0)
		{
			CheckAndResizeBuffer(sizeHint);
			return _buffer.AsMemory(_index);
		}

		public Span<T> GetSpan(int sizeHint = 0)
		{
			CheckAndResizeBuffer(sizeHint);
			return _buffer.AsSpan(_index);
		}

		private void CheckAndResizeBuffer(int sizeHint)
		{
			if (sizeHint < 0)
			{
				throw new ArgumentException("sizeHint");
			}
			if (sizeHint == 0)
			{
				sizeHint = 1;
			}
			if (sizeHint <= FreeCapacity)
			{
				return;
			}
			int num = _buffer.Length;
			int num2 = Math.Max(sizeHint, num);
			if (num == 0)
			{
				num2 = Math.Max(num2, 256);
			}
			int num3 = num + num2;
			if ((uint)num3 > 2147483647u)
			{
				uint num4 = (uint)(num - FreeCapacity + sizeHint);
				if (num4 > 2147483591)
				{
					ThrowOutOfMemoryException(num4);
				}
				num3 = 2147483591;
			}
			Array.Resize(ref _buffer, num3);
		}

		private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity)
		{
			throw new InvalidOperationException(System.SR.Format(System.SR.BufferWriterAdvancedTooFar, capacity));
		}

		private static void ThrowOutOfMemoryException(uint capacity)
		{
			throw new OutOfMemoryException(System.SR.Format(System.SR.BufferMaximumSizeExceeded, capacity));
		}
	}
}
namespace System.IO
{
	internal static class StreamExtensions
	{
		public static ValueTask<int> ReadAsync(this Stream stream, Memory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (MemoryMarshal.TryGetArray((ReadOnlyMemory<byte>)buffer, out ArraySegment<byte> segment))
			{
				return new ValueTask<int>(stream.ReadAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));
			}
			byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length);
			return FinishReadAsync(stream.ReadAsync(array, 0, buffer.Length, cancellationToken), array, buffer);
			static async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination)
			{
				try
				{
					int num = await readTask.ConfigureAwait(continueOnCapturedContext: false);
					new Span<byte>(localBuffer, 0, num).CopyTo(localDestination.Span);
					return num;
				}
				finally
				{
					ArrayPool<byte>.Shared.Return(localBuffer);
				}
			}
		}

		public static void Write(this Stream stream, ReadOnlyMemory<byte> buffer)
		{
			if (MemoryMarshal.TryGetArray(buffer, out var segment))
			{
				stream.Write(segment.Array, segment.Offset, segment.Count);
				return;
			}
			byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length);
			try
			{
				buffer.Span.CopyTo(array);
				stream.Write(array, 0, buffer.Length);
			}
			finally
			{
				ArrayPool<byte>.Shared.Return(array);
			}
		}

		public static ValueTask WriteAsync(this Stream stream, ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (MemoryMarshal.TryGetArray(buffer, out var segment))
			{
				return new ValueTask(stream.WriteAsync(segment.Array, segment.Offset, segment.Count, cancellationToken));
			}
			byte[] array = ArrayPool<byte>.Shared.Rent(buffer.Length);
			buffer.Span.CopyTo(array);
			return new ValueTask(FinishWriteAsync(stream.WriteAsync(array, 0, buffer.Length, cancellationToken), array));
		}

		private static async Task FinishWriteAsync(Task writeTask, byte[] localBuffer)
		{
			try
			{
				await writeTask.ConfigureAwait(continueOnCapturedContext: false);
			}
			finally
			{
				ArrayPool<byte>.Shared.Return(localBuffer);
			}
		}

		public static Task CopyToAsync(this Stream source, Stream destination, CancellationToken cancellationToken = default(CancellationToken))
		{
			return source.CopyToAsync(destination, 81920, cancellationToken);
		}
	}
}
namespace System.Reflection
{
	internal sealed class NullabilityInfo
	{
		public Type Type { get; }

		public NullabilityState ReadState { get; internal set; }

		public NullabilityState WriteState { get; internal set; }

		public NullabilityInfo ElementType { get; }

		public NullabilityInfo[] GenericTypeArguments { get; }

		internal NullabilityInfo(Type type, NullabilityState readState, NullabilityState writeState, NullabilityInfo elementType, NullabilityInfo[] typeArguments)
		{
			Type = type;
			ReadState = readState;
			WriteState = writeState;
			ElementType = elementType;
			GenericTypeArguments = typeArguments;
		}
	}
	internal enum NullabilityState
	{
		Unknown,
		NotNull,
		Nullable
	}
	internal sealed class NullabilityInfoContext
	{
		[Flags]
		private enum NotAnnotatedStatus
		{
			None = 0,
			Private = 1,
			Internal = 2
		}

		private readonly struct NullableAttributeStateParser
		{
			private static readonly object UnknownByte = (byte)0;

			private readonly object _nullableAttributeArgument;

			public static NullableAttributeStateParser Unknown => new NullableAttributeStateParser(UnknownByte);

			public NullableAttributeStateParser(object nullableAttributeArgument)
			{
				_nullableAttributeArgument = nullableAttributeArgument;
			}

			public bool ParseNullableState(int index, ref NullabilityState state)
			{
				object nullableAttributeArgument = _nullableAttributeArgument;
				if (!(nullableAttributeArgument is byte b))
				{
					if (nullableAttributeArgument is ReadOnlyCollection<CustomAttributeTypedArgument> readOnlyCollection)
					{
						ReadOnlyCollection<CustomAttributeTypedArgument> readOnlyCollection2 = readOnlyCollection;
						if (index < readOnlyCollection2.Count && readOnlyCollection2[index].Value is byte b2)
						{
							state = TranslateByte(b2);
							return true;
						}
					}
					return false;
				}
				byte b3 = b;
				state = TranslateByte(b3);
				return true;
			}
		}

		private const string CompilerServicesNameSpace = "System.Runtime.CompilerServices";

		private readonly Dictionary<Module, NotAnnotatedStatus> _publicOnlyModules = new Dictionary<Module, NotAnnotatedStatus>();

		private readonly Dictionary<MemberInfo, NullabilityState> _context = new Dictionary<MemberInfo, NullabilityState>();

		private NullabilityState? GetNullableContext(MemberInfo memberInfo)
		{
			while (memberInfo != null)
			{
				if (_context.TryGetValue(memberInfo, out var value))
				{
					return value;
				}
				foreach (CustomAttributeData customAttributesDatum in memberInfo.GetCustomAttributesData())
				{
					if (customAttributesDatum.AttributeType.Name == "NullableContextAttribute" && customAttributesDatum.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttributesDatum.ConstructorArguments.Count == 1)
					{
						value = TranslateByte(customAttributesDatum.ConstructorArguments[0].Value);
						_context.Add(memberInfo, value);
						return value;
					}
				}
				memberInfo = memberInfo.DeclaringType;
			}
			return null;
		}

		public NullabilityInfo Create(ParameterInfo parameterInfo)
		{
			ExceptionPolyfills.ThrowIfNull(parameterInfo, "parameterInfo");
			IList<CustomAttributeData> customAttributesData = parameterInfo.GetCustomAttributesData();
			NullableAttributeStateParser parser = ((parameterInfo.Member is MethodBase method && IsPrivateOrInternalMethodAndAnnotationDisabled(method)) ? NullableAttributeStateParser.Unknown : CreateParser(customAttributesData));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(parameterInfo.Member, parameterInfo.ParameterType, parser);
			if (nullabilityInfo.ReadState != 0)
			{
				CheckParameterMetadataType(parameterInfo, nullabilityInfo);
			}
			CheckNullabilityAttributes(nullabilityInfo, customAttributesData);
			return nullabilityInfo;
		}

		private void CheckParameterMetadataType(ParameterInfo parameter, NullabilityInfo nullability)
		{
			MemberInfo member = parameter.Member;
			MemberInfo metaMember;
			ParameterInfo parameterInfo;
			if (!(member is ConstructorInfo member2))
			{
				if (!(member is MethodInfo method))
				{
					return;
				}
				MethodInfo methodMetadataDefinition = GetMethodMetadataDefinition(method);
				metaMember = methodMetadataDefinition;
				parameterInfo = (string.IsNullOrEmpty(parameter.Name) ? methodMetadataDefinition.ReturnParameter : GetMetaParameter(methodMetadataDefinition, parameter));
			}
			else
			{
				parameterInfo = GetMetaParameter((MethodBase)(metaMember = (ConstructorInfo)GetMemberMetadataDefinition(member2)), parameter);
			}
			if (parameterInfo != null)
			{
				CheckGenericParameters(nullability, metaMember, parameterInfo.ParameterType, parameter.Member.ReflectedType);
			}
		}

		private static ParameterInfo GetMetaParameter(MethodBase metaMethod, ParameterInfo parameter)
		{
			ReadOnlySpan<ParameterInfo> parametersAsSpan = metaMethod.GetParametersAsSpan();
			for (int i = 0; i < parametersAsSpan.Length; i++)
			{
				if (parameter.Position == i && parameter.Name == parametersAsSpan[i].Name)
				{
					return parametersAsSpan[i];
				}
			}
			return null;
		}

		private static MethodInfo GetMethodMetadataDefinition(MethodInfo method)
		{
			if (method.IsGenericMethod && !method.IsGenericMethodDefinition)
			{
				method = method.GetGenericMethodDefinition();
			}
			return (MethodInfo)GetMemberMetadataDefinition(method);
		}

		private static void CheckNullabilityAttributes(NullabilityInfo nullability, IList<CustomAttributeData> attributes)
		{
			NullabilityState nullabilityState = NullabilityState.Unknown;
			NullabilityState nullabilityState2 = NullabilityState.Unknown;
			foreach (CustomAttributeData attribute in attributes)
			{
				if (attribute.AttributeType.Namespace == "System.Diagnostics.CodeAnalysis")
				{
					if (attribute.AttributeType.Name == "NotNullAttribute")
					{
						nullabilityState = NullabilityState.NotNull;
					}
					else if ((attribute.AttributeType.Name == "MaybeNullAttribute" || attribute.AttributeType.Name == "MaybeNullWhenAttribute") && nullabilityState == NullabilityState.Unknown && !IsValueTypeOrValueTypeByRef(nullability.Type))
					{
						nullabilityState = NullabilityState.Nullable;
					}
					else if (attribute.AttributeType.Name == "DisallowNullAttribute")
					{
						nullabilityState2 = NullabilityState.NotNull;
					}
					else if (attribute.AttributeType.Name == "AllowNullAttribute" && nullabilityState2 == NullabilityState.Unknown && !IsValueTypeOrValueTypeByRef(nullability.Type))
					{
						nullabilityState2 = NullabilityState.Nullable;
					}
				}
			}
			if (nullabilityState != 0)
			{
				nullability.ReadState = nullabilityState;
			}
			if (nullabilityState2 != 0)
			{
				nullability.WriteState = nullabilityState2;
			}
		}

		public NullabilityInfo Create(PropertyInfo propertyInfo)
		{
			ExceptionPolyfills.ThrowIfNull(propertyInfo, "propertyInfo");
			MethodInfo getMethod = propertyInfo.GetGetMethod(nonPublic: true);
			MethodInfo setMethod = propertyInfo.GetSetMethod(nonPublic: true);
			NullableAttributeStateParser parser = (((getMethod == null || IsPrivateOrInternalMethodAndAnnotationDisabled(getMethod)) && (setMethod == null || IsPrivateOrInternalMethodAndAnnotationDisabled(setMethod))) ? NullableAttributeStateParser.Unknown : CreateParser(propertyInfo.GetCustomAttributesData()));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(propertyInfo, propertyInfo.PropertyType, parser);
			if (getMethod != null)
			{
				CheckNullabilityAttributes(nullabilityInfo, getMethod.ReturnParameter.GetCustomAttributesData());
			}
			else
			{
				nullabilityInfo.ReadState = NullabilityState.Unknown;
			}
			if (setMethod != null)
			{
				ReadOnlySpan<ParameterInfo> parametersAsSpan = setMethod.GetParametersAsSpan();
				ParameterInfo parameterInfo = parametersAsSpan[parametersAsSpan.Length - 1];
				CheckNullabilityAttributes(nullabilityInfo, parameterInfo.GetCustomAttributesData());
			}
			else
			{
				nullabilityInfo.WriteState = NullabilityState.Unknown;
			}
			return nullabilityInfo;
		}

		private bool IsPrivateOrInternalMethodAndAnnotationDisabled(MethodBase method)
		{
			if ((method.IsPrivate || method.IsFamilyAndAssembly || method.IsAssembly) && IsPublicOnly(method.IsPrivate, method.IsFamilyAndAssembly, method.IsAssembly, method.Module))
			{
				return true;
			}
			return false;
		}

		public NullabilityInfo Create(EventInfo eventInfo)
		{
			ExceptionPolyfills.ThrowIfNull(eventInfo, "eventInfo");
			return GetNullabilityInfo(eventInfo, eventInfo.EventHandlerType, CreateParser(eventInfo.GetCustomAttributesData()));
		}

		public NullabilityInfo Create(FieldInfo fieldInfo)
		{
			ExceptionPolyfills.ThrowIfNull(fieldInfo, "fieldInfo");
			IList<CustomAttributeData> customAttributesData = fieldInfo.GetCustomAttributesData();
			NullableAttributeStateParser parser = (IsPrivateOrInternalFieldAndAnnotationDisabled(fieldInfo) ? NullableAttributeStateParser.Unknown : CreateParser(customAttributesData));
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(fieldInfo, fieldInfo.FieldType, parser);
			CheckNullabilityAttributes(nullabilityInfo, customAttributesData);
			return nullabilityInfo;
		}

		private bool IsPrivateOrInternalFieldAndAnnotationDisabled(FieldInfo fieldInfo)
		{
			if ((fieldInfo.IsPrivate || fieldInfo.IsFamilyAndAssembly || fieldInfo.IsAssembly) && IsPublicOnly(fieldInfo.IsPrivate, fieldInfo.IsFamilyAndAssembly, fieldInfo.IsAssembly, fieldInfo.Module))
			{
				return true;
			}
			return false;
		}

		private bool IsPublicOnly(bool isPrivate, bool isFamilyAndAssembly, bool isAssembly, Module module)
		{
			if (!_publicOnlyModules.TryGetValue(module, out var value))
			{
				value = PopulateAnnotationInfo(module.GetCustomAttributesData());
				_publicOnlyModules.Add(module, value);
			}
			if (value == NotAnnotatedStatus.None)
			{
				return false;
			}
			if (((isPrivate || isFamilyAndAssembly) && value.HasFlag(NotAnnotatedStatus.Private)) || (isAssembly && value.HasFlag(NotAnnotatedStatus.Internal)))
			{
				return true;
			}
			return false;
		}

		private static NotAnnotatedStatus PopulateAnnotationInfo(IList<CustomAttributeData> customAttributes)
		{
			bool flag = default(bool);
			foreach (CustomAttributeData customAttribute in customAttributes)
			{
				if (customAttribute.AttributeType.Name == "NullablePublicOnlyAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1)
				{
					object value = customAttribute.ConstructorArguments[0].Value;
					int num;
					if (value is bool)
					{
						flag = (bool)value;
						num = 1;
					}
					else
					{
						num = 0;
					}
					if (((uint)num & (flag ? 1u : 0u)) != 0)
					{
						return NotAnnotatedStatus.Private | NotAnnotatedStatus.Internal;
					}
					return NotAnnotatedStatus.Private;
				}
			}
			return NotAnnotatedStatus.None;
		}

		private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser)
		{
			int index = 0;
			NullabilityInfo nullabilityInfo = GetNullabilityInfo(memberInfo, type, parser, ref index);
			if (nullabilityInfo.ReadState != 0)
			{
				TryLoadGenericMetaTypeNullability(memberInfo, nullabilityInfo);
			}
			return nullabilityInfo;
		}

		private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, NullableAttributeStateParser parser, ref int index)
		{
			NullabilityState state = NullabilityState.Unknown;
			NullabilityInfo elementType = null;
			NullabilityInfo[] array = Array.Empty<NullabilityInfo>();
			Type type2 = type;
			if (type2.IsByRef || type2.IsPointer)
			{
				type2 = type2.GetElementType();
			}
			if (type2.IsValueType)
			{
				Type underlyingType = Nullable.GetUnderlyingType(type2);
				if ((object)underlyingType != null)
				{
					type2 = underlyingType;
					state = NullabilityState.Nullable;
				}
				else
				{
					state = NullabilityState.NotNull;
				}
				if (type2.IsGenericType)
				{
					index++;
				}
			}
			else
			{
				if (!parser.ParseNullableState(index++, ref state))
				{
					NullabilityState? nullableContext = GetNullableContext(memberInfo);
					if (nullableContext.HasValue)
					{
						NullabilityState valueOrDefault = nullableContext.GetValueOrDefault();
						state = valueOrDefault;
					}
				}
				if (type2.IsArray)
				{
					elementType = GetNullabilityInfo(memberInfo, type2.GetElementType(), parser, ref index);
				}
			}
			if (type2.IsGenericType)
			{
				Type[] genericArguments = type2.GetGenericArguments();
				array = new NullabilityInfo[genericArguments.Length];
				for (int i = 0; i < genericArguments.Length; i++)
				{
					array[i] = GetNullabilityInfo(memberInfo, genericArguments[i], parser, ref index);
				}
			}
			return new NullabilityInfo(type, state, state, elementType, array);
		}

		private static NullableAttributeStateParser CreateParser(IList<CustomAttributeData> customAttributes)
		{
			foreach (CustomAttributeData customAttribute in customAttributes)
			{
				if (customAttribute.AttributeType.Name == "NullableAttribute" && customAttribute.AttributeType.Namespace == "System.Runtime.CompilerServices" && customAttribute.ConstructorArguments.Count == 1)
				{
					return new NullableAttributeStateParser(customAttribute.ConstructorArguments[0].Value);
				}
			}
			return new NullableAttributeStateParser(null);
		}

		private void TryLoadGenericMetaTypeNullability(MemberInfo memberInfo, NullabilityInfo nullability)
		{
			MemberInfo memberMetadataDefinition = GetMemberMetadataDefinition(memberInfo);
			Type type = null;
			if (memberMetadataDefinition is FieldInfo fieldInfo)
			{
				type = fieldInfo.FieldType;
			}
			else if (memberMetadataDefinition is PropertyInfo property)
			{
				type = GetPropertyMetaType(property);
			}
			if (type != null)
			{
				CheckGenericParameters(nullability, memberMetadataDefinition, type, memberInfo.ReflectedType);
			}
		}

		private static MemberInfo GetMemberMetadataDefinition(MemberInfo member)
		{
			Type declaringType = member.DeclaringType;
			if (declaringType != null && declaringType.IsGenericType && !declaringType.IsGenericTypeDefinition)
			{
				return NetstandardHelpers.GetMemberWithSameMetadataDefinitionAs(declaringType.GetGenericTypeDefinition(), member);
			}
			return member;
		}

		private static Type GetPropertyMetaType(PropertyInfo property)
		{
			MethodInfo getMethod = property.GetGetMethod(nonPublic: true);
			if ((object)getMethod != null)
			{
				return getMethod.ReturnType;
			}
			return property.GetSetMethod(nonPublic: true).GetParametersAsSpan()[0].ParameterType;
		}

		private void CheckGenericParameters(NullabilityInfo nullability, MemberInfo metaMember, Type metaType, Type reflectedType)
		{
			if (metaType.IsGenericParameter)
			{
				if (nullability.ReadState == NullabilityState.NotNull)
				{
					TryUpdateGenericParameterNullability(nullability, metaType, reflectedType);
				}
			}
			else
			{
				if (!metaType.ContainsGenericParameters)
				{
					return;
				}
				if (nullability.GenericTypeArguments.Length != 0)
				{
					Type[] genericArguments = metaType.GetGenericArguments();
					for (int i = 0; i < genericArguments.Length; i++)
					{
						CheckGenericParameters(nullability.GenericTypeArguments[i], metaMember, genericArguments[i], reflectedType);
					}
					return;
				}
				NullabilityInfo elementType = nullability.ElementType;
				if (elementType != null && metaType.IsArray)
				{
					CheckGenericParameters(elementType, metaMember, metaType.GetElementType(), reflectedType);
				}
				else if (metaType.IsByRef)
				{
					CheckGenericParameters(nullability, metaMember, metaType.GetElementType(), reflectedType);
				}
			}
		}

		private bool TryUpdateGenericParameterNullability(NullabilityInfo nullability, Type genericParameter, Type reflectedType)
		{
			if ((object)reflectedType != null && !genericParameter.IsGenericMethodParameter() && TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, reflectedType, reflectedType))
			{
				return true;
			}
			if (IsValueTypeOrValueTypeByRef(nullability.Type))
			{
				return true;
			}
			NullabilityState state = NullabilityState.Unknown;
			if (CreateParser(genericParameter.GetCustomAttributesData()).ParseNullableState(0, ref state))
			{
				nullability.ReadState = state;
				nullability.WriteState = state;
				return true;
			}
			NullabilityState? nullableContext = GetNullableContext(genericParameter);
			if (nullableContext.HasValue)
			{
				NullabilityState writeState = (nullability.ReadState = nullableContext.GetValueOrDefault());
				nullability.WriteState = writeState;
				return true;
			}
			return false;
		}

		private bool TryUpdateGenericTypeParameterNullabilityFromReflectedType(NullabilityInfo nullability, Type genericParameter, Type context, Type reflectedType)
		{
			Type type2 = ((context.IsGenericType && !context.IsGenericTypeDefinition) ? context.GetGenericTypeDefinition() : context);
			if (genericParameter.DeclaringType == type2)
			{
				return false;
			}
			Type baseType = type2.BaseType;
			if ((object)baseType == null)
			{
				return false;
			}
			if (!baseType.IsGenericType || (baseType.IsGenericTypeDefinition ? baseType : baseType.GetGenericTypeDefinition()) != genericParameter.DeclaringType)
			{
				return TryUpdateGenericTypeParameterNullabilityFromReflectedType(nullability, genericParameter, baseType, reflectedType);
			}
			Type[] genericArguments = baseType.GetGenericArguments();
			Type type3 = genericArguments[genericParameter.GenericParameterPosition];
			if (type3.IsGenericParameter)
			{
				return TryUpdateGenericParameterNullability(nullability, type3, reflectedType);
			}
			NullableAttributeStateParser parser = CreateParser(type2.GetCustomAttributesData());
			int index = 1;
			for (int i = 0; i < genericParameter.GenericParameterPosition; i++)
			{
				index += CountNullabilityStates(genericArguments[i]);
			}
			return TryPopulateNullabilityInfo(nullability, parser, ref index);
			static int CountNullabilityStates(Type type)
			{
				Type type4 = Nullable.GetUnderlyingType(type) ?? type;
				if (type4.IsGenericType)
				{
					int num = 1;
					Type[] genericArguments2 = type4.GetGenericArguments();
					foreach (Type type5 in genericArguments2)
					{
						num += CountNullabilityStates(type5);
					}
					return num;
				}
				if (type4.HasElementType)
				{
					return (type4.IsArray ? 1 : 0) + CountNullabilityStates(type4.GetElementType());
				}
				return (!type.IsValueType) ? 1 : 0;
			}
		}

		private static bool TryPopulateNullabilityInfo(NullabilityInfo nullability, NullableAttributeStateParser parser, ref int index)
		{
			bool flag = IsValueTypeOrValueTypeByRef(nullability.Type);
			if (!flag)
			{
				NullabilityState state = NullabilityState.Unknown;
				if (!parser.ParseNullableState(index, ref state))
				{
					return false;
				}
				nullability.ReadState = state;
				nullability.WriteState = state;
			}
			if (!flag || (Nullable.GetUnderlyingType(nullability.Type) ?? nullability.Type).IsGenericType)
			{
				index++;
			}
			if (nullability.GenericTypeArguments.Length != 0)
			{
				NullabilityInfo[] genericTypeArguments = nullability.GenericTypeArguments;
				for (int i = 0; i < genericTypeArguments.Length; i++)
				{
					TryPopulateNullabilityInfo(genericTypeArguments[i], parser, ref index);
				}
			}
			else
			{
				NullabilityInfo elementType = nullability.ElementType;
				if (elementType != null)
				{
					TryPopulateNullabilityInfo(elementType, parser, ref index);
				}
			}
			return true;
		}

		private static NullabilityState TranslateByte(object value)
		{
			if (!(value is byte b))
			{
				return NullabilityState.Unknown;
			}
			return TranslateByte(b);
		}

		private static NullabilityState TranslateByte(byte b)
		{
			return b switch
			{
				1 => NullabilityState.NotNull, 
				2 => NullabilityState.Nullable, 
				_ => NullabilityState.Unknown, 
			};
		}

		private static bool IsValueTypeOrValueTypeByRef(Type type)
		{
			if (!type.IsValueType)
			{
				if (type.IsByRef || type.IsPointer)
				{
					return type.GetElementType().IsValueType;
				}
				return false;
			}
			return true;
		}
	}
	internal static class NetstandardHelpers
	{
		[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern", Justification = "This is finding the MemberInfo with the same MetadataToken as specified MemberInfo. If the specified MemberInfo exists and wasn't trimmed, then the current Type's MemberInfo couldn't have been trimmed.")]
		public static MemberInfo GetMemberWithSameMetadataDefinitionAs(this Type type, MemberInfo member)
		{
			ExceptionPolyfills.ThrowIfNull(member, "member");
			MemberInfo[] members = type.GetMembers(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MemberInfo memberInfo in members)
			{
				if (HasSameMetadataDefinitionAs(memberInfo, member))
				{
					return memberInfo;
				}
			}
			throw new MissingMemberException(type.FullName, member.Name);
		}

		private static bool HasSameMetadataDefinitionAs(this MemberInfo info, MemberInfo other)
		{
			if (info.MetadataToken != other.MetadataToken)
			{
				return false;
			}
			if (!info.Module.Equals(other.Module))
			{
				return false;
			}
			return true;
		}

		public static bool IsGenericMethodParameter(this Type type)
		{
			if (type.IsGenericParameter)
			{
				return (object)type.DeclaringMethod != null;
			}
			return false;
		}

		public static ReadOnlySpan<ParameterInfo> GetParametersAsSpan(this MethodBase metaMethod)
		{
			return metaMethod.GetParameters();
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Field, AllowMultiple = true, Inherited = false)]
	internal sealed class DynamicDependencyAttribute : Attribute
	{
		public string MemberSignature { get; }

		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public Type Type { get; }

		public string TypeName { get; }

		public string AssemblyName { get; }

		[Obsolete("This property is no longer supported.")]
		[EditorBrowsable(EditorBrowsableState.Never)]
		public string Condition { get; set; }

		public DynamicDependencyAttribute(string memberSignature)
		{
			MemberSignature = memberSignature;
		}

		public DynamicDependencyAttribute(string memberSignature, Type type)
		{
			MemberSignature = memberSignature;
			Type = type;
		}

		public DynamicDependencyAttribute(string memberSignature, string typeName, string assemblyName)
		{
			MemberSignature = memberSignature;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, Type type)
		{
			MemberTypes = memberTypes;
			Type = type;
		}

		public DynamicDependencyAttribute(DynamicallyAccessedMemberTypes memberTypes, string typeName, string assemblyName)
		{
			MemberTypes = memberTypes;
			TypeName = typeName;
			AssemblyName = assemblyName;
		}
	}
	[CompilerLoweringPreserve]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, Inherited = false)]
	internal sealed class DynamicallyAccessedMembersAttribute : Attribute
	{
		public DynamicallyAccessedMemberTypes MemberTypes { get; }

		public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes)
		{
			MemberTypes = memberTypes;
		}
	}
	[Flags]
	internal enum DynamicallyAccessedMemberTypes
	{
		None = 0,
		PublicParameterlessConstructor = 1,
		PublicConstructors = 3,
		NonPublicConstructors = 4,
		PublicMethods = 8,
		NonPublicMethods = 0x10,
		PublicFields = 0x20,
		NonPublicFields = 0x40,
		PublicNestedTypes = 0x80,
		NonPublicNestedTypes = 0x100,
		PublicProperties = 0x200,
		NonPublicProperties = 0x400,
		PublicEvents = 0x800,
		NonPublicEvents = 0x1000,
		Interfaces = 0x2000,
		NonPublicConstructorsWithInherited = 0x4004,
		NonPublicMethodsWithInherited = 0x8010,
		NonPublicFieldsWithInherited = 0x10040,
		NonPublicNestedTypesWithInherited = 0x20100,
		NonPublicPropertiesWithInherited = 0x40400,
		NonPublicEventsWithInherited = 0x81000,
		PublicConstructorsWithInherited = 0x100003,
		PublicNestedTypesWithInherited = 0x200080,
		AllConstructors = 0x104007,
		AllMethods = 0x8018,
		AllFields = 0x10060,
		AllNestedTypes = 0x220180,
		AllProperties = 0x40600,
		AllEvents = 0x81800,
		[EditorBrowsable(EditorBrowsableState.Never)]
		All = -1
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresUnreferencedCodeAttribute : Attribute
	{
		public bool ExcludeStatics { get; set; }

		public string Message { get; }

		public string Url { get; set; }

		public RequiresUnreferencedCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
	internal sealed class UnconditionalSuppressMessageAttribute : Attribute
	{
		public string Category { get; }

		public string CheckId { get; }

		public string Scope { get; set; }

		public string Target { get; set; }

		public string MessageId { get; set; }

		public string Justification { get; set; }

		public UnconditionalSuppressMessageAttribute(string category, string checkId)
		{
			Category = category;
			CheckId = checkId;
		}
	}
	[AttributeUsage(AttributeTargets.Property, Inherited = false)]
	internal sealed class FeatureSwitchDefinitionAttribute : Attribute
	{
		public string SwitchName { get; }

		public FeatureSwitchDefinitionAttribute(string switchName)
		{
			SwitchName = switchName;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class StringSyntaxAttribute : Attribute
	{
		public const string CompositeFormat = "CompositeFormat";

		public const string DateOnlyFormat = "DateOnlyFormat";

		public const string DateTimeFormat = "DateTimeFormat";

		public const string EnumFormat = "EnumFormat";

		public const string GuidFormat = "GuidFormat";

		public const string Json = "Json";

		public const string NumericFormat = "NumericFormat";

		public const string Regex = "Regex";

		public const string TimeOnlyFormat = "TimeOnlyFormat";

		public const string TimeSpanFormat = "TimeSpanFormat";

		public const string Uri = "Uri";

		public const string Xml = "Xml";

		public string Syntax { get; }

		public object[] Arguments { get; }

		public StringSyntaxAttribute(string syntax)
		{
			Syntax = syntax;
			Arguments = Array.Empty<object>();
		}

		public StringSyntaxAttribute(string syntax, params object[] arguments)
		{
			Syntax = syntax;
			Arguments = arguments;
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method, Inherited = false)]
	internal sealed class RequiresDynamicCodeAttribute : Attribute
	{
		public bool ExcludeStatics { get; set; }

		public string Message { get; }

		public string Url { get; set; }

		public RequiresDynamicCodeAttribute(string message)
		{
			Message = message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class AllowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DisallowNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class MaybeNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)]
	internal sealed class NotNullAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class MaybeNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public MaybeNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class NotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public NotNullWhenAttribute(bool returnValue)
		{
			ReturnValue = returnValue;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)]
	internal sealed class NotNullIfNotNullAttribute : Attribute
	{
		public string ParameterName { get; }

		public NotNullIfNotNullAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
	[AttributeUsage(AttributeTargets.Method, Inherited = false)]
	internal sealed class DoesNotReturnAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
	internal sealed class DoesNotReturnIfAttribute : Attribute
	{
		public bool ParameterValue { get; }

		public DoesNotReturnIfAttribute(bool parameterValue)
		{
			ParameterValue = parameterValue;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Collections
{
	internal static class HashHelpers
	{
		public const uint HashCollisionThreshold = 100u;

		public const int MaxPrimeArrayLength = 2147483587;

		public const int HashPrime = 101;

		internal static ReadOnlySpan<int> Primes
		{
			get
			{
				object obj = global::<PrivateImplementationDetails>.74BCD6ED20AF2231F2BB1CDE814C5F4FF48E54BAC46029EEF90DDF4A208E2B20_A6;
				if (obj == null)
				{
					obj = new int[72

BepInEx/core/System.Threading.Channels.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;
using FxResources.System.Threading.Channels;
using Internal;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyDefaultAlias("System.Threading.Channels")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("IsAotCompatible", "True")]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyCopyright("© Microsoft Corporation. All rights reserved.")]
[assembly: AssemblyDescription("Provides types for passing data between producers and consumers.\r\n\r\nCommonly Used Types:\r\nSystem.Threading.Channel\r\nSystem.Threading.Channel<T>")]
[assembly: AssemblyFileVersion("10.0.125.57005")]
[assembly: AssemblyInformationalVersion("10.0.1+fad253f51b461736dfd3cd9c15977bb7493becef")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("System.Threading.Channels")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/dotnet")]
[assembly: AssemblyVersion("10.0.0.0")]
[module: RefSafetyRules(11)]
[module: System.Runtime.CompilerServices.NullablePublicOnly(false)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public NullablePublicOnlyAttribute(bool P_0)
		{
			IncludesInternals = P_0;
		}
	}
	[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;
		}
	}
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class ExtensionMarkerAttribute : Attribute
	{
		public ExtensionMarkerAttribute(string name)
		{
		}
	}
}
namespace FxResources.System.Threading.Channels
{
	internal static class SR
	{
	}
}
namespace Internal
{
	internal static class PaddingHelpers
	{
		internal const int CACHE_LINE_SIZE = 128;
	}
	[StructLayout(LayoutKind.Explicit, Size = 124)]
	internal struct PaddingFor32
	{
	}
}
namespace System
{
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal readonly struct VoidResult
	{
	}
	internal static class Obsoletions
	{
		internal const string SharedUrlFormat = "https://aka.ms/dotnet-warnings/{0}";

		internal const string SystemTextEncodingUTF7Message = "The UTF-7 encoding is insecure and should not be used. Consider using UTF-8 instead.";

		internal const string SystemTextEncodingUTF7DiagId = "SYSLIB0001";

		internal const string PrincipalPermissionAttributeMessage = "PrincipalPermissionAttribute is not honored by the runtime and must not be used.";

		internal const string PrincipalPermissionAttributeDiagId = "SYSLIB0002";

		internal const string CodeAccessSecurityMessage = "Code Access Security is not supported or honored by the runtime.";

		internal const string CodeAccessSecurityDiagId = "SYSLIB0003";

		internal const string ConstrainedExecutionRegionMessage = "The Constrained Execution Region (CER) feature is not supported.";

		internal const string ConstrainedExecutionRegionDiagId = "SYSLIB0004";

		internal const string GlobalAssemblyCacheMessage = "The Global Assembly Cache is not supported.";

		internal const string GlobalAssemblyCacheDiagId = "SYSLIB0005";

		internal const string ThreadAbortMessage = "Thread.Abort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadResetAbortMessage = "Thread.ResetAbort is not supported and throws PlatformNotSupportedException.";

		internal const string ThreadAbortDiagId = "SYSLIB0006";

		internal const string DefaultCryptoAlgorithmsMessage = "The default implementation of this cryptography algorithm is not supported.";

		internal const string DefaultCryptoAlgorithmsDiagId = "SYSLIB0007";

		internal const string CreatePdbGeneratorMessage = "The CreatePdbGenerator API is not supported and throws PlatformNotSupportedException.";

		internal const string CreatePdbGeneratorDiagId = "SYSLIB0008";

		internal const string AuthenticationManagerMessage = "AuthenticationManager is not supported. Methods will no-op or throw PlatformNotSupportedException.";

		internal const string AuthenticationManagerDiagId = "SYSLIB0009";

		internal const string RemotingApisMessage = "This Remoting API is not supported and throws PlatformNotSupportedException.";

		internal const string RemotingApisDiagId = "SYSLIB0010";

		internal const string BinaryFormatterMessage = "BinaryFormatter serialization is obsolete and should not be used. See https://aka.ms/binaryformatter for more information.";

		internal const string BinaryFormatterDiagId = "SYSLIB0011";

		internal const string CodeBaseMessage = "Assembly.CodeBase and Assembly.EscapedCodeBase are only included for .NET Framework compatibility. Use Assembly.Location instead.";

		internal const string CodeBaseDiagId = "SYSLIB0012";

		internal const string EscapeUriStringMessage = "Uri.EscapeUriString can corrupt the Uri string in some cases. Consider using Uri.EscapeDataString for query string components instead.";

		internal const string EscapeUriStringDiagId = "SYSLIB0013";

		internal const string WebRequestMessage = "WebRequest, HttpWebRequest, ServicePoint, and WebClient are obsolete. Use HttpClient instead.";

		internal const string WebRequestDiagId = "SYSLIB0014";

		internal const string DisablePrivateReflectionAttributeMessage = "DisablePrivateReflectionAttribute has no effect in .NET 6.0+.";

		internal const string DisablePrivateReflectionAttributeDiagId = "SYSLIB0015";

		internal const string GetContextInfoMessage = "Use the Graphics.GetContextInfo overloads that accept arguments for better performance and fewer allocations.";

		internal const string GetContextInfoDiagId = "SYSLIB0016";

		internal const string StrongNameKeyPairMessage = "Strong name signing is not supported and throws PlatformNotSupportedException.";

		internal const string StrongNameKeyPairDiagId = "SYSLIB0017";

		internal const string ReflectionOnlyLoadingMessage = "ReflectionOnly loading is not supported and throws PlatformNotSupportedException.";

		internal const string ReflectionOnlyLoadingDiagId = "SYSLIB0018";

		internal const string RuntimeEnvironmentMessage = "RuntimeEnvironment members SystemConfigurationFile, GetRuntimeInterfaceAsIntPtr, and GetRuntimeInterfaceAsObject are not supported and throw PlatformNotSupportedException.";

		internal const string RuntimeEnvironmentDiagId = "SYSLIB0019";

		internal const string JsonSerializerOptionsIgnoreNullValuesMessage = "JsonSerializerOptions.IgnoreNullValues is obsolete. To ignore null values when serializing, set DefaultIgnoreCondition to JsonIgnoreCondition.WhenWritingNull.";

		internal const string JsonSerializerOptionsIgnoreNullValuesDiagId = "SYSLIB0020";

		internal const string DerivedCryptographicTypesMessage = "Derived cryptographic types are obsolete. Use the Create method on the base type instead.";

		internal const string DerivedCryptographicTypesDiagId = "SYSLIB0021";

		internal const string RijndaelMessage = "The Rijndael and RijndaelManaged types are obsolete. Use Aes instead.";

		internal const string RijndaelDiagId = "SYSLIB0022";

		internal const string RNGCryptoServiceProviderMessage = "RNGCryptoServiceProvider is obsolete. To generate a random number, use one of the RandomNumberGenerator static methods instead.";

		internal const string RNGCryptoServiceProviderDiagId = "SYSLIB0023";

		internal const string AppDomainCreateUnloadMessage = "Creating and unloading AppDomains is not supported and throws an exception.";

		internal const string AppDomainCreateUnloadDiagId = "SYSLIB0024";

		internal const string SuppressIldasmAttributeMessage = "SuppressIldasmAttribute has no effect in .NET 6.0+.";

		internal const string SuppressIldasmAttributeDiagId = "SYSLIB0025";

		internal const string X509CertificateImmutableMessage = "X509Certificate and X509Certificate2 are immutable. Use X509CertificateLoader to create a new certificate.";

		internal const string X509CertificateImmutableDiagId = "SYSLIB0026";

		internal const string PublicKeyPropertyMessage = "PublicKey.Key is obsolete. Use the appropriate method to get the public key, such as GetRSAPublicKey.";

		internal const string PublicKeyPropertyDiagId = "SYSLIB0027";

		internal const string X509CertificatePrivateKeyMessage = "X509Certificate2.PrivateKey is obsolete. Use the appropriate method to get the private key, such as GetRSAPrivateKey, or use the CopyWithPrivateKey method to create a new instance with a private key.";

		internal const string X509CertificatePrivateKeyDiagId = "SYSLIB0028";

		internal const string ProduceLegacyHmacValuesMessage = "ProduceLegacyHmacValues is obsolete. Producing legacy HMAC values is not supported.";

		internal const string ProduceLegacyHmacValuesDiagId = "SYSLIB0029";

		internal const string UseManagedSha1Message = "HMACSHA1 always uses the algorithm implementation provided by the platform. Use a constructor without the useManagedSha1 parameter.";

		internal const string UseManagedSha1DiagId = "SYSLIB0030";

		internal const string CryptoConfigEncodeOIDMessage = "EncodeOID is obsolete. Use the ASN.1 functionality provided in System.Formats.Asn1.";

		internal const string CryptoConfigEncodeOIDDiagId = "SYSLIB0031";

		internal const string CorruptedStateRecoveryMessage = "Recovery from corrupted process state exceptions is not supported; HandleProcessCorruptedStateExceptionsAttribute is ignored.";

		internal const string CorruptedStateRecoveryDiagId = "SYSLIB0032";

		internal const string Rfc2898CryptDeriveKeyMessage = "Rfc2898DeriveBytes.CryptDeriveKey is obsolete and is not supported. Use PasswordDeriveBytes.CryptDeriveKey instead.";

		internal const string Rfc2898CryptDeriveKeyDiagId = "SYSLIB0033";

		internal const string CmsSignerCspParamsCtorMessage = "CmsSigner(CspParameters) is obsolete and is not supported. Use an alternative constructor instead.";

		internal const string CmsSignerCspParamsCtorDiagId = "SYSLIB0034";

		internal const string SignerInfoCounterSigMessage = "ComputeCounterSignature without specifying a CmsSigner is obsolete and is not supported. Use the overload that accepts a CmsSigner.";

		internal const string SignerInfoCounterSigDiagId = "SYSLIB0035";

		internal const string RegexCompileToAssemblyMessage = "Regex.CompileToAssembly is obsolete and not supported. Use the GeneratedRegexAttribute with the regular expression source generator instead.";

		internal const string RegexCompileToAssemblyDiagId = "SYSLIB0036";

		internal const string AssemblyNameMembersMessage = "AssemblyName members HashAlgorithm, ProcessorArchitecture, and VersionCompatibility are obsolete and not supported.";

		internal const string AssemblyNameMembersDiagId = "SYSLIB0037";

		internal const string SystemDataSerializationFormatBinaryMessage = "SerializationFormat.Binary is obsolete and should not be used. See https://aka.ms/serializationformat-binary-obsolete for more information.";

		internal const string SystemDataSerializationFormatBinaryDiagId = "SYSLIB0038";

		internal const string TlsVersion10and11Message = "TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults.";

		internal const string TlsVersion10and11DiagId = "SYSLIB0039";

		internal const string EncryptionPolicyMessage = "EncryptionPolicy.NoEncryption and AllowEncryption significantly reduce security and should not be used in production code.";

		internal const string EncryptionPolicyDiagId = "SYSLIB0040";

		internal const string EccXmlExportImportMessage = "ToXmlString and FromXmlString have no implementation for ECC types, and are obsolete. Use a standard import and export format such as ExportSubjectPublicKeyInfo or ImportSubjectPublicKeyInfo for public keys and ExportPkcs8PrivateKey or ImportPkcs8PrivateKey for private keys.";

		internal const string EccXmlExportImportDiagId = "SYSLIB0042";

		internal const string EcDhPublicKeyBlobMessage = "ECDiffieHellmanPublicKey.ToByteArray() and the associated constructor do not have a consistent and interoperable implementation on all platforms. Use ECDiffieHellmanPublicKey.ExportSubjectPublicKeyInfo() instead.";

		internal const string EcDhPublicKeyBlobDiagId = "SYSLIB0043";

		internal const string AssemblyNameCodeBaseMessage = "AssemblyName.CodeBase and AssemblyName.EscapedCodeBase are obsolete. Using them for loading an assembly is not supported.";

		internal const string AssemblyNameCodeBaseDiagId = "SYSLIB0044";

		internal const string CryptoStringFactoryMessage = "Cryptographic factory methods accepting an algorithm name are obsolete. Use the parameterless Create factory method on the algorithm type instead.";

		internal const string CryptoStringFactoryDiagId = "SYSLIB0045";

		internal const string ControlledExecutionRunMessage = "ControlledExecution.Run method may corrupt the process and should not be used in production code.";

		internal const string ControlledExecutionRunDiagId = "SYSLIB0046";

		internal const string XmlSecureResolverMessage = "XmlSecureResolver is obsolete. Use XmlResolver.ThrowingResolver instead when attempting to forbid XML external entity resolution.";

		internal const string XmlSecureResolverDiagId = "SYSLIB0047";

		internal const string RsaEncryptDecryptValueMessage = "RSA.EncryptValue and DecryptValue are not supported and throw NotSupportedException. Use RSA.Encrypt and RSA.Decrypt instead.";

		internal const string RsaEncryptDecryptDiagId = "SYSLIB0048";

		internal const string JsonSerializerOptionsAddContextMessage = "JsonSerializerOptions.AddContext is obsolete. To register a JsonSerializerContext, use either the TypeInfoResolver or TypeInfoResolverChain properties.";

		internal const string JsonSerializerOptionsAddContextDiagId = "SYSLIB0049";

		internal const string LegacyFormatterMessage = "Formatter-based serialization is obsolete and should not be used.";

		internal const string LegacyFormatterDiagId = "SYSLIB0050";

		internal const string LegacyFormatterImplMessage = "This API supports obsolete formatter-based serialization. It should not be called or extended by application code.";

		internal const string LegacyFormatterImplDiagId = "SYSLIB0051";

		internal const string RegexExtensibilityImplMessage = "This API supports obsolete mechanisms for Regex extensibility. It is not supported.";

		internal const string RegexExtensibilityDiagId = "SYSLIB0052";

		internal const string AesGcmTagConstructorMessage = "AesGcm should indicate the required tag size for encryption and decryption. Use a constructor that accepts the tag size.";

		internal const string AesGcmTagConstructorDiagId = "SYSLIB0053";

		internal const string ThreadVolatileReadWriteMessage = "Thread.VolatileRead and Thread.VolatileWrite are obsolete. Use Volatile.Read or Volatile.Write respectively instead.";

		internal const string ThreadVolatileReadWriteDiagId = "SYSLIB0054";

		internal const string ArmIntrinsicPerformsUnsignedOperationMessage = "The underlying hardware instruction does not perform a signed saturate narrowing operation, and it always returns an unsigned result. Use the unsigned overload instead.";

		internal const string ArmIntrinsicPerformsUnsignedOperationDiagId = "SYSLIB0055";

		internal const string LoadFromHashAlgorithmMessage = "LoadFrom with a custom AssemblyHashAlgorithm is obsolete. Use overloads without an AssemblyHashAlgorithm.";

		internal const string LoadFromHashAlgorithmDiagId = "SYSLIB0056";

		internal const string X509CtorCertDataObsoleteMessage = "Loading certificate data through the constructor or Import is obsolete. Use X509CertificateLoader instead to load certificates.";

		internal const string X509CtorCertDataObsoleteDiagId = "SYSLIB0057";

		internal const string TlsCipherAlgorithmEnumsMessage = "KeyExchangeAlgorithm, KeyExchangeStrength, CipherAlgorithm, CipherStrength, HashAlgorithm and HashStrength properties of SslStream are obsolete. Use NegotiatedCipherSuite instead.";

		internal const string TlsCipherAlgorithmEnumsDiagId = "SYSLIB0058";

		internal const string SystemEventsEventsThreadShutdownMessage = "SystemEvents.EventsThreadShutdown callbacks are not run before the process exits. Use AppDomain.ProcessExit instead.";

		internal const string SystemEventsEventsThreadShutdownDiagId = "SYSLIB0059";

		internal const string Rfc2898DeriveBytesCtorMessage = "The constructors on Rfc2898DeriveBytes are obsolete. Use the static Pbkdf2 method instead.";

		internal const string Rfc2898DeriveBytesCtorDiagId = "SYSLIB0060";

		internal const string QueryableMinByMaxByTSourceObsoleteMessage = "The Queryable MinBy and MaxBy taking an IComparer<TSource> are obsolete. Use the new ones that take an IComparer<TKey>.";

		internal const string QueryableMinByMaxByTSourceObsoleteDiagId = "SYSLIB0061";

		internal const string XsltSettingsEnableScriptMessage = "XSLT Script blocks are not supported.";

		internal const string XsltSettingsEnableScriptDiagId = "SYSLIB0062";
	}
	internal static class SR
	{
		private static readonly bool s_usingResourceKeys = GetUsingResourceKeysSwitchValue();

		private static ResourceManager s_resourceManager;

		internal static ResourceManager ResourceManager => s_resourceManager ?? (s_resourceManager = new ResourceManager(typeof(SR)));

		internal static string ChannelClosedException_DefaultMessage => GetResourceString("ChannelClosedException_DefaultMessage");

		internal static string InvalidOperation_IncompleteAsyncOperation => GetResourceString("InvalidOperation_IncompleteAsyncOperation");

		internal static string InvalidOperation_MultipleContinuations => GetResourceString("InvalidOperation_MultipleContinuations");

		internal static string InvalidOperation_IncorrectToken => GetResourceString("InvalidOperation_IncorrectToken");

		private static bool GetUsingResourceKeysSwitchValue()
		{
			if (!AppContext.TryGetSwitch("System.Resources.UseSystemResourceKeys", out var isEnabled))
			{
				return false;
			}
			return isEnabled;
		}

		internal static bool UsingResourceKeys()
		{
			return s_usingResourceKeys;
		}

		private static string GetResourceString(string resourceKey)
		{
			if (UsingResourceKeys())
			{
				return resourceKey;
			}
			string result = null;
			try
			{
				result = ResourceManager.GetString(resourceKey);
			}
			catch (MissingManifestResourceException)
			{
			}
			return result;
		}

		private static string GetResourceString(string resourceKey, string defaultString)
		{
			string resourceString = GetResourceString(resourceKey);
			if (!(resourceKey == resourceString) && resourceString != null)
			{
				return resourceString;
			}
			return defaultString;
		}

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

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

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

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

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

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

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

		internal static string Format(IFormatProvider provider, string resourceFormat, params object[] args)
		{
			if (args != null)
			{
				if (UsingResourceKeys())
				{
					return resourceFormat + ", " + string.Join(", ", args);
				}
				return string.Format(provider, resourceFormat, args);
			}
			return resourceFormat;
		}
	}
	internal static class ExceptionPolyfills
	{
		[SpecialName]
		public sealed class <G>$E6188BA5B951F1F7AA9135E0EBB76F2B
		{
			[SpecialName]
			public static class <M>$96F0261AC622664B8B003966835C0332
			{
			}

			[ExtensionMarker("<M>$96F0261AC622664B8B003966835C0332")]
			public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
			{
				throw null;
			}
		}

		[SpecialName]
		public sealed class <G>$3F30F31B33543D5FB8E174FB4FD780B9
		{
			[SpecialName]
			public static class <M>$1F10CFA08738E6D8AF61CBECC6763DBC
			{
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
			{
				throw null;
			}

			[ExtensionMarker("<M>$1F10CFA08738E6D8AF61CBECC6763DBC")]
			public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
			{
				throw null;
			}
		}

		public static void ThrowIfNull([NotNull] object argument, [CallerArgumentExpression("argument")] string paramName = null)
		{
			if (argument == null)
			{
				ThrowArgumentNullException(paramName);
			}
		}

		[DoesNotReturn]
		private static void ThrowArgumentNullException(string paramName)
		{
			throw new ArgumentNullException(paramName);
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, object instance)
		{
			if (condition)
			{
				ThrowObjectDisposedException(instance);
			}
		}

		public static void ThrowIf([DoesNotReturnIf(true)] bool condition, Type type)
		{
			if (condition)
			{
				ThrowObjectDisposedException(type);
			}
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(object instance)
		{
			throw new ObjectDisposedException(instance?.GetType().FullName);
		}

		[DoesNotReturn]
		private static void ThrowObjectDisposedException(Type type)
		{
			throw new ObjectDisposedException(type?.FullName);
		}
	}
}
namespace System.Diagnostics.CodeAnalysis
{
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullAttribute : Attribute
	{
		public string[] Members { get; }

		public MemberNotNullAttribute(string member)
		{
			Members = new string[1] { member };
		}

		public MemberNotNullAttribute(params string[] members)
		{
			Members = members;
		}
	}
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)]
	internal sealed class MemberNotNullWhenAttribute : Attribute
	{
		public bool ReturnValue { get; }

		public string[] Members { get; }

		public MemberNotNullWhenAttribute(bool returnValue, string member)
		{
			ReturnValue = returnValue;
			Members = new string[1] { member };
		}

		public MemberNotNullWhenAttribute(bool returnValue, params string[] members)
		{
			ReturnValue = returnValue;
			Members = members;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
	internal sealed class CallerArgumentExpressionAttribute : Attribute
	{
		public string ParameterName { get; }

		public CallerArgumentExpressionAttribute(string parameterName)
		{
			ParameterName = parameterName;
		}
	}
}
namespace System.Runtime.InteropServices
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
	internal sealed class LibraryImportAttribute : Attribute
	{
		public string LibraryName { get; }

		public string EntryPoint { get; set; }

		public StringMarshalling StringMarshalling { get; set; }

		public Type StringMarshallingCustomType { get; set; }

		public bool SetLastError { get; set; }

		public LibraryImportAttribute(string libraryName)
		{
			LibraryName = libraryName;
		}
	}
	internal enum StringMarshalling
	{
		Custom,
		Utf8,
		Utf16
	}
}
namespace System.Collections.Generic
{
	[DebuggerDisplay("Count = {_size}")]
	internal sealed class Deque<T>
	{
		[CompilerGenerated]
		private sealed class <GetEnumerator>d__13 : IEnumerator<T>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private T <>2__current;

			public Deque<T> <>4__this;

			private int <pos>5__2;

			private int <count>5__3;

			T IEnumerator<T>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

			[DebuggerHidden]
			public <GetEnumerator>d__13(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				int num = <>1__state;
				Deque<T> deque = <>4__this;
				switch (num)
				{
				default:
					return false;
				case 0:
					<>1__state = -1;
					<pos>5__2 = deque._head;
					<count>5__3 = deque._size;
					break;
				case 1:
					<>1__state = -1;
					<pos>5__2 = (<pos>5__2 + 1) % deque._array.Length;
					break;
				}
				if (<count>5__3-- > 0)
				{
					<>2__current = deque._array[<pos>5__2];
					<>1__state = 1;
					return true;
				}
				return false;
			}

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

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private T[] _array = Array.Empty<T>();

		private int _head;

		private int _tail;

		private int _size;

		public int Count => _size;

		public bool IsEmpty => _size == 0;

		public void EnqueueTail(T item)
		{
			if (_size == _array.Length)
			{
				Grow();
			}
			_array[_tail] = item;
			if (++_tail == _array.Length)
			{
				_tail = 0;
			}
			_size++;
		}

		public T DequeueHead()
		{
			T result = _array[_head];
			_array[_head] = default(T);
			if (++_head == _array.Length)
			{
				_head = 0;
			}
			_size--;
			return result;
		}

		public T PeekHead()
		{
			return _array[_head];
		}

		public T PeekTail()
		{
			int num = _tail - 1;
			if (num == -1)
			{
				num = _array.Length - 1;
			}
			return _array[num];
		}

		public T DequeueTail()
		{
			if (--_tail == -1)
			{
				_tail = _array.Length - 1;
			}
			T result = _array[_tail];
			_array[_tail] = default(T);
			_size--;
			return result;
		}

		[IteratorStateMachine(typeof(Deque<>.<GetEnumerator>d__13))]
		public IEnumerator<T> GetEnumerator()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetEnumerator>d__13(0)
			{
				<>4__this = this
			};
		}

		private void Grow()
		{
			int num = (int)((long)_array.Length * 2L);
			if (num < _array.Length + 4)
			{
				num = _array.Length + 4;
			}
			T[] array = new T[num];
			if (_head == 0)
			{
				Array.Copy(_array, array, _size);
			}
			else
			{
				Array.Copy(_array, _head, array, 0, _array.Length - _head);
				Array.Copy(_array, 0, array, _array.Length - _head, _tail);
			}
			_array = array;
			_head = 0;
			_tail = _size;
		}
	}
}
namespace System.Collections.Concurrent
{
	internal interface IProducerConsumerQueue<T> : IEnumerable<T>, IEnumerable
	{
		bool IsEmpty { get; }

		int Count { get; }

		void Enqueue(T item);

		bool TryDequeue([MaybeNullWhen(false)] out T result);

		int GetCountSafe(object syncObj);
	}
	[DebuggerDisplay("Count = {Count}")]
	internal sealed class MultiProducerMultiConsumerQueue<T> : ConcurrentQueue<T>, IProducerConsumerQueue<T>, IEnumerable<T>, IEnumerable
	{
		bool IProducerConsumerQueue<T>.IsEmpty => base.IsEmpty;

		int IProducerConsumerQueue<T>.Count => base.Count;

		void IProducerConsumerQueue<T>.Enqueue(T item)
		{
			Enqueue(item);
		}

		bool IProducerConsumerQueue<T>.TryDequeue([MaybeNullWhen(false)] out T result)
		{
			return TryDequeue(out result);
		}

		int IProducerConsumerQueue<T>.GetCountSafe(object syncObj)
		{
			return base.Count;
		}
	}
	[DebuggerDisplay("Count = {Count}")]
	[DebuggerTypeProxy(typeof(SingleProducerSingleConsumerQueue<>.SingleProducerSingleConsumerQueue_DebugView))]
	internal sealed class SingleProducerSingleConsumerQueue<T> : IProducerConsumerQueue<T>, IEnumerable<T>, IEnumerable
	{
		[StructLayout(LayoutKind.Sequential)]
		private sealed class Segment
		{
			internal Segment _next;

			internal readonly T[] _array;

			internal SegmentState _state;

			internal Segment(int size)
			{
				_array = new T[size];
			}
		}

		private struct SegmentState
		{
			internal Internal.PaddingFor32 _pad0;

			internal volatile int _first;

			internal int _lastCopy;

			internal Internal.PaddingFor32 _pad1;

			internal int _firstCopy;

			internal volatile int _last;

			internal Internal.PaddingFor32 _pad2;
		}

		private sealed class SingleProducerSingleConsumerQueue_DebugView
		{
			private readonly SingleProducerSingleConsumerQueue<T> _queue;

			[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
			public T[] Items => new List<T>(_queue).ToArray();

			public SingleProducerSingleConsumerQueue_DebugView(SingleProducerSingleConsumerQueue<T> queue)
			{
				_queue = queue;
			}
		}

		[CompilerGenerated]
		private sealed class <GetEnumerator>d__15 : IEnumerator<T>, IEnumerator, IDisposable
		{
			private int <>1__state;

			private T <>2__current;

			public SingleProducerSingleConsumerQueue<T> <>4__this;

			private Segment <segment>5__2;

			private int <pt>5__3;

			T IEnumerator<T>.Current
			{
				[DebuggerHidden]
				get
				{
					return <>2__current;
				}
			}

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

			[DebuggerHidden]
			public <GetEnumerator>d__15(int <>1__state)
			{
				this.<>1__state = <>1__state;
			}

			[DebuggerHidden]
			void IDisposable.Dispose()
			{
				<segment>5__2 = null;
				<>1__state = -2;
			}

			private bool MoveNext()
			{
				int num = <>1__state;
				SingleProducerSingleConsumerQueue<T> singleProducerSingleConsumerQueue = <>4__this;
				if (num != 0)
				{
					if (num != 1)
					{
						return false;
					}
					<>1__state = -1;
					<pt>5__3 = (<pt>5__3 + 1) & (<segment>5__2._array.Length - 1);
					goto IL_0095;
				}
				<>1__state = -1;
				<segment>5__2 = singleProducerSingleConsumerQueue._head;
				goto IL_00c0;
				IL_0095:
				if (<pt>5__3 != <segment>5__2._state._last)
				{
					<>2__current = <segment>5__2._array[<pt>5__3];
					<>1__state = 1;
					return true;
				}
				<segment>5__2 = <segment>5__2._next;
				goto IL_00c0;
				IL_00c0:
				if (<segment>5__2 != null)
				{
					<pt>5__3 = <segment>5__2._state._first;
					goto IL_0095;
				}
				<segment>5__2 = null;
				return false;
			}

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

			[DebuggerHidden]
			void IEnumerator.Reset()
			{
				throw new NotSupportedException();
			}
		}

		private const int InitialSegmentSize = 32;

		private const int MaxSegmentSize = 16777216;

		private volatile Segment _head;

		private volatile Segment _tail;

		public bool IsEmpty
		{
			get
			{
				Segment head = _head;
				if (head._state._first != head._state._lastCopy)
				{
					return false;
				}
				if (head._state._first != head._state._last)
				{
					return false;
				}
				return head._next == null;
			}
		}

		public int Count
		{
			get
			{
				int num = 0;
				for (Segment segment = _head; segment != null; segment = segment._next)
				{
					int num2 = segment._array.Length;
					int first;
					int last;
					do
					{
						first = segment._state._first;
						last = segment._state._last;
					}
					while (first != segment._state._first);
					num += (last - first) & (num2 - 1);
				}
				return num;
			}
		}

		public SingleProducerSingleConsumerQueue()
		{
			_head = (_tail = new Segment(32));
		}

		public void Enqueue(T item)
		{
			Segment segment = _tail;
			T[] array = segment._array;
			int last = segment._state._last;
			int num = (last + 1) & (array.Length - 1);
			if (num != segment._state._firstCopy)
			{
				array[last] = item;
				segment._state._last = num;
			}
			else
			{
				EnqueueSlow(item, ref segment);
			}
		}

		private void EnqueueSlow(T item, ref Segment segment)
		{
			if (segment._state._firstCopy != segment._state._first)
			{
				segment._state._firstCopy = segment._state._first;
				Enqueue(item);
				return;
			}
			Segment segment2 = new Segment(Math.Min(_tail._array.Length * 2, 16777216));
			segment2._array[0] = item;
			segment2._state._last = 1;
			segment2._state._lastCopy = 1;
			try
			{
			}
			finally
			{
				Volatile.Write(ref _tail._next, segment2);
				_tail = segment2;
			}
		}

		public bool TryDequeue([MaybeNullWhen(false)] out T result)
		{
			Segment head = _head;
			T[] array = head._array;
			int first = head._state._first;
			if (first != head._state._lastCopy)
			{
				result = array[first];
				array[first] = default(T);
				head._state._first = (first + 1) & (array.Length - 1);
				return true;
			}
			return TryDequeueSlow(head, array, peek: false, out result);
		}

		public bool TryPeek([MaybeNullWhen(false)] out T result)
		{
			Segment head = _head;
			T[] array = head._array;
			int first = head._state._first;
			if (first != head._state._lastCopy)
			{
				result = array[first];
				return true;
			}
			return TryDequeueSlow(head, array, peek: true, out result);
		}

		private bool TryDequeueSlow(Segment segment, T[] array, bool peek, [MaybeNullWhen(false)] out T result)
		{
			if (segment._state._last != segment._state._lastCopy)
			{
				segment._state._lastCopy = segment._state._last;
				if (!peek)
				{
					return TryDequeue(out result);
				}
				return TryPeek(out result);
			}
			if (segment._next != null && segment._state._first == segment._state._last)
			{
				segment = segment._next;
				array = segment._array;
				_head = segment;
			}
			int first = segment._state._first;
			if (first == segment._state._last)
			{
				result = default(T);
				return false;
			}
			result = array[first];
			if (!peek)
			{
				array[first] = default(T);
				segment._state._first = (first + 1) & (segment._array.Length - 1);
				segment._state._lastCopy = segment._state._last;
			}
			return true;
		}

		public bool TryDequeueIf(Predicate<T> predicate, [MaybeNullWhen(false)] out T result)
		{
			Segment head = _head;
			T[] array = head._array;
			int first = head._state._first;
			if (first != head._state._lastCopy)
			{
				result = array[first];
				if (predicate == null || predicate(result))
				{
					array[first] = default(T);
					head._state._first = (first + 1) & (array.Length - 1);
					return true;
				}
				result = default(T);
				return false;
			}
			return TryDequeueIfSlow(predicate, head, array, out result);
		}

		private bool TryDequeueIfSlow(Predicate<T> predicate, Segment segment, T[] array, [MaybeNullWhen(false)] out T result)
		{
			if (segment._state._last != segment._state._lastCopy)
			{
				segment._state._lastCopy = segment._state._last;
				return TryDequeueIf(predicate, out result);
			}
			if (segment._next != null && segment._state._first == segment._state._last)
			{
				segment = segment._next;
				array = segment._array;
				_head = segment;
			}
			int first = segment._state._first;
			if (first == segment._state._last)
			{
				result = default(T);
				return false;
			}
			result = array[first];
			if (predicate == null || predicate(result))
			{
				array[first] = default(T);
				segment._state._first = (first + 1) & (segment._array.Length - 1);
				segment._state._lastCopy = segment._state._last;
				return true;
			}
			result = default(T);
			return false;
		}

		public void Clear()
		{
			T result;
			while (TryDequeue(out result))
			{
			}
		}

		[IteratorStateMachine(typeof(SingleProducerSingleConsumerQueue<>.<GetEnumerator>d__15))]
		public IEnumerator<T> GetEnumerator()
		{
			//yield-return decompiler failed: Unexpected instruction in Iterator.Dispose()
			return new <GetEnumerator>d__15(0)
			{
				<>4__this = this
			};
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}

		int IProducerConsumerQueue<T>.GetCountSafe(object syncObj)
		{
			lock (syncObj)
			{
				return Count;
			}
		}
	}
}
namespace System.Threading.Channels
{
	internal abstract class AsyncOperation
	{
		private protected sealed class CapturedSchedulerAndExecutionContext
		{
			internal readonly object _scheduler;

			internal readonly ExecutionContext _executionContext;

			public CapturedSchedulerAndExecutionContext(object scheduler, ExecutionContext executionContext)
			{
				_scheduler = scheduler;
				_executionContext = executionContext;
			}
		}

		protected static readonly Action<object> s_availableSentinel = AvailableSentinel;

		protected static readonly Action<object> s_completedSentinel = CompletedSentinel;

		private readonly CancellationTokenRegistration _cancellationRegistration;

		private readonly Action<object, CancellationToken> _cancellationCallback;

		private protected readonly bool _pooled;

		private volatile int _completionReserved;

		private protected ExceptionDispatchInfo _error;

		private protected Action<object> _continuation;

		private protected object _continuationState;

		private protected object _capturedContext;

		private protected short _currentId;

		public bool RunContinuationsAsynchronously { get; }

		private CancellationToken CancellationToken { get; }

		internal bool IsCompleted => (object)_continuation == s_completedSentinel;

		private static void AvailableSentinel(object s)
		{
		}

		private static void CompletedSentinel(object s)
		{
		}

		protected static void ThrowIncompleteOperationException()
		{
			throw new InvalidOperationException(System.SR.InvalidOperation_IncompleteAsyncOperation);
		}

		protected static void ThrowMultipleContinuations()
		{
			throw new InvalidOperationException(System.SR.InvalidOperation_MultipleContinuations);
		}

		protected static void ThrowIncorrectCurrentIdException()
		{
			throw new InvalidOperationException(System.SR.InvalidOperation_IncorrectToken);
		}

		protected AsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken, bool pooled, Action<object, CancellationToken> cancellationCallback)
		{
			_continuation = (pooled ? s_availableSentinel : null);
			_pooled = pooled;
			RunContinuationsAsynchronously = runContinuationsAsynchronously;
			if (cancellationToken.CanBeCanceled)
			{
				_cancellationCallback = cancellationCallback;
				CancellationToken = cancellationToken;
				_cancellationRegistration = cancellationToken.Register(delegate(object s)
				{
					AsyncOperation asyncOperation = (AsyncOperation)s;
					asyncOperation._cancellationCallback(asyncOperation, asyncOperation.CancellationToken);
				}, this);
			}
		}

		public bool TrySetException(Exception exception)
		{
			if (TryReserveCompletionIfCancelable())
			{
				_error = ExceptionDispatchInfo.Capture(exception);
				SignalCompletion();
				return true;
			}
			return false;
		}

		public bool TrySetCanceled(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TryReserveCompletionIfCancelable())
			{
				_error = ExceptionDispatchInfo.Capture(new OperationCanceledException(cancellationToken));
				SignalCompletion();
				return true;
			}
			return false;
		}

		public bool TryReserveCompletionIfCancelable()
		{
			if (CancellationToken.CanBeCanceled)
			{
				return Interlocked.Exchange(ref _completionReserved, 1) == 0;
			}
			return true;
		}

		private protected void SignalCompletion()
		{
			Unregister(_cancellationRegistration);
			if (_continuation == null && Interlocked.CompareExchange(ref _continuation, s_completedSentinel, null) == null)
			{
				return;
			}
			object capturedContext = _capturedContext;
			if ((capturedContext == null || capturedContext is ExecutionContext) ? true : false)
			{
				if (RunContinuationsAsynchronously)
				{
					UnsafeQueueSetCompletionAndInvokeContinuation();
					return;
				}
			}
			else
			{
				SynchronizationContext synchronizationContext = (capturedContext as SynchronizationContext) ?? ((capturedContext as CapturedSchedulerAndExecutionContext)?._scheduler as SynchronizationContext);
				if (synchronizationContext != null)
				{
					if (RunContinuationsAsynchronously || synchronizationContext != SynchronizationContext.Current)
					{
						synchronizationContext.Post(delegate(object s)
						{
							((AsyncOperation)s).SetCompletionAndInvokeContinuation();
						}, this);
						return;
					}
				}
				else
				{
					TaskScheduler taskScheduler = (capturedContext as TaskScheduler) ?? ((capturedContext as CapturedSchedulerAndExecutionContext)?._scheduler as TaskScheduler);
					if (RunContinuationsAsynchronously || taskScheduler != TaskScheduler.Current)
					{
						Task.Factory.StartNew(delegate(object s)
						{
							((AsyncOperation)s).SetCompletionAndInvokeContinuation();
						}, this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, taskScheduler);
						return;
					}
				}
			}
			SetCompletionAndInvokeContinuation();
		}

		private void SetCompletionAndInvokeContinuation()
		{
			object capturedContext = _capturedContext;
			ExecutionContext executionContext = ((capturedContext == null) ? null : ((capturedContext as ExecutionContext) ?? (capturedContext as CapturedSchedulerAndExecutionContext)?._executionContext));
			if (executionContext == null)
			{
				Action<object> continuation = _continuation;
				_continuation = s_completedSentinel;
				continuation(_continuationState);
				return;
			}
			ExecutionContext.Run(executionContext, delegate(object s)
			{
				AsyncOperation asyncOperation = (AsyncOperation)s;
				Action<object> continuation2 = asyncOperation._continuation;
				asyncOperation._continuation = s_completedSentinel;
				continuation2(asyncOperation._continuationState);
			}, this);
		}

		public void OnCompleted(Action<object> continuation, object state, short token, ValueTaskSourceOnCompletedFlags flags)
		{
			if (_currentId != token)
			{
				ThrowIncorrectCurrentIdException();
			}
			if (_continuationState != null)
			{
				ThrowMultipleContinuations();
			}
			_continuationState = state;
			if ((flags & ValueTaskSourceOnCompletedFlags.FlowExecutionContext) != 0)
			{
				_capturedContext = ExecutionContext.Capture();
			}
			SynchronizationContext synchronizationContext = null;
			TaskScheduler taskScheduler = null;
			if ((flags & ValueTaskSourceOnCompletedFlags.UseSchedulingContext) != 0)
			{
				synchronizationContext = SynchronizationContext.Current;
				if (synchronizationContext != null && synchronizationContext.GetType() != typeof(SynchronizationContext))
				{
					_capturedContext = ((_capturedContext == null) ? ((object)synchronizationContext) : ((object)new CapturedSchedulerAndExecutionContext(synchronizationContext, (ExecutionContext)_capturedContext)));
				}
				else
				{
					synchronizationContext = null;
					taskScheduler = TaskScheduler.Current;
					if (taskScheduler != TaskScheduler.Default)
					{
						_capturedContext = ((_capturedContext == null) ? ((object)taskScheduler) : ((object)new CapturedSchedulerAndExecutionContext(taskScheduler, (ExecutionContext)_capturedContext)));
					}
					else
					{
						taskScheduler = null;
					}
				}
			}
			Action<object> action = Interlocked.CompareExchange(ref _continuation, continuation, null);
			if (action == null)
			{
				return;
			}
			if ((object)action != s_completedSentinel)
			{
				ThrowMultipleContinuations();
			}
			if (_capturedContext == null)
			{
				ChannelUtilities.UnsafeQueueUserWorkItem(continuation, state);
			}
			else if (synchronizationContext != null)
			{
				synchronizationContext.Post(delegate(object s)
				{
					KeyValuePair<Action<object>, object> keyValuePair = (KeyValuePair<Action<object>, object>)s;
					keyValuePair.Key(keyValuePair.Value);
				}, new KeyValuePair<Action<object>, object>(continuation, state));
			}
			else if (taskScheduler != null)
			{
				Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, taskScheduler);
			}
			else
			{
				ChannelUtilities.QueueUserWorkItem(continuation, state);
			}
		}

		private void UnsafeQueueSetCompletionAndInvokeContinuation()
		{
			ThreadPool.UnsafeQueueUserWorkItem(delegate(object s)
			{
				((AsyncOperation)s).SetCompletionAndInvokeContinuation();
			}, this);
		}

		private static void Unregister(CancellationTokenRegistration registration)
		{
			registration.Dispose();
		}
	}
	internal abstract class AsyncOperation<TSelf> : AsyncOperation, IValueTaskSource
	{
		public TSelf Next { get; set; }

		public TSelf Previous { get; set; }

		public ValueTask ValueTask => new ValueTask(this, _currentId);

		protected AsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false, Action<object, CancellationToken> cancellationCallback = null)
			: base(runContinuationsAsynchronously, cancellationToken, pooled, cancellationCallback)
		{
		}

		public ValueTaskSourceStatus GetStatus(short token)
		{
			if (_currentId != token)
			{
				AsyncOperation.ThrowIncorrectCurrentIdException();
			}
			if (base.IsCompleted)
			{
				if (_error != null)
				{
					if (!(_error.SourceException is OperationCanceledException))
					{
						return ValueTaskSourceStatus.Faulted;
					}
					return ValueTaskSourceStatus.Canceled;
				}
				return ValueTaskSourceStatus.Succeeded;
			}
			return ValueTaskSourceStatus.Pending;
		}

		void IValueTaskSource.GetResult(short token)
		{
			if (_currentId != token)
			{
				AsyncOperation.ThrowIncorrectCurrentIdException();
			}
			if (!base.IsCompleted)
			{
				AsyncOperation.ThrowIncompleteOperationException();
			}
			ExceptionDispatchInfo error = _error;
			_currentId++;
			if (_pooled)
			{
				Volatile.Write(ref _continuation, AsyncOperation.s_availableSentinel);
			}
			error?.Throw();
		}
	}
	internal abstract class AsyncOperation<TSelf, TResult> : AsyncOperation<TSelf>, IValueTaskSource<TResult> where TSelf : AsyncOperation<TSelf, TResult>
	{
		private TResult _result;

		public ValueTask<TResult> ValueTaskOfT => new ValueTask<TResult>(this, _currentId);

		public AsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false, Action<object, CancellationToken> cancellationCallback = null)
			: base(runContinuationsAsynchronously, cancellationToken, pooled, cancellationCallback)
		{
		}

		public TResult GetResult(short token)
		{
			if (_currentId != token)
			{
				AsyncOperation.ThrowIncorrectCurrentIdException();
			}
			if (!base.IsCompleted)
			{
				AsyncOperation.ThrowIncompleteOperationException();
			}
			ExceptionDispatchInfo error = _error;
			TResult result = _result;
			_currentId++;
			if (_pooled)
			{
				Volatile.Write(ref _continuation, AsyncOperation.s_availableSentinel);
			}
			error?.Throw();
			return result;
		}

		public bool TryOwnAndReset()
		{
			if ((object)Interlocked.CompareExchange(ref _continuation, null, AsyncOperation.s_availableSentinel) == AsyncOperation.s_availableSentinel)
			{
				_continuationState = null;
				_result = default(TResult);
				_error = null;
				_capturedContext = null;
				return true;
			}
			return false;
		}

		public bool TrySetResult(TResult result)
		{
			if (TryReserveCompletionIfCancelable())
			{
				DangerousSetResult(result);
				return true;
			}
			return false;
		}

		public void DangerousSetResult(TResult result)
		{
			_result = result;
			SignalCompletion();
		}
	}
	internal sealed class BlockedReadAsyncOperation<TResult> : AsyncOperation<BlockedReadAsyncOperation<TResult>, TResult>
	{
		public BlockedReadAsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false, Action<object, CancellationToken> cancellationCallback = null)
			: base(runContinuationsAsynchronously, cancellationToken, pooled, cancellationCallback)
		{
		}
	}
	internal sealed class BlockedWriteAsyncOperation<T> : AsyncOperation<BlockedWriteAsyncOperation<T>, VoidResult>
	{
		public T Item { get; set; }

		public BlockedWriteAsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false, Action<object, CancellationToken> cancellationCallback = null)
			: base(runContinuationsAsynchronously, cancellationToken, pooled, cancellationCallback)
		{
		}
	}
	internal sealed class WaitingReadAsyncOperation : AsyncOperation<WaitingReadAsyncOperation, bool>
	{
		public WaitingReadAsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false, Action<object, CancellationToken> cancellationCallback = null)
			: base(runContinuationsAsynchronously, cancellationToken, pooled, cancellationCallback)
		{
		}
	}
	internal sealed class WaitingWriteAsyncOperation : AsyncOperation<WaitingWriteAsyncOperation, bool>
	{
		public WaitingWriteAsyncOperation(bool runContinuationsAsynchronously, CancellationToken cancellationToken = default(CancellationToken), bool pooled = false, Action<object, CancellationToken> cancellationCallback = null)
			: base(runContinuationsAsynchronously, cancellationToken, pooled, cancellationCallback)
		{
		}
	}
	[DebuggerDisplay("Items = {ItemsCountForDebugger}, Capacity = {_bufferedCapacity}, Mode = {_mode}, Closed = {ChannelIsClosedForDebugger}")]
	[DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))]
	internal sealed class BoundedChannel<T> : Channel<T>, IDebugEnumerable<T>
	{
		[DebuggerDisplay("Items = {ItemsCountForDebugger}")]
		[DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))]
		private sealed class BoundedChannelReader : ChannelReader<T>, IDebugEnumerable<T>
		{
			internal readonly BoundedChannel<T> _parent;

			private readonly BlockedReadAsyncOperation<T> _readerSingleton;

			private readonly WaitingReadAsyncOperation _waiterSingleton;

			public override Task Completion => _parent._completion.Task;

			public override bool CanCount => true;

			public override bool CanPeek => true;

			public override int Count
			{
				get
				{
					BoundedChannel<T> parent = _parent;
					lock (parent.SyncObj)
					{
						return parent._items.Count;
					}
				}
			}

			private int ItemsCountForDebugger => _parent._items.Count;

			internal BoundedChannelReader(BoundedChannel<T> parent)
			{
				_parent = parent;
				_readerSingleton = new BlockedReadAsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true);
				_waiterSingleton = new WaitingReadAsyncOperation(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true);
			}

			public override bool TryRead([MaybeNullWhen(false)] out T item)
			{
				BoundedChannel<T> parent = _parent;
				lock (parent.SyncObj)
				{
					if (!parent._items.IsEmpty)
					{
						item = DequeueItemAndPostProcess();
						return true;
					}
				}
				item = default(T);
				return false;
			}

			public override bool TryPeek([MaybeNullWhen(false)] out T item)
			{
				BoundedChannel<T> parent = _parent;
				lock (parent.SyncObj)
				{
					if (!parent._items.IsEmpty)
					{
						item = parent._items.PeekHead();
						return true;
					}
				}
				item = default(T);
				return false;
			}

			public override ValueTask<T> ReadAsync(CancellationToken cancellationToken)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken));
				}
				BoundedChannel<T> parent = _parent;
				lock (parent.SyncObj)
				{
					if (!parent._items.IsEmpty)
					{
						return new ValueTask<T>(DequeueItemAndPostProcess());
					}
					if (parent._doneWriting != null)
					{
						return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting);
					}
					if (!cancellationToken.CanBeCanceled)
					{
						BlockedReadAsyncOperation<T> readerSingleton = _readerSingleton;
						if (readerSingleton.TryOwnAndReset())
						{
							ChannelUtilities.Enqueue(ref parent._blockedReadersHead, readerSingleton);
							return readerSingleton.ValueTaskOfT;
						}
					}
					BlockedReadAsyncOperation<T> blockedReadAsyncOperation = new BlockedReadAsyncOperation<T>(parent._runContinuationsAsynchronously, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate);
					ChannelUtilities.Enqueue(ref parent._blockedReadersHead, blockedReadAsyncOperation);
					return blockedReadAsyncOperation.ValueTaskOfT;
				}
			}

			public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken));
				}
				BoundedChannel<T> parent = _parent;
				lock (parent.SyncObj)
				{
					if (!parent._items.IsEmpty)
					{
						return new ValueTask<bool>(result: true);
					}
					if (parent._doneWriting != null)
					{
						return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>);
					}
					if (!cancellationToken.CanBeCanceled)
					{
						WaitingReadAsyncOperation waiterSingleton = _waiterSingleton;
						if (waiterSingleton.TryOwnAndReset())
						{
							ChannelUtilities.Enqueue(ref parent._waitingReadersHead, waiterSingleton);
							return waiterSingleton.ValueTaskOfT;
						}
					}
					WaitingReadAsyncOperation waitingReadAsyncOperation = new WaitingReadAsyncOperation(parent._runContinuationsAsynchronously, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate);
					ChannelUtilities.Enqueue(ref parent._waitingReadersHead, waitingReadAsyncOperation);
					return waitingReadAsyncOperation.ValueTaskOfT;
				}
			}

			private T DequeueItemAndPostProcess()
			{
				BoundedChannel<T> parent = _parent;
				T result = parent._items.DequeueHead();
				if (parent._doneWriting != null)
				{
					if (parent._items.IsEmpty)
					{
						ChannelUtilities.Complete(parent._completion, parent._doneWriting);
					}
				}
				else
				{
					BlockedWriteAsyncOperation<T> op;
					while (ChannelUtilities.TryDequeue(ref parent._blockedWritersHead, out op))
					{
						if (op.TrySetResult(default(VoidResult)))
						{
							parent._items.EnqueueTail(op.Item);
							return result;
						}
					}
					ChannelUtilities.SetOperations(ref parent._waitingWritersHead, result: true);
				}
				return result;
			}

			IEnumerator<T> IDebugEnumerable<T>.GetEnumerator()
			{
				return _parent._items.GetEnumerator();
			}
		}

		[DebuggerDisplay("Items = {ItemsCountForDebugger}, Capacity = {CapacityForDebugger}")]
		[DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))]
		private sealed class BoundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T>
		{
			internal readonly BoundedChannel<T> _parent;

			private readonly BlockedWriteAsyncOperation<T> _writerSingleton;

			private readonly WaitingWriteAsyncOperation _waiterSingleton;

			private int ItemsCountForDebugger => _parent._items.Count;

			private int CapacityForDebugger => _parent._bufferedCapacity;

			internal BoundedChannelWriter(BoundedChannel<T> parent)
			{
				_parent = parent;
				_writerSingleton = new BlockedWriteAsyncOperation<T>(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true);
				_waiterSingleton = new WaitingWriteAsyncOperation(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true);
			}

			public override bool TryComplete(Exception error)
			{
				BoundedChannel<T> parent = _parent;
				bool isEmpty;
				BlockedReadAsyncOperation<T> blockedReadersHead;
				BlockedWriteAsyncOperation<T> blockedWritersHead;
				WaitingReadAsyncOperation waitingReadersHead;
				WaitingWriteAsyncOperation waitingWritersHead;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting != null)
					{
						return false;
					}
					parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel;
					isEmpty = parent._items.IsEmpty;
					blockedReadersHead = parent._blockedReadersHead;
					blockedWritersHead = parent._blockedWritersHead;
					waitingReadersHead = parent._waitingReadersHead;
					waitingWritersHead = parent._waitingWritersHead;
					parent._blockedReadersHead = null;
					parent._blockedWritersHead = null;
					parent._waitingReadersHead = null;
					parent._waitingWritersHead = null;
				}
				if (isEmpty)
				{
					ChannelUtilities.Complete(parent._completion, error);
				}
				ChannelUtilities.FailOperations(blockedReadersHead, ChannelUtilities.CreateInvalidCompletionException(error));
				ChannelUtilities.FailOperations(blockedWritersHead, ChannelUtilities.CreateInvalidCompletionException(error));
				ChannelUtilities.SetOrFailOperations(waitingReadersHead, result: false, error);
				ChannelUtilities.SetOrFailOperations(waitingWritersHead, result: false, error);
				return true;
			}

			public override bool TryWrite(T item)
			{
				BlockedReadAsyncOperation<T> blockedReadAsyncOperation = null;
				WaitingReadAsyncOperation waitingReadAsyncOperation = null;
				BoundedChannel<T> parent = _parent;
				bool lockTaken = false;
				try
				{
					Monitor.Enter(parent.SyncObj, ref lockTaken);
					if (parent._doneWriting != null)
					{
						return false;
					}
					int count = parent._items.Count;
					if (count != 0)
					{
						if (count < parent._bufferedCapacity)
						{
							parent._items.EnqueueTail(item);
							return true;
						}
						if (parent._mode == BoundedChannelFullMode.Wait)
						{
							return false;
						}
						if (parent._mode == BoundedChannelFullMode.DropWrite)
						{
							Monitor.Exit(parent.SyncObj);
							lockTaken = false;
							parent._itemDropped?.Invoke(item);
							return true;
						}
						T obj = ((parent._mode == BoundedChannelFullMode.DropNewest) ? parent._items.DequeueTail() : parent._items.DequeueHead());
						parent._items.EnqueueTail(item);
						Monitor.Exit(parent.SyncObj);
						lockTaken = false;
						parent._itemDropped?.Invoke(obj);
						return true;
					}
					blockedReadAsyncOperation = ChannelUtilities.TryDequeueAndReserveCompletionIfCancelable(ref parent._blockedReadersHead);
					if (blockedReadAsyncOperation == null)
					{
						parent._items.EnqueueTail(item);
						waitingReadAsyncOperation = ChannelUtilities.TryReserveCompletionIfCancelable(ref parent._waitingReadersHead);
						if (waitingReadAsyncOperation == null)
						{
							return true;
						}
					}
				}
				finally
				{
					if (lockTaken)
					{
						Monitor.Exit(parent.SyncObj);
					}
				}
				if (blockedReadAsyncOperation != null)
				{
					blockedReadAsyncOperation.DangerousSetResult(item);
				}
				else
				{
					ChannelUtilities.DangerousSetOperations(waitingReadAsyncOperation, result: true);
				}
				return true;
			}

			public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken));
				}
				BoundedChannel<T> parent = _parent;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting != null)
					{
						return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>);
					}
					if (parent._items.Count < parent._bufferedCapacity || parent._mode != 0)
					{
						return new ValueTask<bool>(result: true);
					}
					if (!cancellationToken.CanBeCanceled)
					{
						WaitingWriteAsyncOperation waiterSingleton = _waiterSingleton;
						if (waiterSingleton.TryOwnAndReset())
						{
							ChannelUtilities.Enqueue(ref parent._waitingWritersHead, waiterSingleton);
							return waiterSingleton.ValueTaskOfT;
						}
					}
					WaitingWriteAsyncOperation waitingWriteAsyncOperation = new WaitingWriteAsyncOperation(runContinuationsAsynchronously: true, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate);
					ChannelUtilities.Enqueue(ref parent._waitingWritersHead, waitingWriteAsyncOperation);
					return waitingWriteAsyncOperation.ValueTaskOfT;
				}
			}

			public override ValueTask WriteAsync(T item, CancellationToken cancellationToken)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask(Task.FromCanceled(cancellationToken));
				}
				BlockedReadAsyncOperation<T> blockedReadAsyncOperation = null;
				WaitingReadAsyncOperation waitingReadAsyncOperation = null;
				BoundedChannel<T> parent = _parent;
				bool lockTaken = false;
				try
				{
					Monitor.Enter(parent.SyncObj, ref lockTaken);
					if (parent._doneWriting != null)
					{
						return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(parent._doneWriting)));
					}
					int count = parent._items.Count;
					if (count != 0)
					{
						if (count < parent._bufferedCapacity)
						{
							parent._items.EnqueueTail(item);
							return default(ValueTask);
						}
						if (parent._mode == BoundedChannelFullMode.Wait)
						{
							if (!cancellationToken.CanBeCanceled)
							{
								BlockedWriteAsyncOperation<T> writerSingleton = _writerSingleton;
								if (writerSingleton.TryOwnAndReset())
								{
									writerSingleton.Item = item;
									ChannelUtilities.Enqueue(ref parent._blockedWritersHead, writerSingleton);
									return writerSingleton.ValueTask;
								}
							}
							BlockedWriteAsyncOperation<T> blockedWriteAsyncOperation = new BlockedWriteAsyncOperation<T>(runContinuationsAsynchronously: true, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate)
							{
								Item = item
							};
							ChannelUtilities.Enqueue(ref parent._blockedWritersHead, blockedWriteAsyncOperation);
							return blockedWriteAsyncOperation.ValueTask;
						}
						if (parent._mode == BoundedChannelFullMode.DropWrite)
						{
							Monitor.Exit(parent.SyncObj);
							lockTaken = false;
							parent._itemDropped?.Invoke(item);
							return default(ValueTask);
						}
						T obj = ((parent._mode == BoundedChannelFullMode.DropNewest) ? parent._items.DequeueTail() : parent._items.DequeueHead());
						parent._items.EnqueueTail(item);
						Monitor.Exit(parent.SyncObj);
						lockTaken = false;
						parent._itemDropped?.Invoke(obj);
						return default(ValueTask);
					}
					blockedReadAsyncOperation = ChannelUtilities.TryDequeueAndReserveCompletionIfCancelable(ref parent._blockedReadersHead);
					if (blockedReadAsyncOperation == null)
					{
						parent._items.EnqueueTail(item);
						waitingReadAsyncOperation = ChannelUtilities.TryReserveCompletionIfCancelable(ref parent._waitingReadersHead);
						if (waitingReadAsyncOperation == null)
						{
							return default(ValueTask);
						}
					}
				}
				finally
				{
					if (lockTaken)
					{
						Monitor.Exit(parent.SyncObj);
					}
				}
				if (blockedReadAsyncOperation != null)
				{
					blockedReadAsyncOperation.DangerousSetResult(item);
				}
				else
				{
					ChannelUtilities.DangerousSetOperations(waitingReadAsyncOperation, result: true);
				}
				return default(ValueTask);
			}

			IEnumerator<T> IDebugEnumerable<T>.GetEnumerator()
			{
				return _parent._items.GetEnumerator();
			}
		}

		private readonly BoundedChannelFullMode _mode;

		private readonly Action<T> _itemDropped;

		private readonly TaskCompletionSource _completion;

		private readonly int _bufferedCapacity;

		private readonly Deque<T> _items = new Deque<T>();

		private BlockedReadAsyncOperation<T> _blockedReadersHead;

		private BlockedWriteAsyncOperation<T> _blockedWritersHead;

		private WaitingReadAsyncOperation _waitingReadersHead;

		private WaitingWriteAsyncOperation _waitingWritersHead;

		private readonly bool _runContinuationsAsynchronously;

		private Exception _doneWriting;

		private object SyncObj => _items;

		private Action<object, CancellationToken> CancellationCallbackDelegate => delegate(object state, CancellationToken cancellationToken)
		{
			AsyncOperation asyncOperation = (AsyncOperation)state;
			if (asyncOperation.TrySetCanceled(cancellationToken))
			{
				ChannelUtilities.UnsafeQueueUserWorkItem(delegate(KeyValuePair<BoundedChannel<T>, AsyncOperation> state)
				{
					lock (state.Key.SyncObj)
					{
						AsyncOperation value = state.Value;
						if (!(value is BlockedReadAsyncOperation<T> op))
						{
							if (!(value is BlockedWriteAsyncOperation<T> op2))
							{
								if (!(value is WaitingReadAsyncOperation op3))
								{
									if (value is WaitingWriteAsyncOperation op4)
									{
										ChannelUtilities.Remove(ref state.Key._waitingWritersHead, op4);
									}
								}
								else
								{
									ChannelUtilities.Remove(ref state.Key._waitingReadersHead, op3);
								}
							}
							else
							{
								ChannelUtilities.Remove(ref state.Key._blockedWritersHead, op2);
							}
						}
						else
						{
							ChannelUtilities.Remove(ref state.Key._blockedReadersHead, op);
						}
					}
				}, new KeyValuePair<BoundedChannel<T>, AsyncOperation>(this, asyncOperation));
			}
		};

		private int ItemsCountForDebugger => _items.Count;

		private bool ChannelIsClosedForDebugger => _doneWriting != null;

		internal BoundedChannel(int bufferedCapacity, BoundedChannelFullMode mode, bool runContinuationsAsynchronously, Action<T> itemDropped)
		{
			_bufferedCapacity = bufferedCapacity;
			_mode = mode;
			_runContinuationsAsynchronously = runContinuationsAsynchronously;
			_itemDropped = itemDropped;
			_completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None);
			base.Reader = new BoundedChannelReader(this);
			base.Writer = new BoundedChannelWriter(this);
		}

		[Conditional("DEBUG")]
		private void AssertInvariants()
		{
			_ = _items.IsEmpty;
			_ = _items.Count;
			_ = _bufferedCapacity;
			_ = _blockedReadersHead;
			_ = _blockedWritersHead;
			_ = _completion.Task.IsCompleted;
		}

		IEnumerator<T> IDebugEnumerable<T>.GetEnumerator()
		{
			return _items.GetEnumerator();
		}
	}
	public enum BoundedChannelFullMode
	{
		Wait,
		DropNewest,
		DropOldest,
		DropWrite
	}
	public static class Channel
	{
		public static Channel<T> CreateUnbounded<T>()
		{
			return new UnboundedChannel<T>(runContinuationsAsynchronously: true);
		}

		public static Channel<T> CreateUnbounded<T>(UnboundedChannelOptions options)
		{
			ExceptionPolyfills.ThrowIfNull(options, "options");
			if (options.SingleReader)
			{
				return new SingleConsumerUnboundedChannel<T>(!options.AllowSynchronousContinuations);
			}
			return new UnboundedChannel<T>(!options.AllowSynchronousContinuations);
		}

		public static Channel<T> CreateBounded<T>(int capacity)
		{
			if (capacity <= 0)
			{
				if (capacity != 0)
				{
					throw new ArgumentOutOfRangeException("capacity");
				}
				return new RendezvousChannel<T>(BoundedChannelFullMode.Wait, runContinuationsAsynchronously: true, null);
			}
			return new BoundedChannel<T>(capacity, BoundedChannelFullMode.Wait, runContinuationsAsynchronously: true, null);
		}

		public static Channel<T> CreateBounded<T>(BoundedChannelOptions options)
		{
			return CreateBounded<T>(options, null);
		}

		public static Channel<T> CreateBounded<T>(BoundedChannelOptions options, Action<T>? itemDropped)
		{
			ExceptionPolyfills.ThrowIfNull(options, "options");
			if (options.Capacity <= 0)
			{
				return new RendezvousChannel<T>(options.FullMode, !options.AllowSynchronousContinuations, itemDropped);
			}
			return new BoundedChannel<T>(options.Capacity, options.FullMode, !options.AllowSynchronousContinuations, itemDropped);
		}
	}
	[Serializable]
	public class ChannelClosedException : InvalidOperationException
	{
		public ChannelClosedException()
			: base(System.SR.ChannelClosedException_DefaultMessage)
		{
		}

		public ChannelClosedException(string? message)
			: base(message ?? System.SR.ChannelClosedException_DefaultMessage)
		{
		}

		public ChannelClosedException(Exception? innerException)
			: base(System.SR.ChannelClosedException_DefaultMessage, innerException)
		{
		}

		public ChannelClosedException(string? message, Exception? innerException)
			: base(message ?? System.SR.ChannelClosedException_DefaultMessage, innerException)
		{
		}

		protected ChannelClosedException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	public abstract class ChannelOptions
	{
		public bool SingleWriter { get; set; }

		public bool SingleReader { get; set; }

		public bool AllowSynchronousContinuations { get; set; }
	}
	public sealed class BoundedChannelOptions : ChannelOptions
	{
		private int _capacity;

		private BoundedChannelFullMode _mode;

		public int Capacity
		{
			get
			{
				return _capacity;
			}
			set
			{
				if (value < 0)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_capacity = value;
			}
		}

		public BoundedChannelFullMode FullMode
		{
			get
			{
				return _mode;
			}
			set
			{
				if ((uint)value <= 3u)
				{
					_mode = value;
					return;
				}
				throw new ArgumentOutOfRangeException("value");
			}
		}

		public BoundedChannelOptions(int capacity)
		{
			if (capacity < 0)
			{
				throw new ArgumentOutOfRangeException("capacity");
			}
			_capacity = capacity;
		}
	}
	public sealed class UnboundedChannelOptions : ChannelOptions
	{
	}
	public abstract class ChannelReader<T>
	{
		public virtual Task Completion => ChannelUtilities.s_neverCompletingTask;

		public virtual bool CanCount => false;

		public virtual bool CanPeek => false;

		public virtual int Count
		{
			get
			{
				throw new NotSupportedException();
			}
		}

		public abstract bool TryRead([MaybeNullWhen(false)] out T item);

		public virtual bool TryPeek([MaybeNullWhen(false)] out T item)
		{
			item = default(T);
			return false;
		}

		public abstract ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken = default(CancellationToken));

		public virtual ValueTask<T> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (cancellationToken.IsCancellationRequested)
			{
				return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken));
			}
			try
			{
				if (TryRead(out var item))
				{
					return new ValueTask<T>(item);
				}
			}
			catch (Exception ex) when ((!(ex is ChannelClosedException) && !(ex is OperationCanceledException)) || 1 == 0)
			{
				return new ValueTask<T>(Task.FromException<T>(ex));
			}
			return ReadAsyncCore(cancellationToken);
			async ValueTask<T> ReadAsyncCore(CancellationToken ct)
			{
				T item2;
				do
				{
					if (!(await WaitToReadAsync(ct).ConfigureAwait(continueOnCapturedContext: false)))
					{
						throw new ChannelClosedException();
					}
				}
				while (!TryRead(out item2));
				return item2;
			}
		}

		public virtual async IAsyncEnumerable<T> ReadAllAsync([EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			while (await WaitToReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
			{
				T item;
				while (TryRead(out item))
				{
					yield return item;
				}
			}
		}
	}
	internal static class ChannelUtilities
	{
		internal static readonly Exception s_doneWritingSentinel = new Exception("s_doneWritingSentinel");

		internal static readonly Task<bool> s_trueTask = Task.FromResult(result: true);

		internal static readonly Task<bool> s_falseTask = Task.FromResult(result: false);

		internal static readonly Task s_neverCompletingTask = new TaskCompletionSource<bool>().Task;

		internal static void Complete(TaskCompletionSource tcs, Exception error = null)
		{
			if (error is OperationCanceledException ex)
			{
				tcs.TrySetCanceled(ex.CancellationToken);
			}
			else if (error != null && error != s_doneWritingSentinel)
			{
				if (tcs.TrySetException(error))
				{
					_ = tcs.Task.Exception;
				}
			}
			else
			{
				tcs.TrySetResult();
			}
		}

		internal static ValueTask<T> GetInvalidCompletionValueTask<T>(Exception error)
		{
			return new ValueTask<T>((error == s_doneWritingSentinel) ? Task.FromException<T>(CreateInvalidCompletionException()) : ((error is OperationCanceledException ex) ? Task.FromCanceled<T>(ex.CancellationToken.IsCancellationRequested ? ex.CancellationToken : new CancellationToken(canceled: true)) : Task.FromException<T>(CreateInvalidCompletionException(error))));
		}

		internal static TAsyncOp TryDequeueAndReserveCompletionIfCancelable<TAsyncOp>(ref TAsyncOp head) where TAsyncOp : AsyncOperation<TAsyncOp>
		{
			TAsyncOp op;
			while (TryDequeue(ref head, out op))
			{
				if (op.TryReserveCompletionIfCancelable())
				{
					return op;
				}
			}
			return null;
		}

		internal static bool TryDequeue<TAsyncOp>(ref TAsyncOp head, [NotNullWhen(true)] out TAsyncOp op) where TAsyncOp : AsyncOperation<TAsyncOp>
		{
			op = head;
			if (head == null)
			{
				return false;
			}
			if (head.Next == head)
			{
				head = null;
			}
			else
			{
				TAsyncOp previous = head.Previous;
				head = head.Next;
				head.Previous = previous;
				previous.Next = head;
			}
			TAsyncOp val = op;
			TAsyncOp next = (op.Previous = null);
			val.Next = next;
			return true;
		}

		internal static void Enqueue<TAsyncOp>(ref TAsyncOp head, TAsyncOp op) where TAsyncOp : AsyncOperation<TAsyncOp>
		{
			if (head == null)
			{
				TAsyncOp val2 = (op.Previous = op);
				TAsyncOp val4 = (op.Next = val2);
				head = val4;
			}
			else
			{
				TAsyncOp previous = head.Previous;
				op.Next = head;
				op.Previous = previous;
				previous.Next = op;
				head.Previous = op;
			}
		}

		internal static void Remove<TAsyncOp>(ref TAsyncOp head, TAsyncOp op) where TAsyncOp : AsyncOperation<TAsyncOp>
		{
			if (head == null || op.Next == null)
			{
				return;
			}
			if (op.Next == op)
			{
				head = null;
			}
			else
			{
				op.Previous.Next = op.Next;
				op.Next.Previous = op.Previous;
				if (head == op)
				{
					head = op.Next;
				}
			}
			TAsyncOp next = (op.Previous = null);
			op.Next = next;
		}

		internal static void SetOrFailOperations<TAsyncOp, T>(TAsyncOp head, T result, Exception error = null) where TAsyncOp : AsyncOperation<TAsyncOp, T>
		{
			if (error != null)
			{
				FailOperations(head, error);
			}
			else
			{
				SetOperations(ref head, result);
			}
		}

		internal static void SetOperations<TAsyncOp, TResult>(ref TAsyncOp head, TResult result) where TAsyncOp : AsyncOperation<TAsyncOp, TResult>
		{
			TAsyncOp val = head;
			if (val != null)
			{
				do
				{
					TAsyncOp next = val.Next;
					TAsyncOp val2 = val;
					TAsyncOp next2 = (val.Previous = null);
					val2.Next = next2;
					val.TrySetResult(result);
					val = next;
				}
				while (val != head);
				head = null;
			}
		}

		internal static void DangerousSetOperations<TAsyncOp, TResult>(TAsyncOp head, TResult result) where TAsyncOp : AsyncOperation<TAsyncOp, TResult>
		{
			TAsyncOp val = head;
			if (val != null)
			{
				do
				{
					TAsyncOp next = val.Next;
					TAsyncOp val2 = val;
					TAsyncOp next2 = (val.Previous = null);
					val2.Next = next2;
					val.DangerousSetResult(result);
					val = next;
				}
				while (val != head);
			}
		}

		internal static TAsyncOp TryReserveCompletionIfCancelable<TAsyncOp>(ref TAsyncOp head) where TAsyncOp : AsyncOperation<TAsyncOp>
		{
			TAsyncOp head2 = null;
			TAsyncOp val = head;
			if (val != null)
			{
				do
				{
					TAsyncOp next = val.Next;
					TAsyncOp val2 = val;
					TAsyncOp next2 = (val.Previous = null);
					val2.Next = next2;
					if (val.TryReserveCompletionIfCancelable())
					{
						Enqueue(ref head2, val);
					}
					val = next;
				}
				while (val != head);
				head = null;
			}
			return head2;
		}

		internal static void FailOperations<TAsyncOp>(TAsyncOp head, Exception error) where TAsyncOp : AsyncOperation<TAsyncOp>
		{
			TAsyncOp val = head;
			if (val != null)
			{
				do
				{
					TAsyncOp next = val.Next;
					TAsyncOp val2 = val;
					TAsyncOp next2 = (val.Previous = null);
					val2.Next = next2;
					val.TrySetException(error);
					val = next;
				}
				while (val != head);
			}
		}

		[Conditional("DEBUG")]
		internal static void AssertAll<TAsyncOp>(TAsyncOp head, Func<TAsyncOp, bool> condition, string message) where TAsyncOp : AsyncOperation<TAsyncOp>
		{
			TAsyncOp val = head;
			if (val != null)
			{
				do
				{
					val = val.Next;
				}
				while (val != head);
			}
		}

		internal static long CountOperations<TAsyncOp>(TAsyncOp head) where TAsyncOp : AsyncOperation<TAsyncOp>
		{
			TAsyncOp val = head;
			long num = 0L;
			if (val != null)
			{
				do
				{
					num++;
					val = val.Next;
				}
				while (val != head);
			}
			return num;
		}

		internal static Exception CreateInvalidCompletionException(Exception inner = null)
		{
			if (!(inner is OperationCanceledException))
			{
				if (inner == null || inner == s_doneWritingSentinel)
				{
					return new ChannelClosedException();
				}
				return new ChannelClosedException(inner);
			}
			return inner;
		}

		internal static void UnsafeQueueUserWorkItem(Action<object> action, object state)
		{
			QueueUserWorkItem(action, state);
		}

		internal static void UnsafeQueueUserWorkItem<TState>(Action<TState> action, TState state)
		{
			ThreadPool.UnsafeQueueUserWorkItem(delegate(object tuple)
			{
				Tuple<Action<TState>, TState> tuple2 = (Tuple<Action<TState>, TState>)tuple;
				tuple2.Item1(tuple2.Item2);
			}, Tuple.Create(action, state));
		}

		internal static void QueueUserWorkItem(Action<object> action, object state)
		{
			Task.Factory.StartNew(action, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
		}
	}
	public abstract class ChannelWriter<T>
	{
		public virtual bool TryComplete(Exception? error = null)
		{
			return false;
		}

		public abstract bool TryWrite(T item);

		public abstract ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken = default(CancellationToken));

		public virtual ValueTask WriteAsync(T item, CancellationToken cancellationToken = default(CancellationToken))
		{
			try
			{
				return cancellationToken.IsCancellationRequested ? new ValueTask(Task.FromCanceled<T>(cancellationToken)) : (TryWrite(item) ? default(ValueTask) : WriteAsyncCore(item, cancellationToken));
			}
			catch (Exception exception)
			{
				return new ValueTask(Task.FromException(exception));
			}
		}

		private async ValueTask WriteAsyncCore(T innerItem, CancellationToken ct)
		{
			while (await WaitToWriteAsync(ct).ConfigureAwait(continueOnCapturedContext: false))
			{
				if (TryWrite(innerItem))
				{
					return;
				}
			}
			throw ChannelUtilities.CreateInvalidCompletionException();
		}

		public void Complete(Exception? error = null)
		{
			if (!TryComplete(error))
			{
				throw ChannelUtilities.CreateInvalidCompletionException();
			}
		}
	}
	public abstract class Channel<T> : Channel<T, T>
	{
	}
	public abstract class Channel<TWrite, TRead>
	{
		public ChannelReader<TRead> Reader { get; protected set; }

		public ChannelWriter<TWrite> Writer { get; protected set; }

		public static implicit operator ChannelReader<TRead>(Channel<TWrite, TRead> channel)
		{
			return channel.Reader;
		}

		public static implicit operator ChannelWriter<TWrite>(Channel<TWrite, TRead> channel)
		{
			return channel.Writer;
		}
	}
	internal interface IDebugEnumerable<T>
	{
		IEnumerator<T> GetEnumerator();
	}
	internal sealed class DebugEnumeratorDebugView<T>
	{
		[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
		public T[] Items { get; }

		public DebugEnumeratorDebugView(IDebugEnumerable<T> enumerable)
		{
			List<T> list = new List<T>();
			foreach (T item in enumerable)
			{
				list.Add(item);
			}
			Items = list.ToArray();
			base..ctor();
		}
	}
	[DebuggerDisplay("{DebuggerDisplay,nq}")]
	internal sealed class RendezvousChannel<T> : Channel<T>
	{
		[DebuggerDisplay("{DebuggerDisplay,nq}")]
		private sealed class RendezvousChannelReader : ChannelReader<T>
		{
			internal readonly RendezvousChannel<T> _parent;

			private readonly BlockedReadAsyncOperation<T> _readerSingleton;

			private readonly WaitingReadAsyncOperation _waiterSingleton;

			public override Task Completion => _parent._completion.Task;

			public override bool CanCount => true;

			public override bool CanPeek => true;

			public override int Count => 0;

			internal string DebuggerDisplay
			{
				get
				{
					long num;
					long num2;
					lock (_parent.SyncObj)
					{
						num = ChannelUtilities.CountOperations(_parent._blockedReadersHead);
						num2 = ChannelUtilities.CountOperations(_parent._waitingReadersHead);
					}
					return $"ReadAsync={num}, WaitToReadAsync={num2}";
				}
			}

			internal RendezvousChannelReader(RendezvousChannel<T> parent)
			{
				_parent = parent;
				_readerSingleton = new BlockedReadAsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true);
				_waiterSingleton = new WaitingReadAsyncOperation(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true);
			}

			public override bool TryRead([MaybeNullWhen(false)] out T item)
			{
				RendezvousChannel<T> parent = _parent;
				BlockedWriteAsyncOperation<T> blockedWriteAsyncOperation = null;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting == null)
					{
						blockedWriteAsyncOperation = ChannelUtilities.TryDequeueAndReserveCompletionIfCancelable(ref parent._blockedWritersHead);
					}
				}
				if (blockedWriteAsyncOperation != null)
				{
					item = blockedWriteAsyncOperation.Item;
					blockedWriteAsyncOperation.DangerousSetResult(default(VoidResult));
					return true;
				}
				item = default(T);
				return false;
			}

			public override bool TryPeek([MaybeNullWhen(false)] out T item)
			{
				RendezvousChannel<T> parent = _parent;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting == null)
					{
						BlockedWriteAsyncOperation<T> blockedWritersHead = parent._blockedWritersHead;
						if (blockedWritersHead != null)
						{
							item = blockedWritersHead.Item;
							return true;
						}
					}
				}
				item = default(T);
				return false;
			}

			public override ValueTask<T> ReadAsync(CancellationToken cancellationToken)
			{
				RendezvousChannel<T> parent = _parent;
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken));
				}
				BlockedReadAsyncOperation<T> blockedReadAsyncOperation = null;
				WaitingWriteAsyncOperation head = null;
				BlockedWriteAsyncOperation<T> blockedWriteAsyncOperation = null;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting != null)
					{
						return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting);
					}
					blockedWriteAsyncOperation = ChannelUtilities.TryDequeueAndReserveCompletionIfCancelable(ref parent._blockedWritersHead);
					if (blockedWriteAsyncOperation == null)
					{
						blockedReadAsyncOperation = ((!cancellationToken.CanBeCanceled && _readerSingleton.TryOwnAndReset()) ? _readerSingleton : new BlockedReadAsyncOperation<T>(parent._runContinuationsAsynchronously, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate));
						ChannelUtilities.Enqueue(ref parent._blockedReadersHead, blockedReadAsyncOperation);
						head = ChannelUtilities.TryReserveCompletionIfCancelable(ref parent._waitingWritersHead);
					}
				}
				if (blockedWriteAsyncOperation != null)
				{
					ValueTask<T> result = new ValueTask<T>(blockedWriteAsyncOperation.Item);
					blockedWriteAsyncOperation.DangerousSetResult(default(VoidResult));
					return result;
				}
				ChannelUtilities.DangerousSetOperations(head, result: true);
				return blockedReadAsyncOperation.ValueTaskOfT;
			}

			public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken));
				}
				RendezvousChannel<T> parent = _parent;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting != null)
					{
						return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>);
					}
					if (parent._blockedWritersHead != null)
					{
						return new ValueTask<bool>(result: true);
					}
					WaitingReadAsyncOperation waitingReadAsyncOperation = ((!cancellationToken.CanBeCanceled && _waiterSingleton.TryOwnAndReset()) ? _waiterSingleton : new WaitingReadAsyncOperation(parent._runContinuationsAsynchronously, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate));
					ChannelUtilities.Enqueue(ref parent._waitingReadersHead, waitingReadAsyncOperation);
					return waitingReadAsyncOperation.ValueTaskOfT;
				}
			}
		}

		[DebuggerDisplay("{DebuggerDisplay,nq}")]
		private sealed class RendezvousChannelWriter : ChannelWriter<T>
		{
			internal readonly RendezvousChannel<T> _parent;

			private readonly BlockedWriteAsyncOperation<T> _writerSingleton;

			private readonly WaitingWriteAsyncOperation _waiterSingleton;

			internal string DebuggerDisplay
			{
				get
				{
					long num;
					long num2;
					lock (_parent.SyncObj)
					{
						num = ChannelUtilities.CountOperations(_parent._blockedWritersHead);
						num2 = ChannelUtilities.CountOperations(_parent._waitingWritersHead);
					}
					return $"WriteAsync={num}, WaitToWriteAsync={num2}";
				}
			}

			internal RendezvousChannelWriter(RendezvousChannel<T> parent)
			{
				_parent = parent;
				_writerSingleton = new BlockedWriteAsyncOperation<T>(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true);
				_waiterSingleton = new WaitingWriteAsyncOperation(runContinuationsAsynchronously: true, default(CancellationToken), pooled: true);
			}

			public override bool TryComplete(Exception error)
			{
				RendezvousChannel<T> parent = _parent;
				BlockedReadAsyncOperation<T> blockedReadersHead;
				BlockedWriteAsyncOperation<T> blockedWritersHead;
				WaitingReadAsyncOperation waitingReadersHead;
				WaitingWriteAsyncOperation waitingWritersHead;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting != null)
					{
						return false;
					}
					parent._doneWriting = error ?? ChannelUtilities.s_doneWritingSentinel;
					blockedReadersHead = parent._blockedReadersHead;
					blockedWritersHead = parent._blockedWritersHead;
					waitingReadersHead = parent._waitingReadersHead;
					waitingWritersHead = parent._waitingWritersHead;
					parent._blockedReadersHead = null;
					parent._blockedWritersHead = null;
					parent._waitingReadersHead = null;
					parent._waitingWritersHead = null;
				}
				ChannelUtilities.Complete(parent._completion, error);
				ChannelUtilities.FailOperations(blockedReadersHead, ChannelUtilities.CreateInvalidCompletionException(error));
				ChannelUtilities.FailOperations(blockedWritersHead, ChannelUtilities.CreateInvalidCompletionException(error));
				ChannelUtilities.SetOrFailOperations(waitingReadersHead, result: false, error);
				ChannelUtilities.SetOrFailOperations(waitingWritersHead, result: false, error);
				return true;
			}

			public override bool TryWrite(T item)
			{
				RendezvousChannel<T> parent = _parent;
				BlockedReadAsyncOperation<T> blockedReadAsyncOperation = null;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting == null)
					{
						blockedReadAsyncOperation = ChannelUtilities.TryDequeueAndReserveCompletionIfCancelable(ref parent._blockedReadersHead);
					}
				}
				if (blockedReadAsyncOperation != null)
				{
					blockedReadAsyncOperation.DangerousSetResult(item);
					return true;
				}
				if (parent._dropWrites)
				{
					parent._itemDropped?.Invoke(item);
					return true;
				}
				return false;
			}

			public override ValueTask<bool> WaitToWriteAsync(CancellationToken cancellationToken)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken));
				}
				RendezvousChannel<T> parent = _parent;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting != null)
					{
						return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>);
					}
					if (parent._blockedReadersHead != null || parent._dropWrites)
					{
						return new ValueTask<bool>(result: true);
					}
					WaitingWriteAsyncOperation waitingWriteAsyncOperation = ((!cancellationToken.CanBeCanceled && _waiterSingleton.TryOwnAndReset()) ? _waiterSingleton : new WaitingWriteAsyncOperation(parent._runContinuationsAsynchronously, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate));
					ChannelUtilities.Enqueue(ref parent._waitingWritersHead, waitingWriteAsyncOperation);
					return waitingWriteAsyncOperation.ValueTaskOfT;
				}
			}

			public override ValueTask WriteAsync(T item, CancellationToken cancellationToken)
			{
				RendezvousChannel<T> parent = _parent;
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask(Task.FromCanceled<T>(cancellationToken));
				}
				BlockedWriteAsyncOperation<T> blockedWriteAsyncOperation = null;
				WaitingReadAsyncOperation head = null;
				BlockedReadAsyncOperation<T> blockedReadAsyncOperation = null;
				lock (parent.SyncObj)
				{
					if (parent._doneWriting != null)
					{
						return new ValueTask(Task.FromException(ChannelUtilities.CreateInvalidCompletionException(parent._doneWriting)));
					}
					blockedReadAsyncOperation = ChannelUtilities.TryDequeueAndReserveCompletionIfCancelable(ref parent._blockedReadersHead);
					if (blockedReadAsyncOperation == null && !parent._dropWrites)
					{
						blockedWriteAsyncOperation = ((!cancellationToken.CanBeCanceled && _writerSingleton.TryOwnAndReset()) ? _writerSingleton : new BlockedWriteAsyncOperation<T>(parent._runContinuationsAsynchronously, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate));
						blockedWriteAsyncOperation.Item = item;
						ChannelUtilities.Enqueue(ref parent._blockedWritersHead, blockedWriteAsyncOperation);
						head = ChannelUtilities.TryReserveCompletionIfCancelable(ref parent._waitingReadersHead);
					}
				}
				if (blockedWriteAsyncOperation != null)
				{
					ChannelUtilities.DangerousSetOperations(head, result: true);
					return blockedWriteAsyncOperation.ValueTask;
				}
				if (blockedReadAsyncOperation != null)
				{
					blockedReadAsyncOperation.DangerousSetResult(item);
				}
				else
				{
					parent._itemDropped?.Invoke(item);
				}
				return default(ValueTask);
			}
		}

		private readonly bool _dropWrites;

		private readonly Action<T> _itemDropped;

		private readonly TaskCompletionSource _completion;

		private BlockedReadAsyncOperation<T> _blockedReadersHead;

		private BlockedWriteAsyncOperation<T> _blockedWritersHead;

		private WaitingReadAsyncOperation _waitingReadersHead;

		private WaitingWriteAsyncOperation _waitingWritersHead;

		private readonly bool _runContinuationsAsynchronously;

		private Exception _doneWriting;

		private object SyncObj => _completion;

		private Action<object, CancellationToken> CancellationCallbackDelegate => delegate(object state, CancellationToken cancellationToken)
		{
			AsyncOperation asyncOperation = (AsyncOperation)state;
			if (asyncOperation.TrySetCanceled(cancellationToken))
			{
				ChannelUtilities.UnsafeQueueUserWorkItem(delegate(KeyValuePair<RendezvousChannel<T>, AsyncOperation> state)
				{
					lock (state.Key.SyncObj)
					{
						AsyncOperation value = state.Value;
						if (!(value is BlockedReadAsyncOperation<T> op))
						{
							if (!(value is BlockedWriteAsyncOperation<T> op2))
							{
								if (!(value is WaitingReadAsyncOperation op3))
								{
									if (value is WaitingWriteAsyncOperation op4)
									{
										ChannelUtilities.Remove(ref state.Key._waitingWritersHead, op4);
									}
								}
								else
								{
									ChannelUtilities.Remove(ref state.Key._waitingReadersHead, op3);
								}
							}
							else
							{
								ChannelUtilities.Remove(ref state.Key._blockedWritersHead, op2);
							}
						}
						else
						{
							ChannelUtilities.Remove(ref state.Key._blockedReadersHead, op);
						}
					}
				}, new KeyValuePair<RendezvousChannel<T>, AsyncOperation>(this, asyncOperation));
			}
		};

		private string DebuggerDisplay => ((RendezvousChannelReader)base.Reader).DebuggerDisplay + ", " + ((RendezvousChannelWriter)base.Writer).DebuggerDisplay;

		internal RendezvousChannel(BoundedChannelFullMode mode, bool runContinuationsAsynchronously, Action<T> itemDropped)
		{
			_dropWrites = mode != BoundedChannelFullMode.Wait;
			_runContinuationsAsynchronously = runContinuationsAsynchronously;
			_itemDropped = itemDropped;
			_completion = new TaskCompletionSource(runContinuationsAsynchronously ? TaskCreationOptions.RunContinuationsAsynchronously : TaskCreationOptions.None);
			base.Reader = new RendezvousChannelReader(this);
			base.Writer = new RendezvousChannelWriter(this);
		}

		[Conditional("DEBUG")]
		private void AssertInvariants()
		{
			_ = _blockedReadersHead;
			_ = _blockedWritersHead;
			_ = _completion.Task.IsCompleted;
		}
	}
	[DebuggerDisplay("Items = {ItemsCountForDebugger}, Closed = {ChannelIsClosedForDebugger}")]
	[DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))]
	internal sealed class SingleConsumerUnboundedChannel<T> : Channel<T>, IDebugEnumerable<T>
	{
		[DebuggerDisplay("Items = {ItemsCountForDebugger}")]
		[DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))]
		private sealed class UnboundedChannelReader : ChannelReader<T>, IDebugEnumerable<T>
		{
			internal readonly SingleConsumerUnboundedChannel<T> _parent;

			private readonly BlockedReadAsyncOperation<T> _readerSingleton;

			private readonly WaitingReadAsyncOperation _waiterSingleton;

			public override Task Completion => _parent._completion.Task;

			public override bool CanPeek => true;

			private int ItemsCountForDebugger => _parent._items.Count;

			internal UnboundedChannelReader(SingleConsumerUnboundedChannel<T> parent)
			{
				_parent = parent;
				_readerSingleton = new BlockedReadAsyncOperation<T>(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true);
				_waiterSingleton = new WaitingReadAsyncOperation(parent._runContinuationsAsynchronously, default(CancellationToken), pooled: true);
			}

			public override ValueTask<T> ReadAsync(CancellationToken cancellationToken)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask<T>(Task.FromCanceled<T>(cancellationToken));
				}
				if (TryRead(out var item))
				{
					return new ValueTask<T>(item);
				}
				SingleConsumerUnboundedChannel<T> parent = _parent;
				BlockedReadAsyncOperation<T> blockedReadAsyncOperation;
				BlockedReadAsyncOperation<T> blockedReadAsyncOperation2;
				lock (parent.SyncObj)
				{
					if (TryRead(out item))
					{
						return new ValueTask<T>(item);
					}
					if (parent._doneWriting != null)
					{
						return ChannelUtilities.GetInvalidCompletionValueTask<T>(parent._doneWriting);
					}
					blockedReadAsyncOperation = parent._blockedReader;
					if (!cancellationToken.CanBeCanceled && _readerSingleton.TryOwnAndReset())
					{
						blockedReadAsyncOperation2 = _readerSingleton;
						if (blockedReadAsyncOperation2 == blockedReadAsyncOperation)
						{
							blockedReadAsyncOperation = null;
						}
					}
					else
					{
						blockedReadAsyncOperation2 = new BlockedReadAsyncOperation<T>(_parent._runContinuationsAsynchronously, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate);
					}
					parent._blockedReader = blockedReadAsyncOperation2;
				}
				blockedReadAsyncOperation?.TrySetCanceled();
				return blockedReadAsyncOperation2.ValueTaskOfT;
			}

			public override bool TryRead([MaybeNullWhen(false)] out T item)
			{
				SingleConsumerUnboundedChannel<T> parent = _parent;
				if (parent._items.TryDequeue(out item))
				{
					if (parent._doneWriting != null && parent._items.IsEmpty)
					{
						ChannelUtilities.Complete(parent._completion, parent._doneWriting);
					}
					return true;
				}
				return false;
			}

			public override bool TryPeek([MaybeNullWhen(false)] out T item)
			{
				return _parent._items.TryPeek(out item);
			}

			public override ValueTask<bool> WaitToReadAsync(CancellationToken cancellationToken)
			{
				if (cancellationToken.IsCancellationRequested)
				{
					return new ValueTask<bool>(Task.FromCanceled<bool>(cancellationToken));
				}
				if (!_parent._items.IsEmpty)
				{
					return new ValueTask<bool>(result: true);
				}
				SingleConsumerUnboundedChannel<T> parent = _parent;
				WaitingReadAsyncOperation waitingReadAsyncOperation = null;
				WaitingReadAsyncOperation waitingReadAsyncOperation2;
				lock (parent.SyncObj)
				{
					if (!parent._items.IsEmpty)
					{
						return new ValueTask<bool>(result: true);
					}
					if (parent._doneWriting != null)
					{
						return (parent._doneWriting != ChannelUtilities.s_doneWritingSentinel) ? new ValueTask<bool>(Task.FromException<bool>(parent._doneWriting)) : default(ValueTask<bool>);
					}
					waitingReadAsyncOperation = parent._waitingReader;
					if (!cancellationToken.CanBeCanceled && _waiterSingleton.TryOwnAndReset())
					{
						waitingReadAsyncOperation2 = _waiterSingleton;
						if (waitingReadAsyncOperation2 == waitingReadAsyncOperation)
						{
							waitingReadAsyncOperation = null;
						}
					}
					else
					{
						waitingReadAsyncOperation2 = new WaitingReadAsyncOperation(_parent._runContinuationsAsynchronously, cancellationToken, pooled: false, _parent.CancellationCallbackDelegate);
					}
					parent._waitingReader = waitingReadAsyncOperation2;
				}
				waitingReadAsyncOperation?.TrySetCanceled();
				return waitingReadAsyncOperation2.ValueTaskOfT;
			}

			IEnumerator<T> IDebugEnumerable<T>.GetEnumerator()
			{
				return _parent._items.GetEnumerator();
			}
		}

		[DebuggerDisplay("Items = {ItemsCountForDebugger}")]
		[DebuggerTypeProxy(typeof(DebugEnumeratorDebugView<>))]
		private sealed class UnboundedChannelWriter : ChannelWriter<T>, IDebugEnumerable<T>
		{
			internal readonly SingleConsumerUnboundedChannel<T> _parent;

			private int ItemsCountForDebugger => _parent._items.Count;

			internal UnboundedChannelWriter(Singl

BepInEx/core/System.Threading.Tasks.Extensions.dll

Decompiled 2 weeks ago
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Threading.Tasks.Extensions")]
[assembly: AssemblyDescription("System.Threading.Tasks.Extensions")]
[assembly: AssemblyDefaultAlias("System.Threading.Tasks.Extensions")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: AssemblyInformationalVersion("4.0.0.0")]
[assembly: AssemblyFileVersion("4.0.0.0")]
[assembly: AssemblyVersion("4.2.0.0")]
[assembly: TypeForwardedTo(typeof(AsyncMethodBuilderAttribute))]
[assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder))]
[assembly: TypeForwardedTo(typeof(AsyncValueTaskMethodBuilder<>))]
[assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable))]
[assembly: TypeForwardedTo(typeof(ConfiguredValueTaskAwaitable<>))]
[assembly: TypeForwardedTo(typeof(ValueTaskAwaiter))]
[assembly: TypeForwardedTo(typeof(ValueTaskAwaiter<>))]
[assembly: TypeForwardedTo(typeof(IValueTaskSource))]
[assembly: TypeForwardedTo(typeof(IValueTaskSource<>))]
[assembly: TypeForwardedTo(typeof(ValueTaskSourceOnCompletedFlags))]
[assembly: TypeForwardedTo(typeof(ValueTaskSourceStatus))]
[assembly: TypeForwardedTo(typeof(ValueTask))]
[assembly: TypeForwardedTo(typeof(ValueTask<>))]

BepInEx/core/System.Transactions.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System.Transactions.Configuration;
using Unity;

[assembly: BestFitMapping(false)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Transactions.dll")]
[assembly: AssemblyDescription("System.Transactions.dll")]
[assembly: AssemblyDefaultAlias("System.Transactions.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: CompilationRelaxations(8)]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: AssemblyVersion("4.0.0.0")]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal sealed class Locale
{
	private Locale()
	{
	}

	public static string GetText(string msg)
	{
		return msg;
	}

	public static string GetText(string fmt, params object[] args)
	{
		return string.Format(fmt, args);
	}
}
namespace System
{
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoTODOAttribute : Attribute
	{
		private string comment;

		public string Comment => comment;

		public MonoTODOAttribute()
		{
		}

		public MonoTODOAttribute(string comment)
		{
			this.comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoDocumentationNoteAttribute : MonoTODOAttribute
	{
		public MonoDocumentationNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoExtensionAttribute : MonoTODOAttribute
	{
		public MonoExtensionAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoInternalNoteAttribute : MonoTODOAttribute
	{
		public MonoInternalNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoLimitationAttribute : MonoTODOAttribute
	{
		public MonoLimitationAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoNotSupportedAttribute : MonoTODOAttribute
	{
		public MonoNotSupportedAttribute(string comment)
			: base(comment)
		{
		}
	}
}
namespace System.Transactions
{
	[Serializable]
	public sealed class CommittableTransaction : Transaction, ISerializable, IDisposable, IAsyncResult
	{
		private TransactionOptions options;

		private AsyncCallback callback;

		private object user_defined_state;

		private IAsyncResult asyncResult;

		object IAsyncResult.AsyncState => user_defined_state;

		WaitHandle IAsyncResult.AsyncWaitHandle => asyncResult.AsyncWaitHandle;

		bool IAsyncResult.CompletedSynchronously => asyncResult.CompletedSynchronously;

		bool IAsyncResult.IsCompleted => asyncResult.IsCompleted;

		public CommittableTransaction()
			: this(default(TransactionOptions))
		{
		}

		public CommittableTransaction(TimeSpan timeout)
			: base(IsolationLevel.Serializable)
		{
			options = default(TransactionOptions);
			options.Timeout = timeout;
		}

		public CommittableTransaction(TransactionOptions options)
			: base(options.IsolationLevel)
		{
			this.options = options;
		}

		public IAsyncResult BeginCommit(AsyncCallback asyncCallback, object asyncState)
		{
			callback = asyncCallback;
			user_defined_state = asyncState;
			AsyncCallback asyncCallback2 = null;
			if (asyncCallback != null)
			{
				asyncCallback2 = CommitCallback;
			}
			asyncResult = BeginCommitInternal(asyncCallback2);
			return this;
		}

		public void EndCommit(IAsyncResult asyncResult)
		{
			if (asyncResult != this)
			{
				throw new ArgumentException("The IAsyncResult parameter must be the same parameter as returned by BeginCommit.", "asyncResult");
			}
			EndCommitInternal(this.asyncResult);
		}

		private void CommitCallback(IAsyncResult ar)
		{
			if (asyncResult == null && ar.CompletedSynchronously)
			{
				asyncResult = ar;
			}
			callback(this);
		}

		public void Commit()
		{
			CommitInternal();
		}

		[MonoTODO("Not implemented")]
		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			throw new NotImplementedException();
		}
	}
	public delegate Transaction HostCurrentTransactionCallback();
	public delegate void TransactionCompletedEventHandler(object sender, TransactionEventArgs e);
	public delegate void TransactionStartedEventHandler(object sender, TransactionEventArgs e);
	public enum DependentCloneOption
	{
		BlockCommitUntilComplete,
		RollbackIfNotComplete
	}
	[Serializable]
	[MonoTODO("Not supported yet")]
	public sealed class DependentTransaction : Transaction, ISerializable
	{
		private bool completed;

		internal bool Completed => completed;

		internal DependentTransaction(Transaction parent, DependentCloneOption option)
			: base(parent.IsolationLevel)
		{
		}

		[MonoTODO]
		public void Complete()
		{
			throw new NotImplementedException();
		}

		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			completed = info.GetBoolean("completed");
		}

		internal DependentTransaction()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	public class Enlistment
	{
		internal bool done;

		internal Enlistment()
		{
			done = false;
		}

		public void Done()
		{
			done = true;
			InternalOnDone();
		}

		internal virtual void InternalOnDone()
		{
		}
	}
	[Flags]
	public enum EnlistmentOptions
	{
		None = 0,
		EnlistDuringPrepareRequired = 1
	}
	public enum EnterpriseServicesInteropOption
	{
		None,
		Automatic,
		Full
	}
	[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
	public interface IDtcTransaction
	{
		void Abort(IntPtr reason, int retaining, int async);

		void Commit(int retaining, int commitType, int reserved);

		void GetTransactionInfo(IntPtr transactionInformation);
	}
	public interface IEnlistmentNotification
	{
		void Commit(Enlistment enlistment);

		void InDoubt(Enlistment enlistment);

		void Prepare(PreparingEnlistment preparingEnlistment);

		void Rollback(Enlistment enlistment);
	}
	public interface IPromotableSinglePhaseNotification : ITransactionPromoter
	{
		void Initialize();

		void Rollback(SinglePhaseEnlistment singlePhaseEnlistment);

		void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment);
	}
	public interface ISimpleTransactionSuperior : ITransactionPromoter
	{
		void Rollback();
	}
	public interface ISinglePhaseNotification : IEnlistmentNotification
	{
		void SinglePhaseCommit(SinglePhaseEnlistment singlePhaseEnlistment);
	}
	public interface ITransactionPromoter
	{
		byte[] Promote();
	}
	public enum IsolationLevel
	{
		Serializable,
		RepeatableRead,
		ReadCommitted,
		ReadUncommitted,
		Snapshot,
		Chaos,
		Unspecified
	}
	public class PreparingEnlistment : Enlistment
	{
		private bool prepared;

		private Transaction tx;

		private IEnlistmentNotification enlisted;

		private WaitHandle waitHandle;

		private Exception ex;

		internal bool IsPrepared => prepared;

		internal WaitHandle WaitHandle => waitHandle;

		internal IEnlistmentNotification EnlistmentNotification => enlisted;

		internal Exception Exception
		{
			get
			{
				return ex;
			}
			set
			{
				ex = value;
			}
		}

		internal PreparingEnlistment(Transaction tx, IEnlistmentNotification enlisted)
		{
			this.tx = tx;
			this.enlisted = enlisted;
			waitHandle = new ManualResetEvent(initialState: false);
		}

		public void ForceRollback()
		{
			ForceRollback(null);
		}

		internal override void InternalOnDone()
		{
			Prepared();
		}

		[MonoTODO]
		public void ForceRollback(Exception e)
		{
			tx.Rollback(e, enlisted);
			((ManualResetEvent)waitHandle).Set();
		}

		[MonoTODO]
		public void Prepared()
		{
			prepared = true;
			((ManualResetEvent)waitHandle).Set();
		}

		[MonoTODO]
		public byte[] RecoveryInformation()
		{
			throw new NotImplementedException();
		}

		internal PreparingEnlistment()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	public class SinglePhaseEnlistment : Enlistment
	{
		private Transaction tx;

		private object abortingEnlisted;

		internal SinglePhaseEnlistment()
		{
		}

		internal SinglePhaseEnlistment(Transaction tx, object abortingEnlisted)
		{
			this.tx = tx;
			this.abortingEnlisted = abortingEnlisted;
		}

		public void Aborted()
		{
			Aborted(null);
		}

		public void Aborted(Exception e)
		{
			if (tx != null)
			{
				tx.Rollback(e, abortingEnlisted);
			}
		}

		[MonoTODO]
		public void Committed()
		{
		}

		[MonoTODO("Not implemented")]
		public void InDoubt()
		{
			throw new NotImplementedException();
		}

		[MonoTODO("Not implemented")]
		public void InDoubt(Exception e)
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	public sealed class SubordinateTransaction : Transaction
	{
		public SubordinateTransaction(IsolationLevel isoLevel, ISimpleTransactionSuperior superior)
			: base(isoLevel)
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	public class Transaction : IDisposable, ISerializable
	{
		private delegate void AsyncCommit();

		[ThreadStatic]
		private static Transaction ambient;

		private Transaction internalTransaction;

		private IsolationLevel level;

		private TransactionInformation info;

		private ArrayList dependents;

		private List<IEnlistmentNotification> volatiles;

		private List<ISinglePhaseNotification> durables;

		private IPromotableSinglePhaseNotification pspe;

		private AsyncCommit asyncCommit;

		private bool committing;

		private bool committed;

		private bool aborted;

		private TransactionScope scope;

		private Exception innerException;

		private Guid tag;

		internal List<IEnlistmentNotification> Volatiles
		{
			get
			{
				if (volatiles == null)
				{
					volatiles = new List<IEnlistmentNotification>();
				}
				return volatiles;
			}
		}

		internal List<ISinglePhaseNotification> Durables
		{
			get
			{
				if (durables == null)
				{
					durables = new List<ISinglePhaseNotification>();
				}
				return durables;
			}
		}

		internal IPromotableSinglePhaseNotification Pspe => pspe;

		public static Transaction Current
		{
			get
			{
				EnsureIncompleteCurrentScope();
				return CurrentInternal;
			}
			set
			{
				EnsureIncompleteCurrentScope();
				CurrentInternal = value;
			}
		}

		internal static Transaction CurrentInternal
		{
			get
			{
				return ambient;
			}
			set
			{
				ambient = value;
			}
		}

		public IsolationLevel IsolationLevel
		{
			get
			{
				EnsureIncompleteCurrentScope();
				return level;
			}
		}

		public TransactionInformation TransactionInformation
		{
			get
			{
				EnsureIncompleteCurrentScope();
				return info;
			}
		}

		public Guid PromoterType
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		private bool Aborted
		{
			get
			{
				return aborted;
			}
			set
			{
				aborted = value;
				if (aborted)
				{
					info.Status = TransactionStatus.Aborted;
				}
			}
		}

		internal TransactionScope Scope
		{
			get
			{
				return scope;
			}
			set
			{
				scope = value;
			}
		}

		internal event TransactionCompletedEventHandler TransactionCompletedInternal;

		public event TransactionCompletedEventHandler TransactionCompleted
		{
			add
			{
				if (internalTransaction != null)
				{
					internalTransaction.TransactionCompleted += value;
				}
				TransactionCompletedInternal += value;
			}
			remove
			{
				if (internalTransaction != null)
				{
					internalTransaction.TransactionCompleted -= value;
				}
				TransactionCompletedInternal -= value;
			}
		}

		internal Transaction(IsolationLevel isolationLevel)
		{
			dependents = new ArrayList();
			tag = Guid.NewGuid();
			base..ctor();
			info = new TransactionInformation();
			level = isolationLevel;
		}

		internal Transaction(Transaction other)
		{
			dependents = new ArrayList();
			tag = Guid.NewGuid();
			base..ctor();
			level = other.level;
			info = other.info;
			dependents = other.dependents;
			volatiles = other.Volatiles;
			durables = other.Durables;
			pspe = other.Pspe;
			this.TransactionCompletedInternal = other.TransactionCompletedInternal;
			internalTransaction = other;
		}

		[MonoTODO]
		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			throw new NotImplementedException();
		}

		public Transaction Clone()
		{
			return new Transaction(this);
		}

		public void Dispose()
		{
			if (TransactionInformation.Status == TransactionStatus.Active)
			{
				Rollback();
			}
		}

		[MonoTODO]
		public DependentTransaction DependentClone(DependentCloneOption cloneOption)
		{
			DependentTransaction dependentTransaction = new DependentTransaction(this, cloneOption);
			dependents.Add(dependentTransaction);
			return dependentTransaction;
		}

		[MonoTODO("Only SinglePhase commit supported for durable resource managers.")]
		[PermissionSet(SecurityAction.LinkDemand)]
		public Enlistment EnlistDurable(Guid resourceManagerIdentifier, IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions)
		{
			throw new NotImplementedException("DTC unsupported, only SinglePhase commit supported for durable resource managers.");
		}

		[MonoTODO("Only Local Transaction Manager supported. Cannot have more than 1 durable resource per transaction. Only EnlistmentOptions.None supported yet.")]
		[PermissionSet(SecurityAction.LinkDemand)]
		public Enlistment EnlistDurable(Guid resourceManagerIdentifier, ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions)
		{
			EnsureIncompleteCurrentScope();
			if (pspe != null || Durables.Count > 0)
			{
				throw new NotImplementedException("DTC unsupported, multiple durable resource managers aren't supported.");
			}
			if (enlistmentOptions != 0)
			{
				throw new NotImplementedException("EnlistmentOptions other than None aren't supported");
			}
			Durables.Add(singlePhaseNotification);
			return new Enlistment();
		}

		public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification)
		{
			EnsureIncompleteCurrentScope();
			if (pspe != null || Durables.Count > 0)
			{
				return false;
			}
			pspe = promotableSinglePhaseNotification;
			pspe.Initialize();
			return true;
		}

		public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification promotableNotification, Guid distributedTransactionIdentifier)
		{
			throw new NotImplementedException();
		}

		public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
		{
			throw new NotImplementedException();
		}

		public byte[] GetPromotedToken()
		{
			throw new NotImplementedException();
		}

		[MonoTODO("EnlistmentOptions being ignored")]
		public Enlistment EnlistVolatile(IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions)
		{
			return EnlistVolatileInternal(enlistmentNotification, enlistmentOptions);
		}

		[MonoTODO("EnlistmentOptions being ignored")]
		public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions)
		{
			return EnlistVolatileInternal(singlePhaseNotification, enlistmentOptions);
		}

		private Enlistment EnlistVolatileInternal(IEnlistmentNotification notification, EnlistmentOptions options)
		{
			EnsureIncompleteCurrentScope();
			Volatiles.Add(notification);
			return new Enlistment();
		}

		[MonoTODO("Only Local Transaction Manager supported. Cannot have more than 1 durable resource per transaction.")]
		[PermissionSet(SecurityAction.LinkDemand)]
		public Enlistment PromoteAndEnlistDurable(Guid manager, IPromotableSinglePhaseNotification promotableNotification, ISinglePhaseNotification notification, EnlistmentOptions options)
		{
			throw new NotImplementedException("DTC unsupported, multiple durable resource managers aren't supported.");
		}

		public override bool Equals(object obj)
		{
			return Equals(obj as Transaction);
		}

		private bool Equals(Transaction t)
		{
			if ((object)t == this)
			{
				return true;
			}
			if ((object)t == null)
			{
				return false;
			}
			if (level == t.level)
			{
				return info == t.info;
			}
			return false;
		}

		public static bool operator ==(Transaction x, Transaction y)
		{
			return x?.Equals(y) ?? ((object)y == null);
		}

		public static bool operator !=(Transaction x, Transaction y)
		{
			return !(x == y);
		}

		public override int GetHashCode()
		{
			return (int)level ^ info.GetHashCode() ^ dependents.GetHashCode();
		}

		public void Rollback()
		{
			Rollback(null);
		}

		public void Rollback(Exception e)
		{
			EnsureIncompleteCurrentScope();
			Rollback(e, null);
		}

		internal void Rollback(Exception ex, object abortingEnlisted)
		{
			if (aborted)
			{
				FireCompleted();
				return;
			}
			if (info.Status == TransactionStatus.Committed)
			{
				throw new TransactionException("Transaction has already been committed. Cannot accept any new work.");
			}
			innerException = ex;
			SinglePhaseEnlistment singlePhaseEnlistment = new SinglePhaseEnlistment();
			foreach (IEnlistmentNotification @volatile in Volatiles)
			{
				if (@volatile != abortingEnlisted)
				{
					@volatile.Rollback(singlePhaseEnlistment);
				}
			}
			List<ISinglePhaseNotification> list = Durables;
			if (list.Count > 0 && list[0] != abortingEnlisted)
			{
				list[0].Rollback(singlePhaseEnlistment);
			}
			if (pspe != null && pspe != abortingEnlisted)
			{
				pspe.Rollback(singlePhaseEnlistment);
			}
			Aborted = true;
			FireCompleted();
		}

		protected IAsyncResult BeginCommitInternal(AsyncCallback callback)
		{
			if (committed || committing)
			{
				throw new InvalidOperationException("Commit has already been called for this transaction.");
			}
			committing = true;
			asyncCommit = DoCommit;
			return asyncCommit.BeginInvoke(callback, null);
		}

		protected void EndCommitInternal(IAsyncResult ar)
		{
			asyncCommit.EndInvoke(ar);
		}

		internal void CommitInternal()
		{
			if (committed || committing)
			{
				throw new InvalidOperationException("Commit has already been called for this transaction.");
			}
			committing = true;
			try
			{
				DoCommit();
			}
			catch (TransactionException)
			{
				throw;
			}
			catch (Exception ex2)
			{
				throw new TransactionAbortedException("Transaction failed", ex2);
			}
		}

		private void DoCommit()
		{
			if (Scope != null && (!Scope.IsComplete || !Scope.IsDisposed))
			{
				Rollback(null, null);
				CheckAborted();
			}
			List<IEnlistmentNotification> list = Volatiles;
			List<ISinglePhaseNotification> list2 = Durables;
			if (list.Count == 1 && list2.Count == 0 && list[0] is ISinglePhaseNotification single)
			{
				DoSingleCommit(single);
				Complete();
				return;
			}
			if (list.Count > 0)
			{
				DoPreparePhase();
			}
			if (list2.Count > 0)
			{
				DoSingleCommit(list2[0]);
			}
			if (pspe != null)
			{
				DoSingleCommit(pspe);
			}
			if (list.Count > 0)
			{
				DoCommitPhase();
			}
			Complete();
		}

		private void Complete()
		{
			committing = false;
			committed = true;
			if (!aborted)
			{
				info.Status = TransactionStatus.Committed;
			}
			FireCompleted();
		}

		internal void InitScope(TransactionScope scope)
		{
			CheckAborted();
			if (committed)
			{
				throw new InvalidOperationException("Commit has already been called on this transaction.");
			}
			Scope = scope;
		}

		private static void PrepareCallbackWrapper(object state)
		{
			PreparingEnlistment preparingEnlistment = state as PreparingEnlistment;
			try
			{
				preparingEnlistment.EnlistmentNotification.Prepare(preparingEnlistment);
			}
			catch (Exception exception)
			{
				preparingEnlistment.Exception = exception;
				if (!preparingEnlistment.IsPrepared)
				{
					((ManualResetEvent)preparingEnlistment.WaitHandle).Set();
				}
			}
		}

		private void DoPreparePhase()
		{
			foreach (IEnlistmentNotification @volatile in Volatiles)
			{
				PreparingEnlistment preparingEnlistment = new PreparingEnlistment(this, @volatile);
				ThreadPool.QueueUserWorkItem(PrepareCallbackWrapper, preparingEnlistment);
				TimeSpan timeout = ((Scope != null) ? Scope.Timeout : TransactionManager.DefaultTimeout);
				if (!preparingEnlistment.WaitHandle.WaitOne(timeout, exitContext: true))
				{
					Aborted = true;
					throw new TimeoutException("Transaction timedout");
				}
				if (preparingEnlistment.Exception != null)
				{
					innerException = preparingEnlistment.Exception;
					Aborted = true;
					break;
				}
				if (!preparingEnlistment.IsPrepared)
				{
					Aborted = true;
					break;
				}
			}
			CheckAborted();
		}

		private void DoCommitPhase()
		{
			foreach (IEnlistmentNotification @volatile in Volatiles)
			{
				Enlistment enlistment = new Enlistment();
				@volatile.Commit(enlistment);
			}
		}

		private void DoSingleCommit(ISinglePhaseNotification single)
		{
			if (single != null)
			{
				single.SinglePhaseCommit(new SinglePhaseEnlistment(this, single));
				CheckAborted();
			}
		}

		private void DoSingleCommit(IPromotableSinglePhaseNotification single)
		{
			if (single != null)
			{
				single.SinglePhaseCommit(new SinglePhaseEnlistment(this, single));
				CheckAborted();
			}
		}

		private void CheckAborted()
		{
			if (aborted || (Scope != null && Scope.IsAborted))
			{
				throw new TransactionAbortedException("Transaction has aborted", innerException);
			}
		}

		private void FireCompleted()
		{
			if (this.TransactionCompletedInternal != null)
			{
				this.TransactionCompletedInternal(this, new TransactionEventArgs(this));
			}
		}

		private static void EnsureIncompleteCurrentScope()
		{
			if (CurrentInternal == null || CurrentInternal.Scope == null || !CurrentInternal.Scope.IsComplete)
			{
				return;
			}
			throw new InvalidOperationException("The current TransactionScope is already complete");
		}

		internal Transaction()
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	[Serializable]
	public class TransactionAbortedException : TransactionException
	{
		public TransactionAbortedException()
		{
		}

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

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

		protected TransactionAbortedException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	public class TransactionEventArgs : EventArgs
	{
		private Transaction transaction;

		public Transaction Transaction => transaction;

		public TransactionEventArgs()
		{
		}

		internal TransactionEventArgs(Transaction transaction)
			: this()
		{
			this.transaction = transaction;
		}
	}
	[Serializable]
	public class TransactionException : SystemException
	{
		public TransactionException()
		{
		}

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

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

		protected TransactionException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	[Serializable]
	public class TransactionInDoubtException : TransactionException
	{
		public TransactionInDoubtException()
		{
		}

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

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

		protected TransactionInDoubtException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	public class TransactionInformation
	{
		private string local_id;

		private Guid dtcId = Guid.Empty;

		private DateTime creation_time;

		private TransactionStatus status;

		public DateTime CreationTime => creation_time;

		public Guid DistributedIdentifier
		{
			get
			{
				return dtcId;
			}
			internal set
			{
				dtcId = value;
			}
		}

		public string LocalIdentifier => local_id;

		public TransactionStatus Status
		{
			get
			{
				return status;
			}
			internal set
			{
				status = value;
			}
		}

		internal TransactionInformation()
		{
			status = TransactionStatus.Active;
			creation_time = DateTime.Now.ToUniversalTime();
			local_id = Guid.NewGuid().ToString() + ":1";
		}

		private TransactionInformation(TransactionInformation other)
		{
			local_id = other.local_id;
			dtcId = other.dtcId;
			creation_time = other.creation_time;
			status = other.status;
		}

		internal TransactionInformation Clone(TransactionInformation other)
		{
			return new TransactionInformation(other);
		}
	}
	[MonoTODO]
	public static class TransactionInterop
	{
		public static readonly Guid PromoterTypeDtc = new Guid("14229753-FFE1-428D-82B7-DF73045CB8DA");

		[MonoTODO]
		public static IDtcTransaction GetDtcTransaction(Transaction transaction)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static byte[] GetExportCookie(Transaction transaction, byte[] whereabouts)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static Transaction GetTransactionFromDtcTransaction(IDtcTransaction transactionNative)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static Transaction GetTransactionFromExportCookie(byte[] cookie)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static Transaction GetTransactionFromTransmitterPropagationToken(byte[] propagationToken)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static byte[] GetTransmitterPropagationToken(Transaction transaction)
		{
			throw new NotImplementedException();
		}

		[MonoTODO]
		public static byte[] GetWhereabouts()
		{
			throw new NotImplementedException();
		}
	}
	public static class TransactionManager
	{
		private static DefaultSettingsSection defaultSettings;

		private static MachineSettingsSection machineSettings;

		private static TimeSpan defaultTimeout;

		private static TimeSpan maxTimeout;

		public static TimeSpan DefaultTimeout
		{
			get
			{
				if (defaultSettings != null)
				{
					return defaultSettings.Timeout;
				}
				return defaultTimeout;
			}
		}

		[MonoTODO("Not implemented")]
		public static HostCurrentTransactionCallback HostCurrentCallback
		{
			get
			{
				throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}

		public static TimeSpan MaximumTimeout
		{
			get
			{
				if (machineSettings != null)
				{
					return machineSettings.MaxTimeout;
				}
				return maxTimeout;
			}
		}

		public static event TransactionStartedEventHandler DistributedTransactionStarted;

		static TransactionManager()
		{
			defaultTimeout = new TimeSpan(0, 1, 0);
			maxTimeout = new TimeSpan(0, 10, 0);
			defaultSettings = ConfigurationManager.GetSection("system.transactions/defaultSettings") as DefaultSettingsSection;
			machineSettings = ConfigurationManager.GetSection("system.transactions/machineSettings") as MachineSettingsSection;
		}

		[MonoTODO("Not implemented")]
		public static void RecoveryComplete(Guid resourceManagerIdentifier)
		{
			throw new NotImplementedException();
		}

		[MonoTODO("Not implemented")]
		public static Enlistment Reenlist(Guid resourceManagerIdentifier, byte[] recoveryInformation, IEnlistmentNotification enlistmentNotification)
		{
			throw new NotImplementedException();
		}
	}
	[Serializable]
	public class TransactionManagerCommunicationException : TransactionException
	{
		public TransactionManagerCommunicationException()
		{
		}

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

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

		protected TransactionManagerCommunicationException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	public struct TransactionOptions
	{
		private IsolationLevel level;

		private TimeSpan timeout;

		public IsolationLevel IsolationLevel
		{
			get
			{
				return level;
			}
			set
			{
				level = value;
			}
		}

		public TimeSpan Timeout
		{
			get
			{
				return timeout;
			}
			set
			{
				timeout = value;
			}
		}

		internal TransactionOptions(IsolationLevel level, TimeSpan timeout)
		{
			this.level = level;
			this.timeout = timeout;
		}

		public static bool operator ==(TransactionOptions x, TransactionOptions y)
		{
			if (x.level == y.level)
			{
				return x.timeout == y.timeout;
			}
			return false;
		}

		public static bool operator !=(TransactionOptions x, TransactionOptions y)
		{
			if (x.level == y.level)
			{
				return x.timeout != y.timeout;
			}
			return true;
		}

		public override bool Equals(object obj)
		{
			if (!(obj is TransactionOptions))
			{
				return false;
			}
			return this == (TransactionOptions)obj;
		}

		public override int GetHashCode()
		{
			return (int)level ^ timeout.GetHashCode();
		}
	}
	[Serializable]
	public class TransactionPromotionException : TransactionException
	{
		public TransactionPromotionException()
		{
		}

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

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

		protected TransactionPromotionException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}
	}
	public sealed class TransactionScope : IDisposable
	{
		private static TransactionOptions defaultOptions = new TransactionOptions(IsolationLevel.Serializable, TransactionManager.DefaultTimeout);

		private Timer scopeTimer;

		private Transaction transaction;

		private Transaction oldTransaction;

		private TransactionScope parentScope;

		private TimeSpan timeout;

		private int nested;

		private bool disposed;

		private bool completed;

		private bool aborted;

		private bool isRoot;

		private bool asyncFlowEnabled;

		internal bool IsAborted => aborted;

		internal bool IsDisposed => disposed;

		internal bool IsComplete => completed;

		internal TimeSpan Timeout => timeout;

		public TransactionScope()
			: this(TransactionScopeOption.Required, TransactionManager.DefaultTimeout)
		{
		}

		public TransactionScope(TransactionScopeAsyncFlowOption asyncFlowOption)
			: this(TransactionScopeOption.Required, TransactionManager.DefaultTimeout, asyncFlowOption)
		{
		}

		public TransactionScope(Transaction transactionToUse)
			: this(transactionToUse, TransactionManager.DefaultTimeout)
		{
		}

		public TransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout)
			: this(transactionToUse, scopeTimeout, EnterpriseServicesInteropOption.None)
		{
		}

		[MonoTODO("EnterpriseServicesInteropOption not supported.")]
		public TransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout, EnterpriseServicesInteropOption interopOption)
		{
			Initialize(TransactionScopeOption.Required, transactionToUse, defaultOptions, interopOption, scopeTimeout, TransactionScopeAsyncFlowOption.Suppress);
		}

		public TransactionScope(TransactionScopeOption scopeOption)
			: this(scopeOption, TransactionManager.DefaultTimeout)
		{
		}

		public TransactionScope(TransactionScopeOption scopeOption, TimeSpan scopeTimeout)
			: this(scopeOption, scopeTimeout, TransactionScopeAsyncFlowOption.Suppress)
		{
		}

		public TransactionScope(TransactionScopeOption option, TransactionScopeAsyncFlowOption asyncFlow)
			: this(option, TransactionManager.DefaultTimeout, asyncFlow)
		{
		}

		public TransactionScope(TransactionScopeOption scopeOption, TimeSpan scopeTimeout, TransactionScopeAsyncFlowOption asyncFlow)
		{
			Initialize(scopeOption, null, defaultOptions, EnterpriseServicesInteropOption.None, scopeTimeout, asyncFlow);
		}

		public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions)
			: this(scopeOption, transactionOptions, EnterpriseServicesInteropOption.None)
		{
		}

		[MonoTODO("EnterpriseServicesInteropOption not supported")]
		public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions, EnterpriseServicesInteropOption interopOption)
		{
			Initialize(scopeOption, null, transactionOptions, interopOption, transactionOptions.Timeout, TransactionScopeAsyncFlowOption.Suppress);
		}

		public TransactionScope(Transaction transactionToUse, TransactionScopeAsyncFlowOption asyncFlowOption)
		{
			throw new NotImplementedException();
		}

		public TransactionScope(Transaction transactionToUse, TimeSpan scopeTimeout, TransactionScopeAsyncFlowOption asyncFlowOption)
		{
			throw new NotImplementedException();
		}

		public TransactionScope(TransactionScopeOption scopeOption, TransactionOptions transactionOptions, TransactionScopeAsyncFlowOption asyncFlowOption)
		{
			throw new NotImplementedException();
		}

		private void Initialize(TransactionScopeOption scopeOption, Transaction tx, TransactionOptions options, EnterpriseServicesInteropOption interop, TimeSpan scopeTimeout, TransactionScopeAsyncFlowOption asyncFlow)
		{
			completed = false;
			isRoot = false;
			nested = 0;
			asyncFlowEnabled = asyncFlow == TransactionScopeAsyncFlowOption.Enabled;
			if (scopeTimeout < TimeSpan.Zero)
			{
				throw new ArgumentOutOfRangeException("scopeTimeout");
			}
			timeout = scopeTimeout;
			oldTransaction = Transaction.CurrentInternal;
			Transaction.CurrentInternal = (transaction = InitTransaction(tx, scopeOption, options));
			if (transaction != null)
			{
				transaction.InitScope(this);
			}
			if (parentScope != null)
			{
				parentScope.nested++;
			}
			if (timeout != TimeSpan.Zero)
			{
				scopeTimer = new Timer(TimerCallback, this, scopeTimeout, TimeSpan.Zero);
			}
		}

		private static void TimerCallback(object state)
		{
			if (!(state is TransactionScope transactionScope))
			{
				throw new TransactionException("TransactionScopeTimerObjectInvalid", null);
			}
			transactionScope.TimeoutScope();
		}

		private void TimeoutScope()
		{
			if (!completed && transaction != null)
			{
				try
				{
					transaction.Rollback();
					aborted = true;
				}
				catch (ObjectDisposedException)
				{
				}
				catch (TransactionException)
				{
				}
			}
		}

		private Transaction InitTransaction(Transaction tx, TransactionScopeOption scopeOption, TransactionOptions options)
		{
			if (tx != null)
			{
				return tx;
			}
			switch (scopeOption)
			{
			case TransactionScopeOption.Suppress:
				if (Transaction.CurrentInternal != null)
				{
					parentScope = Transaction.CurrentInternal.Scope;
				}
				return null;
			case TransactionScopeOption.Required:
				if (Transaction.CurrentInternal == null)
				{
					isRoot = true;
					return new Transaction(options.IsolationLevel);
				}
				parentScope = Transaction.CurrentInternal.Scope;
				return Transaction.CurrentInternal;
			default:
				if (Transaction.CurrentInternal != null)
				{
					parentScope = Transaction.CurrentInternal.Scope;
				}
				isRoot = true;
				return new Transaction(options.IsolationLevel);
			}
		}

		public void Complete()
		{
			if (completed)
			{
				throw new InvalidOperationException("The current TransactionScope is already complete. You should dispose the TransactionScope.");
			}
			completed = true;
		}

		public void Dispose()
		{
			if (disposed)
			{
				return;
			}
			disposed = true;
			if (parentScope != null)
			{
				parentScope.nested--;
			}
			if (nested > 0)
			{
				transaction.Rollback();
				throw new InvalidOperationException("TransactionScope nested incorrectly");
			}
			if (Transaction.CurrentInternal != transaction && !asyncFlowEnabled)
			{
				if (transaction != null)
				{
					transaction.Rollback();
				}
				if (Transaction.CurrentInternal != null)
				{
					Transaction.CurrentInternal.Rollback();
				}
				throw new InvalidOperationException("Transaction.Current has changed inside of the TransactionScope");
			}
			if (scopeTimer != null)
			{
				scopeTimer.Dispose();
			}
			if (asyncFlowEnabled)
			{
				if (oldTransaction != null)
				{
					oldTransaction.Scope = parentScope;
				}
				Transaction currentInternal = Transaction.CurrentInternal;
				if (!(transaction == null) || !(currentInternal == null))
				{
					currentInternal.Scope = parentScope;
					Transaction.CurrentInternal = oldTransaction;
					transaction.Scope = null;
					if (IsAborted)
					{
						throw new TransactionAbortedException("Transaction has aborted");
					}
					if (!IsComplete)
					{
						transaction.Rollback();
						currentInternal.Rollback();
					}
					else if (isRoot)
					{
						currentInternal.CommitInternal();
						transaction.CommitInternal();
					}
				}
				return;
			}
			if (Transaction.CurrentInternal == oldTransaction && oldTransaction != null)
			{
				oldTransaction.Scope = parentScope;
			}
			Transaction.CurrentInternal = oldTransaction;
			if (!(transaction == null))
			{
				if (IsAborted)
				{
					transaction.Scope = null;
					throw new TransactionAbortedException("Transaction has aborted");
				}
				if (!IsComplete)
				{
					transaction.Rollback();
				}
				else if (isRoot)
				{
					transaction.CommitInternal();
					transaction.Scope = null;
				}
			}
		}
	}
	public enum TransactionScopeAsyncFlowOption
	{
		Suppress,
		Enabled
	}
	public enum TransactionScopeOption
	{
		Required,
		RequiresNew,
		Suppress
	}
	public enum TransactionStatus
	{
		Active,
		Committed,
		Aborted,
		InDoubt
	}
}
namespace System.Transactions.Configuration
{
	public class DefaultSettingsSection : ConfigurationSection
	{
		[TimeSpanValidator(MinValueString = "00:00:00", MaxValueString = "10675199.02:48:05.4775807")]
		[ConfigurationProperty("timeout", DefaultValue = "00:01:00")]
		public TimeSpan Timeout
		{
			get
			{
				return (TimeSpan)((ConfigurationElement)this)["timeout"];
			}
			set
			{
				((ConfigurationElement)this)["timeout"] = value;
			}
		}

		[ConfigurationProperty("distributedTransactionManagerName", DefaultValue = "")]
		public string DistributedTransactionManagerName
		{
			get
			{
				return ((ConfigurationElement)this)["distributedTransactionManagerName"] as string;
			}
			set
			{
				((ConfigurationElement)this)["distributedTransactionManagerName"] = value;
			}
		}
	}
	public class MachineSettingsSection : ConfigurationSection
	{
		[TimeSpanValidator(MinValueString = "00:00:00", MaxValueString = "10675199.02:48:05.4775807")]
		[ConfigurationProperty("maxTimeout", DefaultValue = "00:10:00")]
		public TimeSpan MaxTimeout
		{
			get
			{
				return (TimeSpan)((ConfigurationElement)this)["maxTimeout"];
			}
			set
			{
				((ConfigurationElement)this)["maxTimeout"] = value;
			}
		}
	}
	public class TransactionsSectionGroup : ConfigurationSectionGroup
	{
		[ConfigurationProperty("defaultSettings")]
		public DefaultSettingsSection DefaultSettings => (DefaultSettingsSection)(object)((ConfigurationSectionGroup)this).Sections["defaultSettings"];

		[ConfigurationProperty("machineSettings")]
		public MachineSettingsSection MachineSettings => (MachineSettingsSection)(object)((ConfigurationSectionGroup)this).Sections["machineSettings"];

		public static TransactionsSectionGroup GetSectionGroup(Configuration config)
		{
			if (config == null)
			{
				throw new ArgumentNullException("config");
			}
			return config.GetSectionGroup("system.transactions") as TransactionsSectionGroup;
		}
	}
}
namespace System.Transactions
{
	[Serializable]
	public sealed class DistributedTransactionPermission : CodeAccessPermission, IUnrestrictedPermission
	{
		public DistributedTransactionPermission(PermissionState state)
		{
			ThrowStub.ThrowNotSupportedException();
		}

		public override IPermission Copy()
		{
			ThrowStub.ThrowNotSupportedException();
			return null;
		}

		public override void FromXml(SecurityElement securityElement)
		{
			ThrowStub.ThrowNotSupportedException();
		}

		public override IPermission Intersect(IPermission target)
		{
			ThrowStub.ThrowNotSupportedException();
			return null;
		}

		public override bool IsSubsetOf(IPermission target)
		{
			ThrowStub.ThrowNotSupportedException();
			return default(bool);
		}

		public bool IsUnrestricted()
		{
			ThrowStub.ThrowNotSupportedException();
			return default(bool);
		}

		public override SecurityElement ToXml()
		{
			ThrowStub.ThrowNotSupportedException();
			return null;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	public sealed class DistributedTransactionPermissionAttribute : CodeAccessSecurityAttribute
	{
		public DistributedTransactionPermissionAttribute(SecurityAction action)
		{
		}

		public override IPermission CreatePermission()
		{
			ThrowStub.ThrowNotSupportedException();
			return null;
		}
	}
}
namespace Unity
{
	internal sealed class ThrowStub : ObjectDisposedException
	{
		public static void ThrowNotSupportedException()
		{
			throw new PlatformNotSupportedException();
		}
	}
}

BepInEx/core/System.Windows.Forms.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Forms.Automation;
using System.Windows.Forms.CarbonInternal;
using System.Windows.Forms.ComponentModel.Com2Interop;
using System.Windows.Forms.Design;
using System.Windows.Forms.Layout;
using System.Windows.Forms.PropertyGridInternal;
using System.Windows.Forms.RTF;
using System.Windows.Forms.Theming;
using System.Windows.Forms.Theming.Default;
using System.Windows.Forms.Theming.VisualStyles;
using System.Windows.Forms.VisualStyles;
using System.Windows.Forms.WebBrowserDialogs;
using System.Xml;
using Accessibility;
using Microsoft.Win32;
using Mono.Unix;
using Mono.Unix.Native;
using Mono.WebBrowser;
using Mono.WebBrowser.DOM;
using Unity;

[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Windows.Forms.dll")]
[assembly: AssemblyDescription("System.Windows.Forms.dll")]
[assembly: AssemblyDefaultAlias("System.Windows.Forms.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: CLSCompliant(true)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: Dependency("System.Drawing,", LoadHint.Always)]
[assembly: Dependency("System,", LoadHint.Always)]
[assembly: StringFreezing]
[assembly: ComCompatibleVersion(1, 0, 3300, 0)]
[assembly: InternalsVisibleTo("UIAutomationWinforms, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
[assembly: InternalsVisibleTo("Mono.WinformsSupport, PublicKey=00240000048000009400000006020000002400005253413100040000110000004bb98b1af6c1df0df8c02c380e116b7a7f0c8c827aecfccddc6e29b7c754cd608b49dfcef4df9699ad182e50f66afa4e68dabc7b6aeeec0aa4719a5f8e0aae8c193080a706adc3443a8356b1f254142034995532ac176398e12a30f6a74a119a89ac47672c9ae24d7e90de686557166e3b873cd707884431a0451d9d6f7fe795")]
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("CocoaDriver, PublicKey=0024000004800000940000000602000000240000525341310004000001000100dfb6f531e52a405fce7bb127fdff8b462a29426618ae319093a6479dbc037c76ce025581c272d47806d3c4c9a65304b7ddacff806e6c7e6483f985a5ac39498190c87b7ddb13d3e9c7107f0ceef392ce3fd01391fd9f61199449fd8702ab0d9c2d32dee637bc557ecc7f75c85b350d0d80d8efdb5bdaa6ecaddae0a23a1eb8db")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
namespace System
{
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoTODOAttribute : Attribute
	{
		private string comment;

		public string Comment => comment;

		public MonoTODOAttribute()
		{
		}

		public MonoTODOAttribute(string comment)
		{
			this.comment = comment;
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoDocumentationNoteAttribute : MonoTODOAttribute
	{
		public MonoDocumentationNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoExtensionAttribute : MonoTODOAttribute
	{
		public MonoExtensionAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoInternalNoteAttribute : MonoTODOAttribute
	{
		public MonoInternalNoteAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoLimitationAttribute : MonoTODOAttribute
	{
		public MonoLimitationAttribute(string comment)
			: base(comment)
		{
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	internal class MonoNotSupportedAttribute : MonoTODOAttribute
	{
		public MonoNotSupportedAttribute(string comment)
			: base(comment)
		{
		}
	}
	internal static class MonoToolsLocator
	{
		public static readonly string Mono;

		public static readonly string McsCSharpCompiler;

		public static readonly string VBCompiler;

		public static readonly string AssemblyLinker;

		static MonoToolsLocator()
		{
			string directoryName = Path.GetDirectoryName((string)typeof(Environment).GetProperty("GacPath", BindingFlags.Static | BindingFlags.NonPublic).GetGetMethod(nonPublic: true).Invoke(null, null));
			if (Path.DirectorySeparatorChar == '\\')
			{
				StringBuilder stringBuilder = new StringBuilder(1024);
				GetModuleFileName(IntPtr.Zero, stringBuilder, stringBuilder.Capacity);
				string text = stringBuilder.ToString();
				string fileName = Path.GetFileName(text);
				if (fileName.StartsWith("mono") && fileName.EndsWith(".exe"))
				{
					Mono = text;
				}
				if (!File.Exists(Mono))
				{
					Mono = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(directoryName)), "bin\\mono.exe");
				}
				if (!File.Exists(Mono))
				{
					Mono = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(directoryName))), "mono\\mini\\mono.exe");
				}
				McsCSharpCompiler = Path.Combine(directoryName, "4.5", "mcs.exe");
				if (!File.Exists(McsCSharpCompiler))
				{
					McsCSharpCompiler = Path.Combine(Path.GetDirectoryName(directoryName), "lib", "net_4_x", "mcs.exe");
				}
				VBCompiler = Path.Combine(directoryName, "4.5\\vbnc.exe");
				AssemblyLinker = Path.Combine(directoryName, "4.5\\al.exe");
				if (!File.Exists(AssemblyLinker))
				{
					AssemblyLinker = Path.Combine(Path.GetDirectoryName(directoryName), "lib\\net_4_x\\al.exe");
				}
				return;
			}
			Mono = Path.Combine(directoryName, "bin", "mono");
			if (!File.Exists(Mono))
			{
				Mono = "mono";
			}
			string localPath = new Uri(typeof(object).Assembly.CodeBase).LocalPath;
			McsCSharpCompiler = Path.GetFullPath(Path.Combine(localPath, "..", "..", "..", "..", "bin", "mcs"));
			if (!File.Exists(McsCSharpCompiler))
			{
				McsCSharpCompiler = "mcs";
			}
			VBCompiler = Path.GetFullPath(Path.Combine(localPath, "..", "..", "..", "..", "bin", "vbnc"));
			if (!File.Exists(VBCompiler))
			{
				VBCompiler = "vbnc";
			}
			AssemblyLinker = Path.GetFullPath(Path.Combine(localPath, "..", "..", "..", "..", "bin", "al"));
			if (!File.Exists(AssemblyLinker))
			{
				AssemblyLinker = "al";
			}
		}

		[DllImport("kernel32.dll")]
		private static extern uint GetModuleFileName([In] IntPtr hModule, [Out] StringBuilder lpFilename, [In] int nSize);
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
	internal sealed class MWFCategoryAttribute : CategoryAttribute
	{
		public MWFCategoryAttribute()
		{
		}

		public MWFCategoryAttribute(string category)
			: base(category)
		{
		}

		protected override string GetLocalizedString(string value)
		{
			return Locale.GetText(value);
		}
	}
	[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
	internal sealed class MWFDescriptionAttribute : DescriptionAttribute
	{
		public override string Description => Locale.GetText(base.Description);

		public MWFDescriptionAttribute()
		{
		}

		public MWFDescriptionAttribute(string category)
			: base(category)
		{
		}
	}
}
namespace System.Resources
{
	internal sealed class AssemblyNamesTypeResolutionService : ITypeResolutionService
	{
		public AssemblyNamesTypeResolutionService(AssemblyName[] names)
		{
		}

		public Assembly GetAssembly(AssemblyName name)
		{
			return GetAssembly(name, throwOnError: true);
		}

		public Assembly GetAssembly(AssemblyName name, bool throwOnError)
		{
			throw new NotImplementedException();
		}

		public Type GetType(string name)
		{
			return GetType(name, throwOnError: true);
		}

		public Type GetType(string name, bool throwOnError)
		{
			return GetType(name, throwOnError, ignoreCase: false);
		}

		public Type GetType(string name, bool throwOnError, bool ignoreCase)
		{
			Type? type = Type.GetType(name, throwOnError: false, ignoreCase);
			if (type == null && throwOnError)
			{
				throw new ArgumentException($"Could not find a type for a name. The type name was `{name}'");
			}
			return type;
		}

		public void ReferenceAssembly(AssemblyName name)
		{
			throw new NotImplementedException();
		}

		public string GetPathOfAssembly(AssemblyName name)
		{
			throw new NotImplementedException();
		}
	}
	internal class ByteArrayFromResXHandler : ResXDataNodeHandler, IWritableHandler
	{
		private string dataString;

		public string DataString => dataString;

		public ByteArrayFromResXHandler(string data)
		{
			dataString = data;
		}

		public override object GetValue(ITypeResolutionService typeResolver)
		{
			return Convert.FromBase64String(dataString);
		}

		public override object GetValue(AssemblyName[] assemblyNames)
		{
			return Convert.FromBase64String(dataString);
		}

		public override string GetValueTypeName(ITypeResolutionService typeResolver)
		{
			return ResolveType(typeof(byte[]).AssemblyQualifiedName, typeResolver).AssemblyQualifiedName;
		}

		public override string GetValueTypeName(AssemblyName[] assemblyNames)
		{
			return typeof(byte[]).AssemblyQualifiedName;
		}
	}
	internal class FileRefHandler : ResXDataNodeHandler
	{
		private ResXFileRef resXFileRef;

		public FileRefHandler(ResXFileRef fileRef)
		{
			resXFileRef = fileRef;
		}

		public override object GetValue(ITypeResolutionService typeResolver)
		{
			return GetValue();
		}

		public override object GetValue(AssemblyName[] assemblyNames)
		{
			return GetValue();
		}

		public override string GetValueTypeName(ITypeResolutionService typeResolver)
		{
			Type type = ResolveType(resXFileRef.TypeName, typeResolver);
			if (type == null)
			{
				return resXFileRef.TypeName;
			}
			return type.AssemblyQualifiedName;
		}

		public override string GetValueTypeName(AssemblyName[] assemblyNames)
		{
			Type type = ResolveType(resXFileRef.TypeName, assemblyNames);
			if (type == null)
			{
				return resXFileRef.TypeName;
			}
			return type.AssemblyQualifiedName;
		}

		private object GetValue()
		{
			TypeConverter converter = TypeDescriptor.GetConverter(typeof(ResXFileRef));
			try
			{
				return converter.ConvertFromInvariantString(resXFileRef.ToString());
			}
			catch (ArgumentNullException ex)
			{
				if (ex.ParamName == "type")
				{
					throw new TypeLoadException("Could not find type", ex);
				}
				throw ex;
			}
		}
	}
	internal class InMemoryHandler : ResXDataNodeHandler
	{
		private object value;

		public InMemoryHandler(object valueObject)
		{
			value = valueObject;
		}

		public override object GetValue(ITypeResolutionService typeResolver)
		{
			return value;
		}

		public override object GetValue(AssemblyName[] assemblyNames)
		{
			return value;
		}

		public override string GetValueTypeName(ITypeResolutionService typeResolver)
		{
			if (value == null)
			{
				return null;
			}
			return value.GetType().AssemblyQualifiedName;
		}

		public override string GetValueTypeName(AssemblyName[] assemblyNames)
		{
			if (value == null)
			{
				return null;
			}
			return value.GetType().AssemblyQualifiedName;
		}
	}
	internal class NullRefHandler : ResXDataNodeHandler, IWritableHandler
	{
		private string dataString;

		public string DataString => dataString;

		public NullRefHandler(string _dataString)
		{
			dataString = _dataString;
		}

		public override object GetValue(ITypeResolutionService typeResolver)
		{
			return null;
		}

		public override object GetValue(AssemblyName[] assemblyNames)
		{
			return null;
		}

		public override string GetValueTypeName(ITypeResolutionService typeResolver)
		{
			return typeof(object).AssemblyQualifiedName;
		}

		public override string GetValueTypeName(AssemblyName[] assemblyNames)
		{
			return typeof(object).AssemblyQualifiedName;
		}
	}
	[Serializable]
	public sealed class ResXDataNode : ISerializable
	{
		private string name;

		private ResXFileRef fileRef;

		private string comment;

		private Point pos;

		internal ResXDataNodeHandler handler;

		public string Comment
		{
			get
			{
				return comment ?? string.Empty;
			}
			set
			{
				comment = value;
			}
		}

		public ResXFileRef FileRef => fileRef;

		public string Name
		{
			get
			{
				return name ?? string.Empty;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("name");
				}
				if (value == string.Empty)
				{
					throw new ArgumentException("name");
				}
				name = value;
			}
		}

		internal bool IsWritable => handler is IWritableHandler;

		internal string MimeType { get; set; }

		internal string Type { get; set; }

		internal string DataString
		{
			get
			{
				if (IsWritable)
				{
					return ((IWritableHandler)handler).DataString;
				}
				throw new NotSupportedException("Node Not Writable");
			}
		}

		public ResXDataNode(string name, object value)
			: this(name, value, Point.Empty)
		{
		}

		public ResXDataNode(string name, ResXFileRef fileRef)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (fileRef == null)
			{
				throw new ArgumentNullException("fileRef");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException("name");
			}
			this.name = name;
			this.fileRef = fileRef;
			pos = Point.Empty;
			handler = new FileRefHandler(fileRef);
		}

		internal ResXDataNode(string name, object value, Point position)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (name.Length == 0)
			{
				throw new ArgumentException("name");
			}
			Type type = ((value == null) ? typeof(object) : value.GetType());
			if (value != null && !type.IsSerializable)
			{
				throw new InvalidOperationException($"'{name}' of type '{type}' cannot be added because it is not serializable");
			}
			this.name = name;
			pos = position;
			handler = new InMemoryHandler(value);
		}

		internal ResXDataNode(string nameAtt, string mimeTypeAtt, string typeAtt, string dataString, string commentString, Point position, string basePath)
		{
			name = nameAtt;
			comment = commentString;
			pos = position;
			MimeType = mimeTypeAtt;
			Type = typeAtt;
			if (!string.IsNullOrEmpty(mimeTypeAtt))
			{
				if (!string.IsNullOrEmpty(typeAtt))
				{
					handler = new TypeConverterFromResXHandler(dataString, mimeTypeAtt, typeAtt);
				}
				else
				{
					handler = new SerializedFromResXHandler(dataString, mimeTypeAtt);
				}
			}
			else if (!string.IsNullOrEmpty(typeAtt))
			{
				if (typeAtt.StartsWith("System.Resources.ResXNullRef, System.Windows.Forms"))
				{
					handler = new NullRefHandler(typeAtt);
				}
				else if (typeAtt.StartsWith("System.Byte[], mscorlib"))
				{
					handler = new ByteArrayFromResXHandler(dataString);
				}
				else if (typeAtt.StartsWith("System.Resources.ResXFileRef, System.Windows.Forms"))
				{
					ResXFileRef resXFileRef = BuildFileRef(dataString, basePath);
					handler = new FileRefHandler(resXFileRef);
					fileRef = resXFileRef;
				}
				else
				{
					handler = new TypeConverterFromResXHandler(dataString, mimeTypeAtt, typeAtt);
				}
			}
			else
			{
				handler = new InMemoryHandler(dataString);
			}
			if (handler == null)
			{
				throw new Exception("handler is null");
			}
		}

		public Point GetNodePosition()
		{
			return pos;
		}

		public string GetValueTypeName(AssemblyName[] names)
		{
			return handler.GetValueTypeName(names);
		}

		public string GetValueTypeName(ITypeResolutionService typeResolver)
		{
			return handler.GetValueTypeName(typeResolver);
		}

		public object GetValue(AssemblyName[] names)
		{
			return handler.GetValue(names);
		}

		public object GetValue(ITypeResolutionService typeResolver)
		{
			return handler.GetValue(typeResolver);
		}

		private ResXFileRef BuildFileRef(string dataString, string basePath)
		{
			string[] array = ResXFileRef.Parse(dataString);
			if (array.Length < 2)
			{
				throw new ArgumentException("ResXFileRef cannot be generated");
			}
			string fileName = array[0];
			if (basePath != null)
			{
				fileName = Path.Combine(basePath, array[0]);
			}
			string typeName = array[1];
			if (array.Length == 3)
			{
				Encoding encoding = Encoding.GetEncoding(array[2]);
				return new ResXFileRef(fileName, typeName, encoding);
			}
			return new ResXFileRef(fileName, typeName);
		}

		void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context)
		{
			si.AddValue("Name", Name);
			si.AddValue("Comment", Comment);
		}

		public ResXDataNode(string name, object value, Func<Type, string> typeNameConverter)
		{
			ThrowStub.ThrowNotSupportedException();
		}

		public ResXDataNode(string name, ResXFileRef fileRef, Func<Type, string> typeNameConverter)
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	internal interface IWritableHandler
	{
		string DataString { get; }
	}
	internal abstract class ResXDataNodeHandler
	{
		public abstract object GetValue(ITypeResolutionService typeResolver);

		public abstract object GetValue(AssemblyName[] assemblyNames);

		public abstract string GetValueTypeName(ITypeResolutionService typeResolver);

		public abstract string GetValueTypeName(AssemblyName[] assemblyNames);

		public virtual object GetValueForResX()
		{
			return GetValue((AssemblyName[])null);
		}

		protected Type ResolveType(string typeString)
		{
			return Type.GetType(typeString);
		}

		protected Type ResolveType(string typeString, AssemblyName[] assemblyNames)
		{
			Type type = null;
			if (assemblyNames != null)
			{
				for (int i = 0; i < assemblyNames.Length; i++)
				{
					type = Assembly.Load(assemblyNames[i]).GetType(typeString, throwOnError: false);
					if (type != null)
					{
						return type;
					}
				}
			}
			if (type == null)
			{
				type = ResolveType(typeString);
			}
			return type;
		}

		protected Type ResolveType(string typeString, ITypeResolutionService typeResolver)
		{
			Type type = null;
			if (typeResolver != null)
			{
				type = typeResolver.GetType(typeString);
			}
			if (type == null)
			{
				type = ResolveType(typeString);
			}
			return type;
		}
	}
	[Serializable]
	[TypeConverter(typeof(Converter))]
	public class ResXFileRef
	{
		public class Converter : TypeConverter
		{
			public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
			{
				return sourceType == typeof(string);
			}

			public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
			{
				return destinationType == typeof(string);
			}

			public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
			{
				//IL_0114: Unknown result type (might be due to invalid IL or missing references)
				if (!(value is string))
				{
					return null;
				}
				string[] array = Parse((string)value);
				if (array.Length == 1)
				{
					throw new ArgumentException("value");
				}
				string text = array[0];
				if (Path.DirectorySeparatorChar == '/')
				{
					text = text.Replace("\\", "/");
				}
				Type type = Type.GetType(array[1]);
				if (type == typeof(string))
				{
					Encoding encoding = ((array.Length <= 2) ? Encoding.Default : Encoding.GetEncoding(array[2]));
					using TextReader textReader = new StreamReader(text, encoding);
					return textReader.ReadToEnd();
				}
				byte[] array2;
				using (FileStream fileStream = new FileStream(text, FileMode.Open, FileAccess.Read, FileShare.Read))
				{
					array2 = new byte[fileStream.Length];
					fileStream.Read(array2, 0, (int)fileStream.Length);
				}
				if (type == typeof(byte[]))
				{
					return array2;
				}
				if (type == typeof(Bitmap) && Path.GetExtension(text) == ".ico")
				{
					return new Icon((Stream)new MemoryStream(array2)).ToBitmap();
				}
				if (type == typeof(MemoryStream))
				{
					return new MemoryStream(array2);
				}
				return Activator.CreateInstance(type, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance, null, new object[1]
				{
					new MemoryStream(array2)
				}, culture);
			}

			public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
			{
				if (destinationType != typeof(string))
				{
					return base.ConvertTo(context, culture, value, destinationType);
				}
				return ((ResXFileRef)value).ToString();
			}
		}

		private string filename;

		private string typename;

		private Encoding textFileEncoding;

		public string FileName => filename;

		public Encoding TextFileEncoding => textFileEncoding;

		public string TypeName => typename;

		public ResXFileRef(string fileName, string typeName)
		{
			if (fileName == null)
			{
				throw new ArgumentNullException("fileName");
			}
			if (typeName == null)
			{
				throw new ArgumentNullException("typeName");
			}
			filename = fileName;
			typename = typeName;
		}

		public ResXFileRef(string fileName, string typeName, Encoding textFileEncoding)
			: this(fileName, typeName)
		{
			this.textFileEncoding = textFileEncoding;
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			if (filename != null)
			{
				stringBuilder.Append(filename);
			}
			stringBuilder.Append(';');
			if (typename != null)
			{
				stringBuilder.Append(typename);
			}
			if (textFileEncoding != null)
			{
				stringBuilder.Append(';');
				stringBuilder.Append(textFileEncoding.WebName);
			}
			return stringBuilder.ToString();
		}

		internal static string[] Parse(string fileRef)
		{
			if (fileRef == null)
			{
				throw new ArgumentNullException("fileRef");
			}
			return fileRef.Split(';');
		}
	}
	[Serializable]
	internal class ResXNullRef
	{
	}
	public class ResXResourceReader : IResourceReader, IEnumerable, IDisposable
	{
		private class ResXHeader
		{
			private string resMimeType;

			private string reader;

			private string version;

			private string writer;

			public string ResMimeType
			{
				get
				{
					return resMimeType;
				}
				set
				{
					resMimeType = value;
				}
			}

			public string Reader
			{
				get
				{
					return reader;
				}
				set
				{
					reader = value;
				}
			}

			public string Version
			{
				get
				{
					return version;
				}
				set
				{
					version = value;
				}
			}

			public string Writer
			{
				get
				{
					return writer;
				}
				set
				{
					writer = value;
				}
			}

			public bool IsValid
			{
				get
				{
					if (string.Compare(ResMimeType, ResXResourceWriter.ResMimeType) != 0)
					{
						return false;
					}
					if (Reader == null || Writer == null)
					{
						return false;
					}
					if (Reader.Split(',')[0].Trim() != typeof(ResXResourceReader).FullName)
					{
						return false;
					}
					if (Writer.Split(',')[0].Trim() != typeof(ResXResourceWriter).FullName)
					{
						return false;
					}
					return true;
				}
			}

			public void Verify()
			{
				if (!IsValid)
				{
					throw new ArgumentException("Invalid ResX input.  Could not find valid \"resheader\" tags for the ResX reader & writer type names.");
				}
			}
		}

		private string fileName;

		private Stream stream;

		private TextReader reader;

		private OrderedDictionary hasht;

		private ITypeResolutionService typeresolver;

		private XmlTextReader xmlReader;

		private string basepath;

		private bool useResXDataNodes;

		private AssemblyName[] assemblyNames;

		private OrderedDictionary hashtm;

		public string BasePath
		{
			get
			{
				return basepath;
			}
			set
			{
				basepath = value;
			}
		}

		public bool UseResXDataNodes
		{
			get
			{
				return useResXDataNodes;
			}
			set
			{
				if (xmlReader != null)
				{
					throw new InvalidOperationException();
				}
				useResXDataNodes = value;
			}
		}

		public ResXResourceReader(Stream stream)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			if (!stream.CanRead)
			{
				throw new ArgumentException("Stream was not readable.");
			}
			this.stream = stream;
		}

		public ResXResourceReader(Stream stream, ITypeResolutionService typeResolver)
			: this(stream)
		{
			typeresolver = typeResolver;
		}

		public ResXResourceReader(string fileName)
		{
			this.fileName = fileName;
		}

		public ResXResourceReader(string fileName, ITypeResolutionService typeResolver)
			: this(fileName)
		{
			typeresolver = typeResolver;
		}

		public ResXResourceReader(TextReader reader)
		{
			this.reader = reader;
		}

		public ResXResourceReader(TextReader reader, ITypeResolutionService typeResolver)
			: this(reader)
		{
			typeresolver = typeResolver;
		}

		public ResXResourceReader(Stream stream, AssemblyName[] assemblyNames)
			: this(stream)
		{
			this.assemblyNames = assemblyNames;
		}

		public ResXResourceReader(string fileName, AssemblyName[] assemblyNames)
			: this(fileName)
		{
			this.assemblyNames = assemblyNames;
		}

		public ResXResourceReader(TextReader reader, AssemblyName[] assemblyNames)
			: this(reader)
		{
			this.assemblyNames = assemblyNames;
		}

		~ResXResourceReader()
		{
			Dispose(disposing: false);
		}

		private void LoadData()
		{
			hasht = new OrderedDictionary();
			hashtm = new OrderedDictionary();
			if (fileName != null)
			{
				stream = File.OpenRead(fileName);
			}
			try
			{
				xmlReader = null;
				if (stream != null)
				{
					xmlReader = new XmlTextReader(stream);
				}
				else if (reader != null)
				{
					xmlReader = new XmlTextReader(reader);
				}
				if (xmlReader == null)
				{
					throw new InvalidOperationException("ResourceReader is closed.");
				}
				xmlReader.WhitespaceHandling = WhitespaceHandling.None;
				ResXHeader resXHeader = new ResXHeader();
				try
				{
					while (xmlReader.Read())
					{
						if (xmlReader.NodeType == XmlNodeType.Element)
						{
							switch (xmlReader.LocalName)
							{
							case "resheader":
								ParseHeaderNode(resXHeader);
								break;
							case "data":
								ParseDataNode(meta: false);
								break;
							case "metadata":
								ParseDataNode(meta: true);
								break;
							}
						}
					}
				}
				catch (XmlException innerException)
				{
					throw new ArgumentException("Invalid ResX input.", innerException);
				}
				catch (SerializationException ex)
				{
					throw ex;
				}
				catch (TargetInvocationException ex2)
				{
					throw ex2;
				}
				catch (Exception ex3)
				{
					XmlException innerException2 = new XmlException(ex3.Message, ex3, xmlReader.LineNumber, xmlReader.LinePosition);
					throw new ArgumentException("Invalid ResX input.", innerException2);
				}
				resXHeader.Verify();
			}
			finally
			{
				if (fileName != null)
				{
					stream.Close();
					stream = null;
				}
				xmlReader = null;
			}
		}

		private void ParseHeaderNode(ResXHeader header)
		{
			string attribute = GetAttribute("name");
			if (attribute != null)
			{
				if (string.Compare(attribute, "resmimetype", ignoreCase: true) == 0)
				{
					header.ResMimeType = GetHeaderValue();
				}
				else if (string.Compare(attribute, "reader", ignoreCase: true) == 0)
				{
					header.Reader = GetHeaderValue();
				}
				else if (string.Compare(attribute, "version", ignoreCase: true) == 0)
				{
					header.Version = GetHeaderValue();
				}
				else if (string.Compare(attribute, "writer", ignoreCase: true) == 0)
				{
					header.Writer = GetHeaderValue();
				}
			}
		}

		private string GetHeaderValue()
		{
			string text = null;
			xmlReader.ReadStartElement();
			if (xmlReader.NodeType == XmlNodeType.Element)
			{
				return xmlReader.ReadElementString();
			}
			return xmlReader.Value.Trim();
		}

		private string GetAttribute(string name)
		{
			if (!xmlReader.HasAttributes)
			{
				return null;
			}
			for (int i = 0; i < xmlReader.AttributeCount; i++)
			{
				xmlReader.MoveToAttribute(i);
				if (string.Compare(xmlReader.Name, name, ignoreCase: true) == 0)
				{
					string value = xmlReader.Value;
					xmlReader.MoveToElement();
					return value;
				}
			}
			xmlReader.MoveToElement();
			return null;
		}

		private string GetDataValue(bool meta, out string comment)
		{
			string result = null;
			comment = null;
			while (xmlReader.Read() && (xmlReader.NodeType != XmlNodeType.EndElement || !(xmlReader.LocalName == (meta ? "metadata" : "data"))))
			{
				if (xmlReader.NodeType == XmlNodeType.Element)
				{
					if (xmlReader.Name.Equals("value"))
					{
						xmlReader.WhitespaceHandling = WhitespaceHandling.Significant;
						result = xmlReader.ReadString();
						xmlReader.WhitespaceHandling = WhitespaceHandling.None;
					}
					else if (xmlReader.Name.Equals("comment"))
					{
						xmlReader.WhitespaceHandling = WhitespaceHandling.Significant;
						comment = xmlReader.ReadString();
						xmlReader.WhitespaceHandling = WhitespaceHandling.None;
						if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.LocalName == (meta ? "metadata" : "data"))
						{
							break;
						}
					}
				}
				else
				{
					result = xmlReader.Value.Trim();
				}
			}
			return result;
		}

		private void ParseDataNode(bool meta)
		{
			OrderedDictionary orderedDictionary = ((meta && !useResXDataNodes) ? hashtm : hasht);
			Point position = new Point(xmlReader.LineNumber, xmlReader.LinePosition);
			string attribute = GetAttribute("name");
			string attribute2 = GetAttribute("type");
			string attribute3 = GetAttribute("mimetype");
			string comment = null;
			string dataValue = GetDataValue(meta, out comment);
			ResXDataNode resXDataNode = new ResXDataNode(attribute, attribute3, attribute2, dataValue, comment, position, BasePath);
			if (useResXDataNodes)
			{
				orderedDictionary[attribute] = resXDataNode;
				return;
			}
			if (attribute == null)
			{
				throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Could not find a name for a resource. The resource value was '{0}'.", resXDataNode.GetValue((AssemblyName[])null).ToString()));
			}
			if (assemblyNames != null)
			{
				try
				{
					orderedDictionary[attribute] = resXDataNode.GetValue(assemblyNames);
					return;
				}
				catch (TypeLoadException ex)
				{
					if (resXDataNode.handler is TypeConverterFromResXHandler)
					{
						orderedDictionary[attribute] = null;
						return;
					}
					throw ex;
				}
			}
			try
			{
				orderedDictionary[attribute] = resXDataNode.GetValue(typeresolver);
			}
			catch (TypeLoadException ex2)
			{
				if (resXDataNode.handler is TypeConverterFromResXHandler)
				{
					orderedDictionary[attribute] = null;
					return;
				}
				throw ex2;
			}
		}

		public void Close()
		{
			if (reader != null)
			{
				reader.Close();
				reader = null;
			}
		}

		public IDictionaryEnumerator GetEnumerator()
		{
			if (hasht == null)
			{
				LoadData();
			}
			return hasht.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return ((IResourceReader)this).GetEnumerator();
		}

		void IDisposable.Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				Close();
			}
		}

		public static ResXResourceReader FromFileContents(string fileContents)
		{
			return new ResXResourceReader(new StringReader(fileContents));
		}

		public static ResXResourceReader FromFileContents(string fileContents, ITypeResolutionService typeResolver)
		{
			return new ResXResourceReader(new StringReader(fileContents), typeResolver);
		}

		public static ResXResourceReader FromFileContents(string fileContents, AssemblyName[] assemblyNames)
		{
			return new ResXResourceReader(new StringReader(fileContents), assemblyNames);
		}

		public IDictionaryEnumerator GetMetadataEnumerator()
		{
			if (hashtm == null)
			{
				LoadData();
			}
			return hashtm.GetEnumerator();
		}
	}
	public class ResXResourceSet : ResourceSet
	{
		public ResXResourceSet(Stream stream)
		{
			Reader = new ResXResourceReader(stream);
			base.Table = new Hashtable();
			ReadResources();
		}

		public ResXResourceSet(string fileName)
		{
			Reader = new ResXResourceReader(fileName);
			base.Table = new Hashtable();
			ReadResources();
		}

		public override Type GetDefaultReader()
		{
			return typeof(ResXResourceReader);
		}

		public override Type GetDefaultWriter()
		{
			return typeof(ResXResourceWriter);
		}
	}
	public class ResXResourceWriter : IResourceWriter, IDisposable
	{
		private string filename;

		private Stream stream;

		private TextWriter textwriter;

		private XmlTextWriter writer;

		private bool written;

		private string base_path;

		public static readonly string BinSerializedObjectMimeType = "application/x-microsoft.net.object.binary.base64";

		public static readonly string ByteArraySerializedObjectMimeType = "application/x-microsoft.net.object.bytearray.base64";

		public static readonly string DefaultSerializedObjectMimeType = BinSerializedObjectMimeType;

		public static readonly string ResMimeType = "text/microsoft-resx";

		public static readonly string ResourceSchema = schema;

		public static readonly string SoapSerializedObjectMimeType = "application/x-microsoft.net.object.soap.base64";

		public static readonly string Version = "2.0";

		private static string schema = "\n  <xsd:schema id='root' xmlns='' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'>\n    <xsd:element name='root' msdata:IsDataSet='true'>\n      <xsd:complexType>\n        <xsd:choice maxOccurs='unbounded'>\n          <xsd:element name='data'>\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />\n                <xsd:element name='comment' type='xsd:string' minOccurs='0' msdata:Ordinal='2' />\n              </xsd:sequence>\n              <xsd:attribute name='name' type='xsd:string' msdata:Ordinal='1' />\n              <xsd:attribute name='type' type='xsd:string' msdata:Ordinal='3' />\n              <xsd:attribute name='mimetype' type='xsd:string' msdata:Ordinal='4' />\n            </xsd:complexType>\n          </xsd:element>\n          <xsd:element name='resheader'>\n            <xsd:complexType>\n              <xsd:sequence>\n                <xsd:element name='value' type='xsd:string' minOccurs='0' msdata:Ordinal='1' />\n              </xsd:sequence>\n              <xsd:attribute name='name' type='xsd:string' use='required' />\n            </xsd:complexType>\n          </xsd:element>\n        </xsd:choice>\n      </xsd:complexType>\n    </xsd:element>\n  </xsd:schema>\n".Replace("'", "\"");

		public string BasePath
		{
			get
			{
				return base_path;
			}
			set
			{
				base_path = value;
			}
		}

		public ResXResourceWriter(Stream stream)
		{
			if (stream == null)
			{
				throw new ArgumentNullException("stream");
			}
			if (!stream.CanWrite)
			{
				throw new ArgumentException("stream is not writable.", "stream");
			}
			this.stream = stream;
		}

		public ResXResourceWriter(TextWriter textWriter)
		{
			if (textWriter == null)
			{
				throw new ArgumentNullException("textWriter");
			}
			textwriter = textWriter;
		}

		public ResXResourceWriter(string fileName)
		{
			if (fileName == null)
			{
				throw new ArgumentNullException("fileName");
			}
			filename = fileName;
		}

		~ResXResourceWriter()
		{
			Dispose(disposing: false);
		}

		private void InitWriter()
		{
			if (filename != null)
			{
				stream = File.Open(filename, FileMode.Create);
			}
			if (textwriter == null)
			{
				textwriter = new StreamWriter(stream, Encoding.UTF8);
			}
			writer = new XmlTextWriter(textwriter);
			writer.Formatting = Formatting.Indented;
			writer.WriteStartDocument();
			writer.WriteStartElement("root");
			writer.WriteRaw(schema);
			WriteHeader("resmimetype", "text/microsoft-resx");
			WriteHeader("version", "1.3");
			WriteHeader("reader", typeof(ResXResourceReader).AssemblyQualifiedName);
			WriteHeader("writer", typeof(ResXResourceWriter).AssemblyQualifiedName);
		}

		private void WriteHeader(string name, string value)
		{
			writer.WriteStartElement("resheader");
			writer.WriteAttributeString("name", name);
			writer.WriteStartElement("value");
			writer.WriteString(value);
			writer.WriteEndElement();
			writer.WriteEndElement();
		}

		private void WriteNiceBase64(byte[] value, int offset, int length)
		{
			string text = Convert.ToBase64String(value, offset, length);
			StringBuilder stringBuilder = new StringBuilder(text, text.Length + (text.Length + 160) / 80 * 3);
			int i = 0;
			int num = 80 + Environment.NewLine.Length + 1;
			string value2 = Environment.NewLine + "\t";
			for (; i < stringBuilder.Length; i += num)
			{
				stringBuilder.Insert(i, value2);
			}
			stringBuilder.Insert(stringBuilder.Length, Environment.NewLine);
			writer.WriteString(stringBuilder.ToString());
		}

		private void WriteBytes(string name, Type type, byte[] value, int offset, int length)
		{
			WriteBytes(name, type, value, offset, length, string.Empty);
		}

		private void WriteBytes(string name, Type type, byte[] value, int offset, int length, string comment)
		{
			writer.WriteStartElement("data");
			writer.WriteAttributeString("name", name);
			if (type != null)
			{
				writer.WriteAttributeString("type", type.AssemblyQualifiedName);
				if (type != typeof(byte[]))
				{
					writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType);
				}
				writer.WriteStartElement("value");
				WriteNiceBase64(value, offset, length);
			}
			else
			{
				writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType);
				writer.WriteStartElement("value");
				writer.WriteBase64(value, offset, length);
			}
			writer.WriteEndElement();
			if (comment != null && !comment.Equals(string.Empty))
			{
				writer.WriteStartElement("comment");
				writer.WriteString(comment);
				writer.WriteEndElement();
			}
			writer.WriteEndElement();
		}

		private void WriteBytes(string name, Type type, byte[] value, string comment)
		{
			WriteBytes(name, type, value, 0, value.Length, comment);
		}

		private void WriteString(string name, string value)
		{
			WriteString(name, value, null);
		}

		private void WriteString(string name, string value, Type type)
		{
			WriteString(name, value, type, string.Empty);
		}

		private void WriteString(string name, string value, Type type, string comment)
		{
			writer.WriteStartElement("data");
			writer.WriteAttributeString("name", name);
			if (type != null)
			{
				writer.WriteAttributeString("type", type.AssemblyQualifiedName);
			}
			writer.WriteStartElement("value");
			writer.WriteString(value);
			writer.WriteEndElement();
			if (comment != null && !comment.Equals(string.Empty))
			{
				writer.WriteStartElement("comment");
				writer.WriteString(comment);
				writer.WriteEndElement();
			}
			writer.WriteEndElement();
			writer.WriteWhitespace("\n  ");
		}

		public void AddResource(string name, byte[] value)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (written)
			{
				throw new InvalidOperationException("The resource is already generated.");
			}
			if (writer == null)
			{
				InitWriter();
			}
			WriteBytes(name, value.GetType(), value, null);
		}

		public void AddResource(string name, object value)
		{
			AddResource(name, value, string.Empty);
		}

		private void AddResource(string name, object value, string comment)
		{
			if (value is string)
			{
				AddResource(name, (string)value, comment);
				return;
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (value != null && !value.GetType().IsSerializable)
			{
				throw new InvalidOperationException($"The element '{name}' of type '{value.GetType().Name}' is not serializable.");
			}
			if (written)
			{
				throw new InvalidOperationException("The resource is already generated.");
			}
			if (writer == null)
			{
				InitWriter();
			}
			if (value is byte[])
			{
				WriteBytes(name, value.GetType(), (byte[])value, comment);
				return;
			}
			if (value == null)
			{
				WriteString(name, "", typeof(ResXNullRef), comment);
				return;
			}
			TypeConverter converter = TypeDescriptor.GetConverter(value);
			if (value is ResXFileRef)
			{
				ResXFileRef value2 = ProcessFileRefBasePath((ResXFileRef)value);
				string value3 = converter.ConvertToInvariantString(value2);
				WriteString(name, value3, value.GetType(), comment);
				return;
			}
			if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
			{
				string value4 = converter.ConvertToInvariantString(value);
				WriteString(name, value4, value.GetType(), comment);
				return;
			}
			if (converter != null && converter.CanConvertTo(typeof(byte[])) && converter.CanConvertFrom(typeof(byte[])))
			{
				byte[] value5 = (byte[])converter.ConvertTo(value, typeof(byte[]));
				WriteBytes(name, value.GetType(), value5, comment);
				return;
			}
			MemoryStream memoryStream = new MemoryStream();
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			try
			{
				binaryFormatter.Serialize(memoryStream, value);
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException("Cannot add a " + value.GetType()?.ToString() + "because it cannot be serialized: " + ex.Message);
			}
			WriteBytes(name, null, memoryStream.GetBuffer(), 0, (int)memoryStream.Length, comment);
			memoryStream.Close();
		}

		public void AddResource(string name, string value)
		{
			AddResource(name, value, string.Empty);
		}

		private void AddResource(string name, string value, string comment)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (written)
			{
				throw new InvalidOperationException("The resource is already generated.");
			}
			if (writer == null)
			{
				InitWriter();
			}
			WriteString(name, value, null, comment);
		}

		[MonoTODO("Stub, not implemented")]
		public virtual void AddAlias(string aliasName, AssemblyName assemblyName)
		{
		}

		public void AddResource(ResXDataNode node)
		{
			if (node == null)
			{
				throw new ArgumentNullException("node");
			}
			if (writer == null)
			{
				InitWriter();
			}
			if (node.IsWritable)
			{
				WriteWritableNode(node);
			}
			else if (node.FileRef != null)
			{
				AddResource(node.Name, node.FileRef, node.Comment);
			}
			else
			{
				AddResource(node.Name, node.GetValue((AssemblyName[])null), node.Comment);
			}
		}

		private ResXFileRef ProcessFileRefBasePath(ResXFileRef fileRef)
		{
			if (string.IsNullOrEmpty(BasePath))
			{
				return fileRef;
			}
			return new ResXFileRef(AbsoluteToRelativePath(BasePath, fileRef.FileName), fileRef.TypeName, fileRef.TextFileEncoding);
		}

		private static bool IsSeparator(char ch)
		{
			if (ch != Path.DirectorySeparatorChar && ch != Path.AltDirectorySeparatorChar)
			{
				return ch == Path.VolumeSeparatorChar;
			}
			return true;
		}

		private unsafe static string AbsoluteToRelativePath(string baseDirectoryPath, string absPath)
		{
			if (string.IsNullOrEmpty(baseDirectoryPath))
			{
				return absPath;
			}
			baseDirectoryPath = baseDirectoryPath.TrimEnd(Path.DirectorySeparatorChar);
			fixed (char* ptr = baseDirectoryPath)
			{
				fixed (char* ptr3 = absPath)
				{
					char* ptr2 = ptr + baseDirectoryPath.Length;
					char* ptr4 = ptr3 + absPath.Length;
					char* ptr5 = ptr4;
					char* ptr6 = ptr2;
					int num = 0;
					char* ptr7 = ptr3;
					char* ptr8 = ptr;
					while (ptr7 < ptr4 && *ptr7 == *ptr8)
					{
						if (IsSeparator(*ptr7))
						{
							num++;
							ptr5 = ptr7 + 1;
							ptr6 = ptr8;
						}
						ptr7++;
						ptr8++;
						if (ptr8 >= ptr2)
						{
							if (ptr7 >= ptr4 || IsSeparator(*ptr7))
							{
								num++;
								ptr5 = ptr7 + 1;
								ptr6 = ptr8;
							}
							break;
						}
					}
					if (num == 0)
					{
						return absPath;
					}
					if (ptr5 >= ptr4)
					{
						return ".";
					}
					if (ptr7 >= ptr4 && IsSeparator(*ptr8))
					{
						ptr5 = ptr7 + 1;
						ptr6 = ptr8;
					}
					int num2 = 0;
					for (; ptr6 < ptr2; ptr6++)
					{
						if (IsSeparator(*ptr6))
						{
							num2++;
						}
					}
					char[] array = new char[num2 * 2 + num2 + ptr4 - ptr5];
					fixed (char* ptr9 = array)
					{
						char* ptr10 = ptr9;
						for (int i = 0; i < num2; i++)
						{
							*(ptr10++) = '.';
							*(ptr10++) = '.';
							*(ptr10++) = Path.DirectorySeparatorChar;
						}
						while (ptr5 < ptr4)
						{
							*(ptr10++) = *(ptr5++);
						}
					}
					return new string(array);
				}
			}
		}

		private void WriteWritableNode(ResXDataNode node)
		{
			writer.WriteStartElement("data");
			writer.WriteAttributeString("name", node.Name);
			if (node.Type != null && !node.Type.Equals(string.Empty))
			{
				writer.WriteAttributeString("type", node.Type);
			}
			if (node.MimeType != null && !node.MimeType.Equals(string.Empty))
			{
				writer.WriteAttributeString("mimetype", node.MimeType);
			}
			writer.WriteStartElement("value");
			writer.WriteString(node.DataString);
			writer.WriteEndElement();
			if (node.Comment != null && !node.Comment.Equals(string.Empty))
			{
				writer.WriteStartElement("comment");
				writer.WriteString(node.Comment);
				writer.WriteEndElement();
			}
			writer.WriteEndElement();
			writer.WriteWhitespace("\n  ");
		}

		public void AddMetadata(string name, string value)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (written)
			{
				throw new InvalidOperationException("The resource is already generated.");
			}
			if (writer == null)
			{
				InitWriter();
			}
			writer.WriteStartElement("metadata");
			writer.WriteAttributeString("name", name);
			writer.WriteAttributeString("xml:space", "preserve");
			writer.WriteElementString("value", value);
			writer.WriteEndElement();
		}

		public void AddMetadata(string name, byte[] value)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (written)
			{
				throw new InvalidOperationException("The resource is already generated.");
			}
			if (writer == null)
			{
				InitWriter();
			}
			writer.WriteStartElement("metadata");
			writer.WriteAttributeString("name", name);
			writer.WriteAttributeString("type", value.GetType().AssemblyQualifiedName);
			writer.WriteStartElement("value");
			WriteNiceBase64(value, 0, value.Length);
			writer.WriteEndElement();
			writer.WriteEndElement();
		}

		public void AddMetadata(string name, object value)
		{
			if (value is string)
			{
				AddMetadata(name, (string)value);
				return;
			}
			if (value is byte[])
			{
				AddMetadata(name, (byte[])value);
				return;
			}
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			if (!value.GetType().IsSerializable)
			{
				throw new InvalidOperationException($"The element '{name}' of type '{value.GetType().Name}' is not serializable.");
			}
			if (written)
			{
				throw new InvalidOperationException("The resource is already generated.");
			}
			if (writer == null)
			{
				InitWriter();
			}
			Type type = value.GetType();
			TypeConverter converter = TypeDescriptor.GetConverter(value);
			if (converter != null && converter.CanConvertTo(typeof(string)) && converter.CanConvertFrom(typeof(string)))
			{
				string text = converter.ConvertToInvariantString(value);
				writer.WriteStartElement("metadata");
				writer.WriteAttributeString("name", name);
				if (type != null)
				{
					writer.WriteAttributeString("type", type.AssemblyQualifiedName);
				}
				writer.WriteStartElement("value");
				writer.WriteString(text);
				writer.WriteEndElement();
				writer.WriteEndElement();
				writer.WriteWhitespace("\n  ");
				return;
			}
			if (converter != null && converter.CanConvertTo(typeof(byte[])) && converter.CanConvertFrom(typeof(byte[])))
			{
				byte[] array = (byte[])converter.ConvertTo(value, typeof(byte[]));
				writer.WriteStartElement("metadata");
				writer.WriteAttributeString("name", name);
				if (type != null)
				{
					writer.WriteAttributeString("type", type.AssemblyQualifiedName);
					writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType);
					writer.WriteStartElement("value");
					WriteNiceBase64(array, 0, array.Length);
				}
				else
				{
					writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType);
					writer.WriteStartElement("value");
					writer.WriteBase64(array, 0, array.Length);
				}
				writer.WriteEndElement();
				writer.WriteEndElement();
				return;
			}
			MemoryStream memoryStream = new MemoryStream();
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			try
			{
				binaryFormatter.Serialize(memoryStream, value);
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException("Cannot add a " + value.GetType()?.ToString() + "because it cannot be serialized: " + ex.Message);
			}
			writer.WriteStartElement("metadata");
			writer.WriteAttributeString("name", name);
			if (type != null)
			{
				writer.WriteAttributeString("type", type.AssemblyQualifiedName);
				writer.WriteAttributeString("mimetype", ByteArraySerializedObjectMimeType);
				writer.WriteStartElement("value");
				WriteNiceBase64(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length);
			}
			else
			{
				writer.WriteAttributeString("mimetype", BinSerializedObjectMimeType);
				writer.WriteStartElement("value");
				writer.WriteBase64(memoryStream.GetBuffer(), 0, memoryStream.GetBuffer().Length);
			}
			writer.WriteEndElement();
			writer.WriteEndElement();
			memoryStream.Close();
		}

		public void Close()
		{
			if (!written)
			{
				Generate();
			}
			if (writer != null)
			{
				writer.Close();
				stream = null;
				filename = null;
				textwriter = null;
			}
		}

		public virtual void Dispose()
		{
			Dispose(disposing: true);
			GC.SuppressFinalize(this);
		}

		public void Generate()
		{
			if (written)
			{
				throw new InvalidOperationException("The resource is already generated.");
			}
			written = true;
			writer.WriteEndElement();
			writer.Flush();
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				Close();
			}
		}

		public ResXResourceWriter(Stream stream, Func<Type, string> typeNameConverter)
		{
			ThrowStub.ThrowNotSupportedException();
		}

		public ResXResourceWriter(TextWriter textWriter, Func<Type, string> typeNameConverter)
		{
			ThrowStub.ThrowNotSupportedException();
		}

		public ResXResourceWriter(string fileName, Func<Type, string> typeNameConverter)
		{
			ThrowStub.ThrowNotSupportedException();
		}
	}
	internal class SerializedFromResXHandler : ResXDataNodeHandler, IWritableHandler
	{
		private sealed class CustomBinder : SerializationBinder
		{
			private ITypeResolutionService typeResolver;

			public CustomBinder(ITypeResolutionService _typeResolver)
			{
				typeResolver = _typeResolver;
			}

			public override Type BindToType(string assemblyName, string typeName)
			{
				Type type = null;
				string text = $"{typeName}, {assemblyName}";
				if (typeResolver != null)
				{
					type = typeResolver.GetType(text);
				}
				if (type == null)
				{
					type = Type.GetType(text);
				}
				return type;
			}
		}

		private string dataString;

		private string mime_type;

		private CustomBinder binder;

		public string DataString => dataString;

		public SerializedFromResXHandler(string data, string _mime_type)
		{
			dataString = data;
			mime_type = _mime_type;
		}

		public override object GetValue(ITypeResolutionService typeResolver)
		{
			return DeserializeObject(typeResolver);
		}

		public override object GetValue(AssemblyName[] assemblyNames)
		{
			return DeserializeObject(new AssemblyNamesTypeResolutionService(assemblyNames));
		}

		public override string GetValueTypeName(ITypeResolutionService typeResolver)
		{
			return InternalGetValueType(typeResolver);
		}

		public override string GetValueTypeName(AssemblyName[] assemblyNames)
		{
			return InternalGetValueType(null);
		}

		private string InternalGetValueType(ITypeResolutionService typeResolver)
		{
			object obj;
			try
			{
				obj = DeserializeObject(typeResolver);
			}
			catch
			{
				return typeof(object).AssemblyQualifiedName;
			}
			return obj?.GetType().AssemblyQualifiedName;
		}

		private object DeserializeObject(ITypeResolutionService typeResolver)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			try
			{
				if (mime_type == ResXResourceWriter.SoapSerializedObjectMimeType)
				{
					SoapFormatter val = new SoapFormatter();
					if (binder == null)
					{
						binder = new CustomBinder(typeResolver);
					}
					val.Binder = binder;
					using MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(dataString));
					return val.Deserialize((Stream)memoryStream);
				}
				if (mime_type == ResXResourceWriter.BinSerializedObjectMimeType)
				{
					BinaryFormatter binaryFormatter = new BinaryFormatter();
					if (binder == null)
					{
						binder = new CustomBinder(typeResolver);
					}
					binaryFormatter.Binder = binder;
					using MemoryStream serializationStream = new MemoryStream(Convert.FromBase64String(dataString));
					return binaryFormatter.Deserialize(serializationStream);
				}
				return null;
			}
			catch (SerializationException ex)
			{
				if (ex.Message.StartsWith("Couldn't find assembly"))
				{
					throw new ArgumentException(ex.Message);
				}
				throw ex;
			}
		}
	}
	internal class TypeConverterFromResXHandler : ResXDataNodeHandler, IWritableHandler
	{
		private string dataString;

		private string mime_type;

		private string typeString;

		public string DataString => dataString;

		public TypeConverterFromResXHandler(string data, string _mime_type, string _typeString)
		{
			dataString = data;
			mime_type = _mime_type;
			typeString = _typeString;
		}

		public override object GetValue(ITypeResolutionService typeResolver)
		{
			if (!string.IsNullOrEmpty(mime_type) && mime_type != ResXResourceWriter.ByteArraySerializedObjectMimeType)
			{
				return null;
			}
			Type type = ResolveType(typeString, typeResolver);
			if (type == null)
			{
				throw new TypeLoadException();
			}
			TypeConverter converter = TypeDescriptor.GetConverter(type);
			if (converter == null)
			{
				throw new TypeLoadException();
			}
			return ConvertData(converter);
		}

		public override object GetValue(AssemblyName[] assemblyNames)
		{
			if (!string.IsNullOrEmpty(mime_type) && mime_type != ResXResourceWriter.ByteArraySerializedObjectMimeType)
			{
				return null;
			}
			Type type = ResolveType(typeString, assemblyNames);
			if (type == null)
			{
				throw new TypeLoadException();
			}
			TypeConverter converter = TypeDescriptor.GetConverter(type);
			if (converter == null)
			{
				throw new TypeLoadException();
			}
			return ConvertData(converter);
		}

		public override string GetValueTypeName(ITypeResolutionService typeResolver)
		{
			Type type = ResolveType(typeString, typeResolver);
			if (type == null)
			{
				return typeString;
			}
			return type.AssemblyQualifiedName;
		}

		public override string GetValueTypeName(AssemblyName[] assemblyNames)
		{
			Type type = ResolveType(typeString, assemblyNames);
			if (type == null)
			{
				return typeString;
			}
			return type.AssemblyQualifiedName;
		}

		private object ConvertData(TypeConverter c)
		{
			if (mime_type == ResXResourceWriter.ByteArraySerializedObjectMimeType)
			{
				if (c.CanConvertFrom(typeof(byte[])))
				{
					return c.ConvertFrom(Convert.FromBase64String(dataString));
				}
			}
			else
			{
				if (!string.IsNullOrEmpty(mime_type))
				{
					throw new Exception("shouldnt get here, invalid mime type");
				}
				if (c.CanConvertFrom(typeof(string)))
				{
					return c.ConvertFromInvariantString(dataString);
				}
			}
			throw new TypeLoadException("No converter for this type found");
		}
	}
}
namespace System.Windows.Forms
{
	internal static class Locale
	{
		private static ResourceManager rm;

		public static ResourceManager ResourceManager => rm;

		static Locale()
		{
			rm = new ResourceManager("System.Windows.Forms", Assembly.GetExecutingAssembly());
		}

		public static string GetText(string msg)
		{
			string @string = ResourceManager.GetString(msg);
			if (@string != null)
			{
				return @string;
			}
			return msg;
		}

		public static string GetText(string msg, params object[] args)
		{
			return string.Format(GetText(msg), args);
		}
	}
	internal class DebugHelper
	{
		private struct Data
		{
			public MethodBase method;

			public object[] args;

			public Data(MethodBase m, object[] a)
			{
				method = m;
				args = a;
			}
		}

		private static Stack<Data> methods;

		static DebugHelper()
		{
			methods = new Stack<Data>();
			Debug.AutoFlush = true;
		}

		[Conditional("DEBUG")]
		internal static void DumpCallers()
		{
			StackTrace stackTrace = new StackTrace(fNeedFileInfo: true);
			int frameCount = stackTrace.FrameCount;
			for (int i = 1; i < frameCount; i++)
			{
				StackFrame? frame = stackTrace.GetFrame(i);
				frame.GetMethod();
				string fileName = frame.GetFileName();
				if (fileName != null && fileName.Length > 1)
				{
					fileName = fileName.Substring(fileName.LastIndexOf(Path.DirectorySeparatorChar) + 1);
				}
			}
		}

		[Conditional("DEBUG")]
		internal static void DumpCallers(int count)
		{
			StackTrace stackTrace = new StackTrace(fNeedFileInfo: true);
			int num = ((count > stackTrace.FrameCount) ? stackTrace.FrameCount : count);
			for (int i = 1; i < num; i++)
			{
				StackFrame? frame = stackTrace.GetFrame(i);
				frame.GetMethod();
				string fileName = frame.GetFileName();
				if (fileName != null && fileName.Length > 1)
				{
					fileName = fileName.Substring(fileName.LastIndexOf(Path.DirectorySeparatorChar) + 1);
				}
			}
		}

		[Conditional("DEBUG")]
		internal static void Enter()
		{
			StackTrace stackTrace = new StackTrace();
			methods.Push(new Data(stackTrace.GetFrame(1).GetMethod(), null));
		}

		[Conditional("DEBUG")]
		internal static void Enter(object[] args)
		{
			StackTrace stackTrace = new StackTrace();
			methods.Push(new Data(stackTrace.GetFrame(1).GetMethod(), args));
		}

		[Conditional("DEBUG")]
		internal static void Leave()
		{
			if (methods.Count > 0)
			{
				methods.Pop();
			}
		}

		[Conditional("DEBUG")]
		internal static void Print()
		{
			if (methods.Count != 0)
			{
				methods.Peek();
			}
		}

		[Conditional("DEBUG")]
		internal static void Print(int index)
		{
			if (methods.Count != 0 && methods.Count > index && index >= 0)
			{
				Stack<Data> stack = new Stack<Data>(index - 1);
				for (int i = 0; i < index; i++)
				{
					stack.Push(methods.Pop());
				}
				methods.Peek();
				for (int j = 0; j < stack.Count; j++)
				{
					methods.Push(stack.Pop());
				}
				stack = null;
			}
		}

		[Conditional("DEBUG")]
		internal static void Print(string methodName, string parameterName)
		{
			if (methods.Count == 0)
			{
				return;
			}
			Stack<Data> stack = new Stack<Data>();
			Data data = methods.Peek();
			bool flag = false;
			for (int i = 0; i < methods.Count; i++)
			{
				data = methods.Peek();
				if (data.method.Name.Equals(methodName))
				{
					flag = true;
					break;
				}
				stack.Push(methods.Pop());
			}
			for (int j = 0; j < stack.Count; j++)
			{
				methods.Push(stack.Pop());
			}
			stack = null;
			if (!flag)
			{
				return;
			}
			ParameterInfo[] parameters = data.method.GetParameters();
			for (int k = 0; k < parameters.Length; k++)
			{
				if (parameters[k].Name == parameterName)
				{
					_ = parameters[k].ParameterType == typeof(IntPtr);
				}
			}
		}

		[Conditional("DEBUG")]
		internal static void Print(string parameterName)
		{
			if (methods.Count == 0)
			{
				return;
			}
			ParameterInfo[] parameters = methods.Peek().method.GetParameters();
			for (int i = 0; i < parameters.Length; i++)
			{
				if (parameters[i].Name == parameterName)
				{
					_ = parameters[i].ParameterType == typeof(IntPtr);
				}
			}
		}

		[Conditional("DEBUG")]
		internal static void WriteLine(object arg)
		{
		}

		[Conditional("DEBUG")]
		internal static void WriteLine(string format, params object[] arg)
		{
		}

		[Conditional("DEBUG")]
		internal static void WriteLine(string message)
		{
		}

		[Conditional("DEBUG")]
		internal static void Indent()
		{
		}

		[Conditional("DEBUG")]
		internal static void Unindent()
		{
		}

		[Conditional("TRACE")]
		internal static void TraceWriteLine(string format, params object[] arg)
		{
		}

		[Conditional("TRACE")]
		internal static void TraceWriteLine(string message)
		{
		}
	}
	public enum AccessibleEvents
	{
		SystemSound = 1,
		SystemAlert = 2,
		SystemForeground = 3,
		SystemMenuStart = 4,
		SystemMenuEnd = 5,
		SystemMenuPopupStart = 6,
		SystemMenuPopupEnd = 7,
		SystemCaptureStart = 8,
		SystemCaptureEnd = 9,
		SystemMoveSizeStart = 10,
		SystemMoveSizeEnd = 11,
		SystemContextHelpStart = 12,
		SystemContextHelpEnd = 13,
		SystemDragDropStart = 14,
		SystemDragDropEnd = 15,
		SystemDialogStart = 16,
		SystemDialogEnd = 17,
		SystemScrollingStart = 18,
		SystemScrollingEnd = 19,
		SystemSwitchStart = 20,
		SystemSwitchEnd = 21,
		SystemMinimizeStart = 22,
		SystemMinimizeEnd = 23,
		Create = 32768,
		Destroy = 32769,
		Show = 32770,
		Hide = 32771,
		Reorder = 32772,
		Focus = 32773,
		Selection = 32774,
		SelectionAdd = 32775,
		SelectionRemove = 32776,
		SelectionWithin = 32777,
		StateChange = 32778,
		LocationChange = 32779,
		NameChange = 32780,
		DescriptionChange = 32781,
		ValueChange = 32782,
		ParentChange = 32783,
		HelpChange = 32784,
		DefaultActionChange = 32785,
		AcceleratorChange = 32786
	}
	public enum AccessibleNavigation
	{
		Up = 1,
		Down,
		Left,
		Right,
		Next,
		Previous,
		FirstChild,
		LastChild
	}
	[ComVisible(true)]
	public class AccessibleObject : StandardOleMarshalObject, IReflect, IAccessible
	{
		internal string name;

		internal string value;

		internal Control owner;

		internal AccessibleRole role;

		internal AccessibleStates state;

		internal string default_action;

		internal string description;

		internal string help;

		internal string keyboard_shortcut;

		public virtual Rectangle Bounds => owner.Bounds;

		public virtual string DefaultAction => default_action;

		public virtual string Description => description;

		public virtual string Help => help;

		public virtual string KeyboardShortcut => keyboard_shortcut;

		public virtual string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}

		public virtual AccessibleObject Parent
		{
			get
			{
				if (owner != null && owner.Parent != null)
				{
					return owner.Parent.AccessibilityObject;
				}
				return null;
			}
		}

		public virtual AccessibleRole Role => role;

		public virtual AccessibleStates State
		{
			get
			{
				if (owner != null)
				{
					if (owner.Focused)
					{
						state |= AccessibleStates.Focused;
					}
					if (owner.CanFocus)
					{
						state |= AccessibleStates.Focusable;
					}
					if (!owner.Visible)
					{
						state |= AccessibleStates.Invisible;
					}
				}
				return state;
			}
		}

		public virtual string Value
		{
			get
			{
				return value;
			}
			set
			{
				this.value = value;
			}
		}

		Type IReflect.UnderlyingSystemType
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		int IAccessible.accChildCount
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		object IAccessible.accFocus
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		object IAccessible.accParent
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		object IAccessible.accSelection
		{
			get
			{
				throw new NotImplementedException();
			}
		}

		public AccessibleObject()
		{
			owner = null;
			value = null;
			name = null;
			role = AccessibleRole.Default;
			default_action = null;
			description = null;
			help = null;
			keyboard_shortcut = null;
			state = AccessibleStates.None;
		}

		internal AccessibleObject(Control owner)
			: this()
		{
			this.owner = owner;
		}

		public virtual void DoDefaultAction()
		{
			if (owner != null)
			{
				owner.DoDefaultAction();
			}
		}

		public virtual AccessibleObject GetChild(int index)
		{
			if (owner != null && index < owner.Controls.Count)
			{
				return owner.Controls[index].AccessibilityObject;
			}
			return null;
		}

		public virtual int GetChildCount()
		{
			if (owner != null)
			{
				return owner.Controls.Count;
			}
			return -1;
		}

		public virtual AccessibleObject GetFocused()
		{
			if (owner.has_focus)
			{
				return owner.AccessibilityObject;
			}
			return FindFocusControl(owner);
		}

		public virtual int GetHelpTopic(out string fileName)
		{
			fileName = null;
			return -1;
		}

		public virtual AccessibleObject GetSelected()
		{
			if ((state & AccessibleStates.Selected) != 0)
			{
				return this;
			}
			return FindSelectedControl(owner);
		}

		public virtual AccessibleObject HitTest(int x, int y)
		{
			return FindHittestControl(owner, x, y)?.AccessibilityObject;
		}

		public virtual AccessibleObject Navigate(AccessibleNavigation navdir)
		{
			int num = ((owner.Parent == null) ? (-1) : owner.Parent.Controls.IndexOf(owner));
			switch (navdir)
			{
			case AccessibleNavigation.Up:
				if (owner.Parent != null)
				{
					for (int k = 0; k < owner.Parent.Controls.Count; k++)
					{
						if (owner != owner.Parent.Controls[k] && owner.Parent.Controls[k].Top < owner.Top)
						{
							return owner.Parent.Controls[k].AccessibilityObject;
						}
					}
				}
				return owner.AccessibilityObject;
			case AccessibleNavigation.Down:
				if (owner.Parent != null)
				{
					for (int j = 0; j < owner.Parent.Controls.Count; j++)
					{
						if (owner != owner.Parent.Controls[j] && owner.Parent.Controls[j].Top > owner.Bottom)
						{
							return owner.Parent.Controls[j].AccessibilityObject;
						}
					}
				}
				return owner.AccessibilityObject;
			case AccessibleNavigation.Left:
				if (owner.Parent != null)
				{
					for (int i = 0; i < owner.Parent.Controls.Count; i++)
					{
						if (owner != owner.Parent.Controls[i] && owner.Parent.Controls[i].Left < owner.Left)
						{
							return owner.Parent.Controls[i].AccessibilityObject;
						}
					}
				}
				return owner.AccessibilityObject;
			case AccessibleNavigation.Right:
				if (owner.Parent != null)
				{
					for (int l = 0; l < owner.Parent.Controls.Count; l++)
					{
						if (owner != owner.Parent.Controls[l] && owner.Parent.Controls[l].Left > owner.Right)
						{
							return owner.Parent.Controls[l].AccessibilityObject;
						}
					}
				}
				return owner.AccessibilityObject;
			case AccessibleNavigation.Next:
				if (owner.Parent != null)
				{
					if (num + 1 < owner.Parent.Controls.Count)
					{
						return owner.Parent.Controls[num + 1].AccessibilityObject;
					}
					return owner.Parent.Controls[0].AccessibilityObject;
				}
				return owner.AccessibilityObject;
			case AccessibleNavigation.Previous:
				if (owner.Parent != null)
				{
					if (num > 0)
					{
						return owner.Parent.Controls[num - 1].AccessibilityObject;
					}
					return owner.Parent.Controls[owner.Parent.Controls.Count - 1].AccessibilityObject;
				}
				return owner.AccessibilityObject;
			case AccessibleNavigation.FirstChild:
				if (owner.Controls.Count > 0)
				{
					return owner.Controls[0].AccessibilityObject;
				}
				return owner.AccessibilityObject;
			case AccessibleNavigation.LastChild:
				if (owner.Controls.Count > 0)
				{
					return owner.Controls[owner.Controls.Count - 1].AccessibilityObject;
				}
				return owner.AccessibilityObject;
			default:
				return owner.AccessibilityObject;
			}
		}

		public virtual void Select(AccessibleSelection flags)
		{
			if ((flags & AccessibleSelection.TakeFocus) != 0)
			{
				owner.Focus();
			}
		}

		protected void UseStdAccessibleObjects(IntPtr handle)
		{
		}

		protected void UseStdAccessibleObjects(IntPtr handle, int objid)
		{
			UseStdAccessibleObjects(handle, 0);
		}

		internal static AccessibleObject FindFocusControl(Control parent)
		{
			if (parent != null)
			{
				for (int i = 0; i < parent.Controls.Count; i++)
				{
					Control control = parent.Controls[i];
					if ((control.AccessibilityObject.state & AccessibleStates.Focused) != 0)
					{
						return control.AccessibilityObject;
					}
					if (control.Controls.Count > 0)
					{
						AccessibleObject accessibleObject = FindFocusControl(control);
						if (accessibleObject != null)
						{
							return accessibleObject;
						}
					}
				}
			}
			return null;
		}

		internal static AccessibleObject FindSelectedControl(Control parent)
		{
			if (parent != null)
			{
				for (int i = 0; i < parent.Controls.Count; i++)
				{
					Control control = parent.Controls[i];
					if ((control.AccessibilityObject.state & AccessibleStates.Selected) != 0)
					{
						return control.AccessibilityObject;
					}
					if (control.Controls.Count > 0)
					{
						AccessibleObject accessibleObject = FindSelectedControl(control);
						if (accessibleObject != null)
						{
							return accessibleObject;
						}
					}
				}
			}
			return null;
		}

		internal static Control FindHittestControl(Control parent, int x, int y)
		{
			Point p = new Point(x, y);
			Point pt = parent.PointToClient(p);
			if (parent.ClientRectangle.Contains(pt))
			{
				return parent;
			}
			for (int i = 0; i < parent.Controls.Count; i++)
			{
				Control control = parent.Controls[i];
				pt = control.PointToClient(p);
				if (control.ClientRectangle.Contains(pt))
				{
					return control;
				}
				if (control.Controls.Count > 0)
				{
					Control control2 = FindHittestControl(control, x, y);
					if (control2 != null)
					{
						return control2;
					}
				}
			}
			return null;
		}

		FieldInfo IReflect.GetField(string name, BindingFlags bindingAttr)
		{
			throw new NotImplementedException();
		}

		FieldInfo[] IReflect.GetFields(BindingFlags bindingAttr)
		{
			throw new NotImplementedException();
		}

		MemberInfo[] IReflect.GetMember(string name, BindingFlags bindingAttr)
		{
			throw new NotImplementedException();
		}

		MemberInfo[] IReflect.GetMembers(BindingFlags bindingAttr)
		{
			throw new NotImplementedException();
		}

		MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr)
		{
			throw new NotImplementedException();
		}

		MethodInfo IReflect.GetMethod(string name, BindingFlags bindingAttr, Binder binder, Type[] types, ParameterModifier[] modifiers)
		{
			throw new NotImplementedException();
		}

		MethodInfo[] IReflect.GetMethods(BindingFlags bindingAttr)
		{
			throw new NotImplementedException();
		}

		PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr)
		{
			throw new NotImplementedException();
		}

		PropertyInfo IReflect.GetProperty(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers)
		{
			throw new NotImplementedException();
		}

		PropertyInfo[] IReflect.GetProperties(BindingFlags bindingAttr)
		{
			throw new NotImplementedException();
		}

		object IReflect.InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters)
		{
			throw new NotImplementedException();
		}

		void IAccessible.accDoDefaultAction(object childID)
		{
			throw new NotImplementedException();
		}

		object IAccessible.accHitTest(int xLeft, int yTop)
		{
			throw new NotImplementedException();
		}

		void IAccessible.accLocation(out int pxLeft, out int pyTop, out int pcxWidth, out int pcyHeight, object childID)
		{
			throw new NotImplementedException();
		}

		object IAccessible.accNavigate(int navDir, object childID)
		{
			throw new NotImplementedException();
		}

		void IAccessible.accSelect(int flagsSelect, object childID)
		{
			throw new NotImplementedException();
		}

		object IAccessible.get_accChild(object childID)
		{
			throw new NotImplementedException();
		}

		string IAccessible.get_accDefaultAction(object childID)
		{
			throw new NotImplementedException();
		}

		string IAccessible.get_accDescription(object childID)
		{
			throw new NotImplementedException();
		}

		string IAccessible.get_accHelp(object childID)
		{
			throw new NotImplementedException();
		}

		int IAccessible.get_accHelpTopic(out string pszHelpFile, object childID)
		{
			throw new NotImplementedException();
		}

		string IAccessible.get_accKeyboardShortcut(object childID)
		{
			throw new NotImplementedException();
		}

		string IAccessible.get_accName(object childID)
		{
			throw new NotImplementedException();
		}

		object IAccessible.get_accRole(object childID)
		{
			throw new NotImplementedException();
		}

		object IAccessible.get_accState(object childID)
		{
			throw new NotImplementedException();
		}

		string IAccessible.get_accValue(object childID)
		{
			throw new NotImplementedException();
		}

		void IAccessible.set_accName(object childID, string newName)
		{
			throw new NotImplementedException();
		}

		void IAccessible.set_accValue(object childID, string newValue)
		{
			throw new NotImplementedException();
		}

		public bool RaiseAutomationNotification(AutomationNotificationKind notificationKind, AutomationNotificationProcessing notificationProcessing, string notificationText)
		{
			ThrowStub.ThrowNotSupportedException();
			return default(bool);
		}

		public virtual bool RaiseLiveRegionChanged()
		{
			ThrowStub.ThrowNotSupportedException();
			return default(bool);
		}
	}
	public enum AccessibleRole
	{
		None = 0,
		TitleBar = 1,
		MenuBar = 2,
		ScrollBar = 3,
		Grip = 4,
		Sound = 5,
		Cursor = 6,
		Caret = 7,
		Alert = 8,
		Window = 9,
		Client = 10,
		MenuPopup = 11,
		MenuItem = 12,
		ToolTip = 13,
		Application = 14,
		Document = 15,
		Pane = 16,
		Chart = 17,
		Dialog = 18,
		Border = 19,
		Grouping = 20,
		Separator = 21,
		ToolBar = 22,
		StatusBar = 23,
		Table = 24,
		ColumnHeader = 25,
		RowHeader = 26,
		Column = 27,
		Row = 28,
		Cell = 29,
		Link = 30,
		HelpBalloon = 31,
		Character = 32,
		List = 33,
		ListItem = 34,
		Outline = 35,
		OutlineItem = 36,
		PageTab = 37,
		PropertyPage = 38,
		Indicator = 39,
		Graphic = 40,
		StaticText = 41,
		Text = 42,
		PushButton = 43,
		CheckButton = 44,
		RadioButton = 45,
		ComboBox = 46,
		DropList = 47,
		ProgressBar = 48,
		Dial = 49,
		HotkeyField = 50,
		Slider = 51,
		SpinButton = 52,
		Diagram = 53,
		Animation = 54,
		Equation = 55,
		ButtonDropDown = 56,
		ButtonMenu = 57,
		ButtonDropDownGrid = 58,
		WhiteSpace = 59,
		PageTabList = 60,
		Clock = 61,
		Default = -1,
		SplitButton = 62,
		IpAddress = 63,
		OutlineButton = 64
	}
	[Flags]
	public enum AccessibleSelection
	{
		None = 0,
		TakeFocus = 1,
		TakeSelection = 2,
		ExtendSelection = 4,
		AddSelection = 8,
		RemoveSelection = 0x10
	}
	[Flags]
	public enum AccessibleStates
	{
		None = 0,
		Unavailable = 1,
		Selected = 2,
		Focused = 4,
		Pressed = 8,
		Checked = 0x10,
		Mixed = 0x20,
		Indeterminate = 0x20,
		ReadOnly = 0x40,
		HotTracked = 0x80,
		Default = 0x100,
		Expanded = 0x200,
		Collapsed = 0x400,
		Busy = 0x800,
		Floating = 0x1000,
		Marqueed = 0x2000,
		Animated = 0x4000,
		Invisible = 0x8000,
		Offscreen = 0x10000,
		Sizeable = 0x20000,
		Moveable = 0x40000,
		SelfVoicing = 0x80000,
		Focusable = 0x100000,
		Selectable = 0x200000,
		Linked = 0x400000,
		Traversed = 0x800000,
		MultiSelectable = 0x1000000,
		ExtSelectable = 0x2000000,
		AlertLow = 0x4000000,
		AlertMedium = 0x8000000,
		AlertHigh = 0x10000000,
		Protected = 0x20000000,
		[Obsolete]
		Valid = 0x3FFFFFFF,
		HasPopup = 0x40000000
	}
	public sealed class AmbientProperties
	{
		private System.Drawing.Color fore_color;

		private System.Drawing.Color back_color;

		private Font font;

		private Cursor cursor;

		public System.Drawing.Color BackColor
		{
			get
			{
				return back_color;
			}
			set
			{
				back_color = value;
			}
		}

		public Cursor Cursor
		{
			get
			{
				return cursor;
			}
			set
			{
				cursor = value;
			}
		}

		public Font Font
		{
			get
			{
				return font;
			}
			set
			{
				font = value;
			}
		}

		public System.Drawing.Color ForeColor
		{
			get
			{
				return fore_color;
			}
			set
			{
				fore_color = value;
			}
		}
	}
	[Editor("System.Windows.Forms.Design.AnchorEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))]
	[Flags]
	public enum AnchorStyles
	{
		None = 0,
		Top = 1,
		Bottom = 2,
		Left = 4,
		Right = 8
	}
	[ComVisible(true)]
	public enum Appearance
	{
		Normal,
		Button
	}
	public sealed class Application
	{
		internal class MWFThread
		{
			private ApplicationContext context;

			private bool messageloop_started;

			private bool handling_exception;

			private int thread_id;

			private static readonly Hashtable threads = new Hashtable();

			public ApplicationContext Context
			{
				get
				{
					return context;
				}
				set
				{
					context = value;
				}
			}

			public bool MessageLoop
			{
				get
				{
					return messageloop_started;
				}
				set
				{
					messageloop_started = value;
				}
			}

			public bool HandlingException
			{
				get
				{
					return handling_exception;
				}
				set
				{
					handling_exception = value;
				}
			}

			public static int LoopCount
			{
				get
				{
					lock (threads)
					{
						int num = 0;
						foreach (MWFThread value in threads.Values)
						{
							if (value.messageloop_started)
							{
								num++;
							}
						}
						return num;
					}
				}
			}

			public static MWFThread Current
			{
				get
				{
					MWFThread mWFThread = null;
					lock (threads)
					{
						mWFThread = (MWFThread)threads[Thread.CurrentThread.GetHashCode()];
						if (mWFThread == null)
						{
							mWFThread = new MWFThread();
							mWFThread.thread_id = Thread.CurrentThread.GetHashCode();
							threads[mWFThread.thread_id] = mWFThread;
						}
					}
					return mWFThread;
				}
			}

			private MWFThread()
			{
			}

			public void Exit()
			{
				if (context != null)
				{
					context.ExitThread();
				}
				context = null;
				if (Application.ThreadExit != null)
				{
					Application.ThreadExit(null, EventArgs.Empty);
				}
				if (LoopCount == 0 && Application.ApplicationExit != null)
				{
					Application.ApplicationExit(null, EventArgs.Empty);
				}
				((MWFThread)threads[thread_id]).MessageLoop = false;
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public delegate bool MessageLoopCallback();

		private static bool browser_embedded;

		private static InputLanguage input_language;

		private static string safe_caption_format;

		private static readonly ArrayList message_filters;

		private static readonly FormCollection forms;

		private static bool use_wait_cursor;

		private static ToolStrip keyboard_capture;

		private static VisualStyleState visual_style_state;

		private static bool visual_styles_enabled;

		internal static bool use_compatible_text_rendering;

		public static bool AllowQuit => !browser_embedded;

		public static string CommonAppDataPath => CreateDataPath(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));

		public static RegistryKey CommonAppDataRegistry
		{
			get
			{
				string subkey = $"Software\\{CompanyName}\\{ProductName}\\{ProductVersion}";
				return Registry.LocalMachine.CreateSubKey(subkey);
			}
		}

		public static string CompanyName
		{
			get
			{
				string text = string.Empty;
				Assembly assembly = Assembly.GetEntryAssembly();
				if (assembly == null)
				{
					assembly = Assembly.GetCallingAssembly();
				}
				AssemblyCompanyAttribute[] array = (AssemblyCompanyAttribute[])assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), inherit: true);
				if (array != null && array.Length != 0)
				{
					text = array[0].Company;
				}
				if ((text == null || text.Length == 0) && assembly.EntryPoint != null)
				{
					text = assembly.EntryPoint.DeclaringType.Namespace;
					if (text != null)
					{
						int num = text.IndexOf('.');
						if (num >= 0)
						{
							text = text.Substring(0, num);
						}
					}
				}
				if ((text == null || text.Length == 0) && assembly.EntryPoint != null)
				{
					text = assembly.EntryPoint.DeclaringType.FullName;
				}
				return text;
			}
		}

		public static CultureInfo CurrentCulture
		{
			get
			{
				return Thread.CurrentThread.CurrentUICulture;
			}
			set
			{
				Thread.CurrentThread.CurrentUICulture = value;
			}
		}

		public static InputLanguage CurrentInputLanguage
		{
			get
			{
				return input_language;
			}
			set
			{
				input_language = value;
			}
		}

		public static string ExecutablePath => Path.GetFullPath(Environment.GetCommandLineArgs()[0]);

		public static string LocalUserAppDataPath => CreateDataPath(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData));

		public static bool MessageLoop => MWFThread.Current.MessageLoop;

		public static string ProductName
		{
			get
			{
				string text = string.Empty;
				Assembly assembly = Assembly.GetEntryAssembly();
				if (assembly == null)
				{
					assembly = Assembly.GetCallingAssembly();
				}
				AssemblyProductAttribute[] array = (AssemblyProductAttribute[])assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), inherit: true);
				if (array != null && array.Length != 0)
				{
					text = array[0].Product;
				}
				if ((text == null || text.Length == 0) && assembly.EntryPoint != null)
				{
					text = assembly.EntryPoint.DeclaringType.Namespace;
					if (text != null)
					{
						int num = text.LastIndexOf('.');
						if (num >= 0 && num < text.Length - 1)
						{
							text = text.Substring(num + 1);
						}
					}
					if (text == null || text.Length == 0)
					{
						text = assembly.EntryPoint.DeclaringType.FullName;
					}
				}
				return text;
			}
		}

		public static string ProductVersion
		{
			get
			{
				string text = string.Empty;
				Assembly assembly = Assembly.GetEntryAssembly();
				if (assembly == null)
				{
					assembly = Assembly.GetCallingAssembly();
				}
				if (Attribute.GetCustomAttribute(assembly, typeof(AssemblyInformationalVersionAttribute)) is AssemblyInformationalVersionAttribute assemblyInformationalVersionAttribute)
				{
					text = assemblyInformationalVersionAttribute.InformationalVersion;
				}
				if ((text == null || text.Length == 0) && Attribute.GetCustomAttribute(assembly, typeof(AssemblyFileVersionAttribute)) is AssemblyFileVersionAttribute assemblyFileVersionAttribute)
				{
					text = assemblyFileVersionAttribute.Version;
				}
				if (text == null || text.Length == 0)
				{
					text = assembly.GetName().Version.ToString();
				}
				return text;
			}
		}

		public static string SafeTopLevelCaptionFormat
		{
			get
			{
				return safe_caption_format;
			}
			set
			{
				safe_caption_format = value;
			}
		}

		public static string StartupPath => Path.GetDirectoryName(ExecutablePath);

		public static string UserAppDataPath => CreateDataPath(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));

		public static RegistryKey UserAppDataRegistry
		{
			get
			{
				string subkey = $"Software\\{CompanyName}\\{ProductName}\\{ProductVersion}";
				return Registry.CurrentUser.CreateSubKey(subkey);
			}
		}

		public static bool UseWaitCursor
		{
			get
			{
				return use_wait_cursor;
			}
			set
			{
				use_wait_cursor = value;
				if (!use_wait_cursor)
				{
					return;
				}
				foreach (Form openForm in OpenForms)
				{
					openForm.Cursor = Cursors.WaitCursor;
				}
			}
		}

		public static bool RenderWithVisualStyles
		{
			get
			{
				if (VisualStyleInformation.IsSupportedByOS)
				{
					if (!VisualStyleInformation.IsEnabledByUser)
					{
						return false;
					}
					if (!XplatUI.ThemesEnabled)
					{
						return false;
					}
					if (VisualStyleState == VisualStyleState.ClientAndNonClientAreasEnabled)
					{
						return true;
					}
					if (VisualStyleState == VisualStyleState.ClientAreaEnabled)
					{
						return true;
					}
				}
				return false;
			}
		}

		public static VisualStyleState VisualStyleState
		{
			get
			{
				return visual_style_state;
			}
			set
			{
				visual_style_state = value;
			}
		}

		public static FormCollection OpenForms => forms;

		internal static ToolStrip KeyboardCapture
		{
			get
			{
				return keyboard_capture;
			}
			set
			{
				keyboard_capture = value;
			}
		}

		internal static bool VisualStylesEnabled => visual_styles_enabled;

		public static event EventHandler ApplicationExit;

		public static event EventHandler Idle
		{
			add
			{
				XplatUI.Idle += value;
			}
			remove
			{
				XplatUI.Idle -= value;
			}
		}

		public static event EventHandler ThreadExit;

		public static event ThreadExceptionEventHandler ThreadException;

		internal static event EventHandler FormAdded;

		internal static event EventHandler PreRun;

		[MonoTODO]
		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public static event EventHandler EnterThreadModal;

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		[MonoTODO]
		public static event EventHandler LeaveThreadModal;

		private Application()
		{
			browser_embedded = false;
		}

		static Application()
		{
			input_language = InputLanguage.CurrentInputLanguage;
			safe_caption_format = "{1} - {0} - {2}";
			message_filters = new ArrayList();
			forms = new FormCollection();
			visual_style_state = VisualStyleState.ClientAndNonClientAreasEnabled;
			use_compatible_text_rendering = true;
			InitializeUIAutomation();
		}

		private static void InitializeUIAutomation()
		{
			Assembly assembly = null;
			try
			{
				assembly = Assembly.Load("UIAutomationWinforms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f4ceacb585d99812");
			}
			catch
			{
			}
			if (assembly == null)
			{
				return;
			}
			try
			{
				Type type = assembly.GetType("Mono.UIAutomation.Winforms.Global", throwOnError: false);
				if (type != null)
				{
					MethodInfo method = type.GetMethod("Initialize", BindingFlags.Static | BindingFlags.Public);
					if (method != null)
					{
						method.Invoke(null, new object[0]);
						return;
					}
					throw new Exception(string.Format("Method {0} not found in type {1}.", "Initialize", "Mono.UIAutomation.Winforms.Global"));
				}
				throw new Exception(string.Format("Type {0} not found in assembly {1}.", "Mono.UIAutomation.Winforms.Global", "UIAutomationWinforms, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f4ceacb585d99812"));
			}
			catch (Exception ex)
			{
				Console.Error.WriteLine("Error setting up UIA: " + ex);
			}
		}

		internal static void CloseForms(Thread thread)
		{
			ArrayList arrayList = new ArrayList();
			lock (forms)
			{
				foreach (Form form in forms)
				{
					if (thread == null || thread == form.creator_thread)
					{
						arrayList.Add(form);
					}
				}
				foreach (Form item in arrayList)
				{
					item.Dispose();
				}
			}
		}

		public static void AddMessageFilter(IMessageFilter value)
		{
			lock (message_filters)
			{
				message_filters.Add(value);
			}
		}

		internal static void AddKeyFilter(IKeyFilter value)
		{
			XplatUI.AddKeyFilter(value);
		}

		public static void DoEvents()
		{
			XplatUI.DoEvents();
		}

		public static void EnableVisualStyles()
		{
			visual_styles_enabled = true;
			XplatUI.EnableThemes();
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public static bool FilterMessage(ref Message message)
		{
			lock (message_filters)
			{
				for (int i = 0; i < message_filters.Count; i++)
				{
					if (((IMessageFilter)message_filters[i]).PreFilterMessage(ref message))
					{
						return true;
					}
				}
			}
			return false;
		}

		public static void SetCompatibleTextRenderingDefault(bool defaultValue)
		{
			use_compatible_text_rendering = defaultValue;
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		[MonoNotSupported("Only applies when Winforms is being hosted by an unmanaged app.")]
		public static void RegisterMessageLoop(MessageLoopCallback callback)
		{
		}

		[MonoNotSupported("Empty stub.")]
		public static bool SetSuspendState(PowerState state, bool force, bool disableWakeEvent)
		{
			return false;
		}

		[MonoNotSupported("Empty stub.")]
		public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode)
		{
		}

		[MonoNotSupported("Empty stub.")]
		public static void SetUnhandledExceptionMode(UnhandledExceptionMode mode, bool threadScope)
		{
		}

		[MonoNotSupported("Only applies when Winforms is being hosted by an unmanaged app.")]
		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public static void UnregisterMessageLoop()
		{
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public static void RaiseIdle(EventArgs e)
		{
			XplatUI.RaiseIdle(e);
		}

		public static void Restart()
		{
			if (Assembly.GetEntryAssembly() == null)
			{
				throw new NotSupportedException("The method 'Restart' is not supported by this application type.");
			}
			string mono = MonoToolsLocator.Mono;
			StringBuilder stringBuilder = new StringBuilder();
			string[] commandLineArgs = Environment.GetCommandLineArgs();
			for (int i = 0; i < commandLineArgs.Length; i++)
			{
				stringBuilder.Append($"\"{commandLineArgs[i]}\" ");
			}
			string text = stringBuilder.ToString();
			ProcessStartInfo startInfo = Process.GetCurrentProcess().StartInfo;
			if (mono == null)
			{
				startInfo.FileName = commandLineArgs[0];
				startInfo.Arguments = text.Remove(0, commandLineArgs[0].Length + 3);
			}
			else
			{
				startInfo.Arguments = text;
				startInfo.FileName = mono;
			}
			startInfo.WorkingDirectory = Environment.CurrentDirectory;
			Exit();
			Process.Start(startInfo);
		}

		public static void Exit()
		{
			Exit(new CancelEventArgs());
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public static void Exit(CancelEventArgs e)
		{
			lock (forms)
			{
				foreach (Form item in new ArrayList(forms))
				{
					e.Cancel = item.FireClosingEvents(CloseReason.ApplicationExitCall, cancel: false);
					if (e.Cancel)
					{
						return;
					}
					item.suppress_closing_events = true;
					item.Close();
					item.Dispose();
				}
			}
			XplatUI.PostQuitMessage(0);
		}

		public static void ExitThread()
		{
			CloseForms(Thread.CurrentThread);
			XplatUI.PostQuitMessage(0);
		}

		public static ApartmentState OleRequired()
		{
			return ApartmentState.Unknown;
		}

		public static void OnThreadException(Exception t)
		{
			if (MWFThread.Current.HandlingException)
			{
				Console.WriteLine(t);
				Environment.Exit(1);
			}
			try
			{
				MWFThread.Current.HandlingException = true;
				if (Application.ThreadException != null)
				{
					Application.ThreadException(null, new ThreadExceptionEventArgs(t));
					return;
				}
				if (SystemInformation.UserInteractive)
				{
					new ThreadExceptionDialog(t).ShowDialog();
					return;
				}
				Console.WriteLine(t.ToString());
				Exit();
			}
			finally
			{
				MWFThread.Current.HandlingException = false;
			}
		}

		public static void RemoveMessageFilter(IMessageFilter value)
		{
			lock (message_filters)
			{
				message_filters.Remove(value);
			}
		}

		public static void Run()
		{
			Run(new ApplicationContext());
		}

		public static void Run(Form mainForm)
		{
			Run(new ApplicationContext(mainForm));
		}

		internal static void FirePreRun()
		{
			Application.PreRun?.Invoke(null, EventArgs.Empty);
		}

		public static void Run(ApplicationContext context)
		{
			if (SynchronizationContext.Current == null)
			{
				SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
			}
			RunLoop(Modal: false, context);
			if (SynchronizationContext.Current is WindowsFormsSynchronizationContext)
			{
				WindowsFormsSynchronizationContext.Uninstall();
			}
		}

		private static void DisableFormsForModalLoop(Queue toplevels, ApplicationContext context)
		{
			lock (forms)
			{
				IEnumerator enumerator = forms.GetEnumerator();
				while (enumerator.MoveNext())
				{
					Form form = (Form)enumerator.Current;
					if (form == context.MainForm)
					{
						continue;
					}
					Control control = form;
					bool flag = false;
					do
					{
						if (control.Parent == context.MainForm)
						{
							flag = true;
							break;
						}
						control = control.Parent;
					}
					while (control != null);
					if (!flag && form.IsHandleCreated && XplatUI.IsEnabled(form.Handle))
					{
						XplatUI.EnableWindow(form.Handle, Enable: false);
						toplevels.Enqueue(form);
					}
				}
			}
		}

		private static void EnableFormsForModalLoop(Queue toplevels, ApplicationContext context)
		{
			while (toplevels.Count > 0)
			{
				Form form = (Form)toplevels.Dequeue();
				if (form.IsHandleCreated)
				{
					XplatUI.EnableWindow(form.window.Handle, Enable: true);
					context.MainForm = form;
				}
			}
		}

		internal static void RunLoop(bool Modal, ApplicationContext context)
		{
			MWFThread current = MWFThread.Current;
			MSG msg = default(MSG);
			if (context == null)
			{
				context = new ApplicationContext();
			}
			ApplicationContext context2 = current.Context;
			current.Context = context;
			if (context.MainForm != null)
			{
				context.MainForm.is_modal = Modal;
				context.MainForm.context = context;
				context.MainForm.closing = false;
				context.MainForm.Visible = true;
				if (context.MainForm != null)
				{
					context.MainForm.Activate();
				}
			}
			Queue toplevels;
			if (Modal)
			{
				toplevels = new Queue();
				DisableFormsForModalLoop(toplevels, context);
				if (context.MainForm != null)
				{
					XplatUI.EnableWindow(context.MainForm.Handle, Enable: true);
					XplatUI.SetModal(context.MainForm.Handle, Modal: true);
				}
			}
			else
			{
				toplevels = null;
			}
			object queue_id = XplatUI.StartLoop(Thread.CurrentThread);
			current.MessageLoop = true;
			bool flag = false;
			while (!flag && XplatUI.GetMessage(queue_id, ref msg, IntPtr.Zero, 0, 0))
			{
				Message message = Message.Create(msg.hwnd, (int)msg.message, msg.wParam, msg.lParam);
				if (FilterMessage(ref message))
				{
					continue;
				}
				Msg message2 = msg.message;
				if (message2 <= Msg.WM_SYSCHAR)
				{
					if (message2 == Msg.WM_QUIT)
					{
						flag = true;
						goto IL_0307;
					}
					if ((uint)(message2 - 256) <= 2u || (uint)(message2 - 260) <= 2u)
					{
						Control control = Control.FromHandle(msg.hwnd);
						if (keyboard_capture != null)
						{
							if (message.Msg == 260 && message.WParam.ToInt32() == 18)
							{
								keyboard_capture.GetTopLevelToolStrip().Dismiss(ToolStripDropDownCloseReason.Keyboard);
								continue;
							}
							message.HWnd = keyboard_capture.Handle;
							PreProcessControlState preProcessControlState = keyboard_capture.PreProcessControlMessageInternal(ref message);
							if (preProcessControlState == PreProcessControlState.MessageProcessed)
							{
								continue;
							}
							if ((uint)(preProcessControlState - 1) <= 1u)
							{
								if ((message.Msg != 256 && message.Msg != 258) || keyboard_capture.ProcessControlMnemonic((char)(int)message.WParam) || control == null || !ControlOnToolStrip(control))
								{
									continue;
								}
								message.HWnd = msg.hwnd;
							}
						}
						if ((control == null || control.PreProcessControlMessageInternal(ref message) == PreProcessControlState.MessageProcessed) && control != null)
						{
							goto IL_0307;
						}
					}
				}
				else if ((message2 == Msg.WM_LBUTTONDOWN || message2 == Msg.WM_RBUTTONDOWN || message2 == Msg.WM_MBUTTONDOWN) && keyboard_capture != null)
				{
					Control control2 = Control.FromHandle(

BepInEx/core/System.Xml.dll

Decompiled 2 weeks ago
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Diagnostics;
using System.Diagnostics.SymbolStore;
using System.Globalization;
using System.IO;
using System.Net;
using System.Net.Cache;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Principal;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.Serialization.Advanced;
using System.Xml.Serialization.Configuration;
using System.Xml.Utils;
using System.Xml.XPath;
using System.Xml.XmlConfiguration;
using System.Xml.Xsl;
using System.Xml.Xsl.IlGen;
using System.Xml.Xsl.Qil;
using System.Xml.Xsl.Runtime;
using System.Xml.Xsl.XPath;
using System.Xml.Xsl.Xslt;
using System.Xml.Xsl.XsltOld;
using System.Xml.Xsl.XsltOld.Debugger;
using MS.Internal.Xml.Cache;
using MS.Internal.Xml.XPath;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using Microsoft.Win32;
using Unity;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: InternalsVisibleTo("System.Data.SqlXml, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.Xml.Linq, PublicKey=00000000000000000400000000000000")]
[assembly: InternalsVisibleTo("System.ServiceModel.Friend, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")]
[assembly: AssemblyTitle("System.Xml.dll")]
[assembly: AssemblyDescription("System.Xml.dll")]
[assembly: AssemblyDefaultAlias("System.Xml.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyKeyFile("../ecma.pub")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("System.Xml.Linq, PublicKey=00000000000000000400000000000000", AllInternalsVisible = false)]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class AssemblyRef
{
	internal const string SystemConfiguration = "System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	internal const string System = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string EcmaPublicKey = "b77a5c561934e089";

	public const string FrameworkPublicKeyFull = "00000000000000000400000000000000";

	public const string FrameworkPublicKeyFull2 = "00000000000000000400000000000000";

	public const string MicrosoftPublicKey = "b03f5f7f11d50a3a";

	public const string MicrosoftJScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string MicrosoftVSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemData = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string SystemDesign = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemDrawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWeb = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string SystemWebExtensions = "System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string SystemWindowsForms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class Consts
{
	public const string MonoCorlibVersion = "1A5E0066-58DC-428A-B21C-0AD6CDAE2789";

	public const string MonoVersion = "6.13.0.0";

	public const string MonoCompany = "Mono development team";

	public const string MonoProduct = "Mono Common Language Infrastructure";

	public const string MonoCopyright = "(c) Various Mono authors";

	public const string FxVersion = "4.0.0.0";

	public const string FxFileVersion = "4.6.57.0";

	public const string EnvironmentVersion = "4.0.30319.42000";

	public const string VsVersion = "0.0.0.0";

	public const string VsFileVersion = "11.0.0.0";

	private const string PublicKeyToken = "b77a5c561934e089";

	public const string AssemblyI18N = "I18N, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMicrosoft_JScript = "Microsoft.JScript, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio = "Microsoft.VisualStudio, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VisualStudio_Web = "Microsoft.VisualStudio.Web, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMicrosoft_VSDesigner = "Microsoft.VSDesigner, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblyMono_Http = "Mono.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Posix = "Mono.Posix, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Security = "Mono.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyMono_Messaging_RabbitMQ = "Mono.Messaging.RabbitMQ, Version=4.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756";

	public const string AssemblyCorlib = "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Data = "System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Design = "System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_DirectoryServices = "System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing = "System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Drawing_Design = "System.Drawing.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Messaging = "System.Messaging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Security = "System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_ServiceProcess = "System.ServiceProcess, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Web = "System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a";

	public const string AssemblySystem_Windows_Forms = "System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_2_0 = "System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystemCore_3_5 = "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string AssemblySystem_Core = "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";

	public const string WindowsBase_3_0 = "WindowsBase, Version=3.0.0.0, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyWindowsBase = "WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_3_5 = "PresentationCore, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationCore_4_0 = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblyPresentationFramework_3_5 = "PresentationFramework, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";

	public const string AssemblySystemServiceModel_3_0 = "System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
}
internal static class SR
{
	public const string Xml_UserException = "{0}";

	public const string Xml_DefaultException = "An XML error has occurred.";

	public const string Xml_InvalidOperation = "Operation is not valid due to the current state of the object.";

	public const string Xml_ErrorFilePosition = "An error occurred at {0}, ({1}, {2}).";

	public const string Xml_StackOverflow = "Stack overflow.";

	public const string Xslt_NoStylesheetLoaded = "No stylesheet was loaded.";

	public const string Xslt_NotCompiledStylesheet = "Type '{0}' is not a compiled stylesheet class.";

	public const string Xslt_IncompatibleCompiledStylesheetVersion = "Executing a stylesheet that was compiled using a later version of the framework is not supported. Stylesheet Version: {0}. Current Framework Version: {1}.";

	public const string Xml_AsyncIsRunningException = "An asynchronous operation is already in progress.";

	public const string Xml_ReaderAsyncNotSetException = "Set XmlReaderSettings.Async to true if you want to use Async Methods.";

	public const string Xml_UnclosedQuote = "There is an unclosed literal string.";

	public const string Xml_UnexpectedEOF = "Unexpected end of file while parsing {0} has occurred.";

	public const string Xml_UnexpectedEOF1 = "Unexpected end of file has occurred.";

	public const string Xml_UnexpectedEOFInElementContent = "Unexpected end of file has occurred. The following elements are not closed: {0}";

	public const string Xml_BadStartNameChar = "Name cannot begin with the '{0}' character, hexadecimal value {1}.";

	public const string Xml_BadNameChar = "The '{0}' character, hexadecimal value {1}, cannot be included in a name.";

	public const string Xml_BadDecimalEntity = "Invalid syntax for a decimal numeric entity reference.";

	public const string Xml_BadHexEntity = "Invalid syntax for a hexadecimal numeric entity reference.";

	public const string Xml_MissingByteOrderMark = "There is no Unicode byte order mark. Cannot switch to Unicode.";

	public const string Xml_UnknownEncoding = "System does not support '{0}' encoding.";

	public const string Xml_InternalError = "An internal error has occurred.";

	public const string Xml_InvalidCharInThisEncoding = "Invalid character in the given encoding.";

	public const string Xml_ErrorPosition = "Line {0}, position {1}.";

	public const string Xml_MessageWithErrorPosition = "{0} Line {1}, position {2}.";

	public const string Xml_UnexpectedTokenEx = "'{0}' is an unexpected token. The expected token is '{1}'.";

	public const string Xml_UnexpectedTokens2 = "'{0}' is an unexpected token. The expected token is '{1}' or '{2}'.";

	public const string Xml_ExpectingWhiteSpace = "'{0}' is an unexpected token. Expecting whitespace.";

	public const string Xml_TagMismatchEx = "The '{0}' start tag on line {1} position {2} does not match the end tag of '{3}'.";

	public const string Xml_UnexpectedEndTag = "Unexpected end tag.";

	public const string Xml_UnknownNs = "'{0}' is an undeclared prefix.";

	public const string Xml_BadAttributeChar = "'{0}', hexadecimal value {1}, is an invalid attribute character.";

	public const string Xml_ExpectExternalOrClose = "Expecting external ID, '[' or '>'.";

	public const string Xml_MissingRoot = "Root element is missing.";

	public const string Xml_MultipleRoots = "There are multiple root elements.";

	public const string Xml_InvalidRootData = "Data at the root level is invalid.";

	public const string Xml_XmlDeclNotFirst = "Unexpected XML declaration. The XML declaration must be the first node in the document, and no whitespace characters are allowed to appear before it.";

	public const string Xml_InvalidXmlDecl = "Syntax for an XML declaration is invalid.";

	public const string Xml_InvalidNodeType = "'{0}' is an invalid XmlNodeType.";

	public const string Xml_InvalidPIName = "'{0}' is an invalid name for processing instructions.";

	public const string Xml_InvalidXmlSpace = "'{0}' is an invalid xml:space value.";

	public const string Xml_InvalidVersionNumber = "Version number '{0}' is invalid.";

	public const string Xml_DupAttributeName = "'{0}' is a duplicate attribute name.";

	public const string Xml_BadDTDLocation = "Unexpected DTD declaration.";

	public const string Xml_ElementNotFound = "Element '{0}' was not found.";

	public const string Xml_ElementNotFoundNs = "Element '{0}' with namespace name '{1}' was not found.";

	public const string Xml_PartialContentNodeTypeNotSupportedEx = "XmlNodeType {0} is not supported for partial content parsing.";

	public const string Xml_MultipleDTDsProvided = "Cannot have multiple DTDs.";

	public const string Xml_CanNotBindToReservedNamespace = "Cannot bind to the reserved namespace.";

	public const string Xml_InvalidCharacter = "'{0}', hexadecimal value {1}, is an invalid character.";

	public const string Xml_InvalidBinHexValue = "'{0}' is not a valid BinHex text sequence.";

	public const string Xml_InvalidBinHexValueOddCount = "'{0}' is not a valid BinHex text sequence. The sequence must contain an even number of characters.";

	public const string Xml_InvalidTextDecl = "Invalid text declaration.";

	public const string Xml_InvalidBase64Value = "'{0}' is not a valid Base64 text sequence.";

	public const string Xml_UndeclaredEntity = "Reference to undeclared entity '{0}'.";

	public const string Xml_RecursiveParEntity = "Parameter entity '{0}' references itself.";

	public const string Xml_RecursiveGenEntity = "General entity '{0}' references itself.";

	public const string Xml_ExternalEntityInAttValue = "External entity '{0}' reference cannot appear in the attribute value.";

	public const string Xml_UnparsedEntityRef = "Reference to unparsed entity '{0}'.";

	public const string Xml_NotSameNametable = "Not the same name table.";

	public const string Xml_NametableMismatch = "XmlReaderSettings.XmlNameTable must be the same name table as in XmlParserContext.NameTable or XmlParserContext.NamespaceManager.NameTable, or it must be null.";

	public const string Xml_BadNamespaceDecl = "Invalid namespace declaration.";

	public const string Xml_ErrorParsingEntityName = "An error occurred while parsing EntityName.";

	public const string Xml_InvalidNmToken = "Invalid NmToken value '{0}'.";

	public const string Xml_EntityRefNesting = "Entity replacement text must nest properly within markup declarations.";

	public const string Xml_CannotResolveEntity = "Cannot resolve entity reference '{0}'.";

	public const string Xml_CannotResolveEntityDtdIgnored = "Cannot resolve entity reference '{0}' because the DTD has been ignored. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.";

	public const string Xml_CannotResolveExternalSubset = "Cannot resolve external DTD subset - public ID = '{0}', system ID = '{1}'.";

	public const string Xml_CannotResolveUrl = "Cannot resolve '{0}'.";

	public const string Xml_CDATAEndInText = "']]>' is not allowed in character data.";

	public const string Xml_ExternalEntityInStandAloneDocument = "Standalone document declaration must have a value of 'no' because an external entity '{0}' is referenced.";

	public const string Xml_DtdAfterRootElement = "DTD must be defined before the document root element.";

	public const string Xml_ReadOnlyProperty = "The '{0}' property is read only and cannot be set.";

	public const string Xml_DtdIsProhibited = "DTD is prohibited in this XML document.";

	public const string Xml_DtdIsProhibitedEx = "For security reasons DTD is prohibited in this XML document. To enable DTD processing set the DtdProcessing property on XmlReaderSettings to Parse and pass the settings into XmlReader.Create method.";

	public const string Xml_ReadSubtreeNotOnElement = "ReadSubtree() can be called only if the reader is on an element node.";

	public const string Xml_DtdNotAllowedInFragment = "DTD is not allowed in XML fragments.";

	public const string Xml_CannotStartDocumentOnFragment = "WriteStartDocument cannot be called on writers created with ConformanceLevel.Fragment.";

	public const string Xml_ErrorOpeningExternalDtd = "An error has occurred while opening external DTD '{0}': {1}";

	public const string Xml_ErrorOpeningExternalEntity = "An error has occurred while opening external entity '{0}': {1}";

	public const string Xml_ReadBinaryContentNotSupported = "{0} method is not supported on this XmlReader. Use CanReadBinaryContent property to find out if a reader implements it.";

	public const string Xml_ReadValueChunkNotSupported = "ReadValueChunk method is not supported on this XmlReader. Use CanReadValueChunk property to find out if an XmlReader implements it.";

	public const string Xml_InvalidReadContentAs = "The {0} method is not supported on node type {1}. If you want to read typed content of an element, use the ReadElementContentAs method.";

	public const string Xml_InvalidReadElementContentAs = "The {0} method is not supported on node type {1}.";

	public const string Xml_MixedReadElementContentAs = "ReadElementContentAs() methods cannot be called on an element that has child elements.";

	public const string Xml_MixingReadValueChunkWithBinary = "ReadValueChunk calls cannot be mixed with ReadContentAsBase64 or ReadContentAsBinHex.";

	public const string Xml_MixingBinaryContentMethods = "ReadContentAsBase64 and ReadContentAsBinHex method calls cannot be mixed with calls to ReadElementContentAsBase64 and ReadElementContentAsBinHex.";

	public const string Xml_MixingV1StreamingWithV2Binary = "ReadContentAsBase64 and ReadContentAsBinHex method calls cannot be mixed with calls to ReadChars, ReadBase64, and ReadBinHex.";

	public const string Xml_InvalidReadValueChunk = "The ReadValueAsChunk method is not supported on node type {0}.";

	public const string Xml_ReadContentAsFormatException = "Content cannot be converted to the type {0}.";

	public const string Xml_DoubleBaseUri = "BaseUri must be specified either as an argument of XmlReader.Create or on the XmlParserContext. If it is specified on both, it must be the same base URI.";

	public const string Xml_NotEnoughSpaceForSurrogatePair = "The buffer is not large enough to fit a surrogate pair. Please provide a buffer of size at least 2 characters.";

	public const string Xml_EmptyUrl = "The URL cannot be empty.";

	public const string Xml_UnexpectedNodeInSimpleContent = "Unexpected node type {0}. {1} method can only be called on elements with simple or empty content.";

	public const string Xml_InvalidWhitespaceCharacter = "The Whitespace or SignificantWhitespace node can contain only XML whitespace characters. '{0}' is not an XML white space character.";

	public const string Xml_IncompatibleConformanceLevel = "Cannot change conformance checking to {0}. Make sure the ConformanceLevel in XmlReaderSettings is set to Auto for wrapping scenarios.";

	public const string Xml_LimitExceeded = "The input document has exceeded a limit set by {0}.";

	public const string Xml_ClosedOrErrorReader = "The XmlReader is closed or in error state.";

	public const string Xml_CharEntityOverflow = "Invalid value of a character entity reference.";

	public const string Xml_BadNameCharWithPos = "The '{0}' character, hexadecimal value {1}, at position {2} within the name, cannot be included in a name.";

	public const string Xml_XmlnsBelongsToReservedNs = "The 'xmlns' attribute is bound to the reserved namespace 'http://www.w3.org/2000/xmlns/'.";

	public const string Xml_UndeclaredParEntity = "Reference to undeclared parameter entity '{0}'.";

	public const string Xml_InvalidXmlDocument = "Invalid XML document. {0}";

	public const string Xml_NoDTDPresent = "No DTD found.";

	public const string Xml_MultipleValidaitonTypes = "Unsupported combination of validation types.";

	public const string Xml_NoValidation = "No validation occurred.";

	public const string Xml_WhitespaceHandling = "Expected WhitespaceHandling.None, or WhitespaceHandling.All, or WhitespaceHandling.Significant.";

	public const string Xml_InvalidResetStateCall = "Cannot call ResetState when parsing an XML fragment.";

	public const string Xml_EntityHandling = "Expected EntityHandling.ExpandEntities or EntityHandling.ExpandCharEntities.";

	public const string Xml_AttlistDuplEnumValue = "'{0}' is a duplicate enumeration value.";

	public const string Xml_AttlistDuplNotationValue = "'{0}' is a duplicate notation value.";

	public const string Xml_EncodingSwitchAfterResetState = "'{0}' is an invalid value for the 'encoding' attribute. The encoding cannot be switched after a call to ResetState.";

	public const string Xml_UnexpectedNodeType = "Unexpected XmlNodeType: '{0}'.";

	public const string Xml_InvalidConditionalSection = "A conditional section is not allowed in an internal subset.";

	public const string Xml_UnexpectedCDataEnd = "']]>' is not expected.";

	public const string Xml_UnclosedConditionalSection = "There is an unclosed conditional section.";

	public const string Xml_ExpectDtdMarkup = "Expected DTD markup was not found.";

	public const string Xml_IncompleteDtdContent = "Incomplete DTD content.";

	public const string Xml_EnumerationRequired = "Enumeration data type required.";

	public const string Xml_InvalidContentModel = "Invalid content model.";

	public const string Xml_FragmentId = "Fragment identifier '{0}' cannot be part of the system identifier '{1}'.";

	public const string Xml_ExpectPcData = "Expecting 'PCDATA'.";

	public const string Xml_ExpectNoWhitespace = "Whitespace not allowed before '?', '*', or '+'.";

	public const string Xml_ExpectOp = "Expecting '?', '*', or '+'.";

	public const string Xml_InvalidAttributeType = "'{0}' is an invalid attribute type.";

	public const string Xml_InvalidAttributeType1 = "Invalid attribute type.";

	public const string Xml_ExpectAttType = "Expecting an attribute type.";

	public const string Xml_ColonInLocalName = "'{0}' is an unqualified name and cannot contain the character ':'.";

	public const string Xml_InvalidParEntityRef = "A parameter entity reference is not allowed in internal markup.";

	public const string Xml_ExpectSubOrClose = "Expecting an internal subset or the end of the DOCTYPE declaration.";

	public const string Xml_ExpectExternalOrPublicId = "Expecting a system identifier or a public identifier.";

	public const string Xml_ExpectExternalIdOrEntityValue = "Expecting an external identifier or an entity value.";

	public const string Xml_ExpectIgnoreOrInclude = "Conditional sections must specify the keyword 'IGNORE' or 'INCLUDE'.";

	public const string Xml_UnsupportedClass = "Object type is not supported.";

	public const string Xml_NullResolver = "Resolving of external URIs was prohibited.";

	public const string Xml_RelativeUriNotSupported = "Relative URIs are not supported.";

	public const string Xml_WriterAsyncNotSetException = "Set XmlWriterSettings.Async to true if you want to use Async Methods.";

	public const string Xml_PrefixForEmptyNs = "Cannot use a prefix with an empty namespace.";

	public const string Xml_InvalidCommentChars = "An XML comment cannot contain '--', and '-' cannot be the last character.";

	public const string Xml_UndefNamespace = "The '{0}' namespace is not defined.";

	public const string Xml_EmptyName = "The empty string '' is not a valid name.";

	public const string Xml_EmptyLocalName = "The empty string '' is not a valid local name.";

	public const string Xml_InvalidNameCharsDetail = "Invalid name character in '{0}'. The '{1}' character, hexadecimal value {2}, cannot be included in a name.";

	public const string Xml_NoStartTag = "There was no XML start tag open.";

	public const string Xml_ClosedOrError = "The Writer is closed or in error state.";

	public const string Xml_WrongToken = "Token {0} in state {1} would result in an invalid XML document.";

	public const string Xml_XmlPrefix = "Prefix \"xml\" is reserved for use by XML and can be mapped only to namespace name \"http://www.w3.org/XML/1998/namespace\".";

	public const string Xml_XmlnsPrefix = "Prefix \"xmlns\" is reserved for use by XML.";

	public const string Xml_NamespaceDeclXmlXmlns = "Prefix '{0}' cannot be mapped to namespace name reserved for \"xml\" or \"xmlns\".";

	public const string Xml_NonWhitespace = "Only whitespace characters should be used.";

	public const string Xml_DupXmlDecl = "Cannot write XML declaration. WriteStartDocument method has already written it.";

	public const string Xml_CannotWriteXmlDecl = "Cannot write XML declaration. XML declaration can be only at the beginning of the document.";

	public const string Xml_NoRoot = "Document does not have a root element.";

	public const string Xml_InvalidPosition = "The current position on the Reader is neither an element nor an attribute.";

	public const string Xml_IncompleteEntity = "Incomplete entity contents.";

	public const string Xml_InvalidSurrogateHighChar = "Invalid high surrogate character (0x{0}). A high surrogate character must have a value from range (0xD800 - 0xDBFF).";

	public const string Xml_InvalidSurrogateMissingLowChar = "The surrogate pair is invalid. Missing a low surrogate character.";

	public const string Xml_InvalidSurrogatePairWithArgs = "The surrogate pair (0x{0}, 0x{1}) is invalid. A high surrogate character (0xD800 - 0xDBFF) must always be paired with a low surrogate character (0xDC00 - 0xDFFF).";

	public const string Xml_RedefinePrefix = "The prefix '{0}' cannot be redefined from '{1}' to '{2}' within the same start element tag.";

	public const string Xml_DtdAlreadyWritten = "The DTD has already been written out.";

	public const string Xml_InvalidCharsInIndent = "XmlWriterSettings.{0} can contain only valid XML text content characters when XmlWriterSettings.CheckCharacters is true. {1}";

	public const string Xml_IndentCharsNotWhitespace = "XmlWriterSettings.{0} can contain only valid XML whitespace characters when XmlWriterSettings.CheckCharacters and XmlWriterSettings.NewLineOnAttributes are true.";

	public const string Xml_ConformanceLevelFragment = "Make sure that the ConformanceLevel setting is set to ConformanceLevel.Fragment or ConformanceLevel.Auto if you want to write an XML fragment. ";

	public const string Xml_InvalidQuote = "Invalid XML attribute quote character. Valid attribute quote characters are ' and \".";

	public const string Xml_UndefPrefix = "An undefined prefix is in use.";

	public const string Xml_NoNamespaces = "Cannot set the namespace if Namespaces is 'false'.";

	public const string Xml_InvalidCDataChars = "Cannot have ']]>' inside an XML CDATA block.";

	public const string Xml_NotTheFirst = "WriteStartDocument needs to be the first call.";

	public const string Xml_InvalidPiChars = "Cannot have '?>' inside an XML processing instruction.";

	public const string Xml_InvalidNameChars = "Invalid name character in '{0}'.";

	public const string Xml_Closed = "The Writer is closed.";

	public const string Xml_InvalidPrefix = "Prefixes beginning with \"xml\" (regardless of whether the characters are uppercase, lowercase, or some combination thereof) are reserved for use by XML.";

	public const string Xml_InvalidIndentation = "Indentation value must be greater than 0.";

	public const string Xml_NotInWriteState = "NotInWriteState.";

	public const string Xml_SurrogatePairSplit = "The second character surrogate pair is not in the input buffer to be written.";

	public const string Xml_NoMultipleRoots = "Document cannot have multiple document elements.";

	public const string XmlBadName = "A node of type '{0}' cannot have the name '{1}'.";

	public const string XmlNoNameAllowed = "A node of type '{0}' cannot have a name.";

	public const string XmlConvert_BadUri = "The string was not recognized as a valid Uri.";

	public const string XmlConvert_BadFormat = "The string '{0}' is not a valid {1} value.";

	public const string XmlConvert_Overflow = "Value '{0}' was either too large or too small for {1}.";

	public const string XmlConvert_TypeBadMapping = "Xml type '{0}' does not support Clr type '{1}'.";

	public const string XmlConvert_TypeBadMapping2 = "Xml type '{0}' does not support a conversion from Clr type '{1}' to Clr type '{2}'.";

	public const string XmlConvert_TypeListBadMapping = "Xml type 'List of {0}' does not support Clr type '{1}'.";

	public const string XmlConvert_TypeListBadMapping2 = "Xml type 'List of {0}' does not support a conversion from Clr type '{1}' to Clr type '{2}'.";

	public const string XmlConvert_TypeToString = "Xml type '{0}' cannot convert from Clr type '{1}' unless the destination type is String or XmlAtomicValue.";

	public const string XmlConvert_TypeFromString = "Xml type '{0}' cannot convert to Clr type '{1}' unless the source value is a String or an XmlAtomicValue.";

	public const string XmlConvert_TypeNoPrefix = "The QName '{0}' cannot be represented as a String.  A prefix for namespace '{1}' cannot be found.";

	public const string XmlConvert_TypeNoNamespace = "The String '{0}' cannot be represented as an XmlQualifiedName.  A namespace for prefix '{1}' cannot be found.";

	public const string XmlConvert_NotOneCharString = "String must be exactly one character long.";

	public const string Sch_ParEntityRefNesting = "The parameter entity replacement text must nest properly within markup declarations.";

	public const string Sch_NotTokenString = "line-feed (#xA) or tab (#x9) characters, leading or trailing spaces and sequences of one or more spaces (#x20) are not allowed in 'xs:token'.";

	public const string Sch_InvalidDateTimeOption = "The '{0}' value for the 'dateTimeOption' parameter is not an allowed value for the 'XmlDateTimeSerializationMode' enumeration.";

	public const string Sch_StandAloneNormalization = "StandAlone is 'yes' and the value of the attribute '{0}' contains a definition in an external document that changes on normalization.";

	public const string Sch_UnSpecifiedDefaultAttributeInExternalStandalone = "Markup for unspecified default attribute '{0}' is external and standalone='yes'.";

	public const string Sch_DefaultException = "A schema error occurred.";

	public const string Sch_DupElementDecl = "The '{0}' element has already been declared.";

	public const string Sch_IdAttrDeclared = "The attribute of type ID is already declared on the '{0}' element.";

	public const string Sch_RootMatchDocType = "Root element name must match the DocType name.";

	public const string Sch_DupId = "'{0}' is already used as an ID.";

	public const string Sch_UndeclaredElement = "The '{0}' element is not declared.";

	public const string Sch_UndeclaredAttribute = "The '{0}' attribute is not declared.";

	public const string Sch_UndeclaredNotation = "The '{0}' notation is not declared.";

	public const string Sch_UndeclaredId = "Reference to undeclared ID is '{0}'.";

	public const string Sch_SchemaRootExpected = "Expected schema root. Make sure the root element is <schema> and the namespace is 'http://www.w3.org/2001/XMLSchema' for an XSD schema or 'urn:schemas-microsoft-com:xml-data' for an XDR schema.";

	public const string Sch_XSDSchemaRootExpected = "The root element of a W3C XML Schema should be <schema> and its namespace should be 'http://www.w3.org/2001/XMLSchema'.";

	public const string Sch_UnsupportedAttribute = "The '{0}' attribute is not supported in this context.";

	public const string Sch_UnsupportedElement = "The '{0}' element is not supported in this context.";

	public const string Sch_MissAttribute = "The '{0}' attribute is either invalid or missing.";

	public const string Sch_AnnotationLocation = "The 'annotation' element cannot appear at this location.";

	public const string Sch_DataTypeTextOnly = "Content must be \"textOnly\" when using DataType on an ElementType.";

	public const string Sch_UnknownModel = "The model attribute must have a value of open or closed, not '{0}'.";

	public const string Sch_UnknownOrder = "The order attribute must have a value of 'seq', 'one', or 'many', not '{0}'.";

	public const string Sch_UnknownContent = "The content attribute must have a value of 'textOnly', 'eltOnly', 'mixed', or 'empty', not '{0}'.";

	public const string Sch_UnknownRequired = "The required attribute must have a value of yes or no.";

	public const string Sch_UnknownDtType = "Reference to an unknown data type, '{0}'.";

	public const string Sch_MixedMany = "The order must be many when content is mixed.";

	public const string Sch_GroupDisabled = "The group is not allowed when ElementType has empty or textOnly content.";

	public const string Sch_MissDtvalue = "The DataType value cannot be empty.";

	public const string Sch_MissDtvaluesAttribute = "The dt:values attribute is missing.";

	public const string Sch_DupDtType = "Data type has already been declared.";

	public const string Sch_DupAttribute = "The '{0}' attribute has already been declared for this ElementType.";

	public const string Sch_RequireEnumeration = "Data type should be enumeration when the values attribute is present.";

	public const string Sch_DefaultIdValue = "An attribute or element of type xs:ID or derived from xs:ID, should not have a value constraint.";

	public const string Sch_ElementNotAllowed = "Element is not allowed when the content is empty or textOnly.";

	public const string Sch_ElementMissing = "There is a missing element.";

	public const string Sch_ManyMaxOccurs = "When the order is many, the maxOccurs attribute must have a value of '*'.";

	public const string Sch_MaxOccursInvalid = "The maxOccurs attribute must have a value of 1 or *.";

	public const string Sch_MinOccursInvalid = "The minOccurs attribute must have a value of 0 or 1.";

	public const string Sch_DtMaxLengthInvalid = "The value '{0}' is invalid for dt:maxLength.";

	public const string Sch_DtMinLengthInvalid = "The value '{0}' is invalid for dt:minLength.";

	public const string Sch_DupDtMaxLength = "The value of maxLength has already been declared.";

	public const string Sch_DupDtMinLength = "The value of minLength has already been declared.";

	public const string Sch_DtMinMaxLength = "The maxLength value must be equal to or greater than the minLength value.";

	public const string Sch_DupElement = "The '{0}' element already exists in the content model.";

	public const string Sch_DupGroupParticle = "The content model can only have one of the following; 'all', 'choice', or 'sequence'.";

	public const string Sch_InvalidValue = "The value '{0}' is invalid according to its data type.";

	public const string Sch_InvalidValueDetailed = "The value '{0}' is invalid according to its schema type '{1}' - {2}";

	public const string Sch_InvalidValueDetailedAttribute = "The attribute '{0}' has an invalid value '{1}' according to its schema type '{2}' - {3}";

	public const string Sch_MissRequiredAttribute = "The required attribute '{0}' is missing.";

	public const string Sch_FixedAttributeValue = "The value of the '{0}' attribute does not equal its fixed value.";

	public const string Sch_FixedElementValue = "The value of the '{0}' element does not equal its fixed value.";

	public const string Sch_AttributeValueDataTypeDetailed = "The '{0}' attribute is invalid - The value '{1}' is invalid according to its datatype '{2}' - {3}";

	public const string Sch_AttributeDefaultDataType = "The default value of '{0}' attribute is invalid according to its datatype.";

	public const string Sch_IncludeLocation = "The 'include' element cannot appear at this location.";

	public const string Sch_ImportLocation = "The 'import' element cannot appear at this location.";

	public const string Sch_RedefineLocation = "The 'redefine' element cannot appear at this location.";

	public const string Sch_InvalidBlockDefaultValue = "The values 'list' and 'union' are invalid for the blockDefault attribute.";

	public const string Sch_InvalidFinalDefaultValue = "The value 'substitution' is invalid for the finalDefault attribute.";

	public const string Sch_InvalidElementBlockValue = "The values 'list' and 'union' are invalid for the block attribute on element.";

	public const string Sch_InvalidElementFinalValue = "The values 'substitution', 'list', and 'union' are invalid for the final attribute on element.";

	public const string Sch_InvalidSimpleTypeFinalValue = "The values 'substitution' and 'extension' are invalid for the final attribute on simpleType.";

	public const string Sch_InvalidComplexTypeBlockValue = "The values 'substitution', 'list', and 'union' are invalid for the block attribute on complexType.";

	public const string Sch_InvalidComplexTypeFinalValue = "The values 'substitution', 'list', and 'union' are invalid for the final attribute on complexType.";

	public const string Sch_DupIdentityConstraint = "The identity constraint '{0}' has already been declared.";

	public const string Sch_DupGlobalElement = "The global element '{0}' has already been declared.";

	public const string Sch_DupGlobalAttribute = "The global attribute '{0}' has already been declared.";

	public const string Sch_DupSimpleType = "The simpleType '{0}' has already been declared.";

	public const string Sch_DupComplexType = "The complexType '{0}' has already been declared.";

	public const string Sch_DupGroup = "The group '{0}' has already been declared.";

	public const string Sch_DupAttributeGroup = "The attributeGroup '{0}' has already been declared.";

	public const string Sch_DupNotation = "The notation '{0}' has already been declared.";

	public const string Sch_DefaultFixedAttributes = "The fixed and default attributes cannot both be present.";

	public const string Sch_FixedInRef = "The fixed value constraint on the '{0}' attribute reference must match the fixed value constraint on the declaration.";

	public const string Sch_FixedDefaultInRef = "The default value constraint cannot be present on the '{0}' attribute reference if the fixed value constraint is present on the declaration.";

	public const string Sch_DupXsdElement = "'{0}' is a duplicate XSD element.";

	public const string Sch_ForbiddenAttribute = "The '{0}' attribute cannot be present.";

	public const string Sch_AttributeIgnored = "The '{0}' attribute is ignored, because the value of 'prohibited' for attribute use only prevents inheritance of an identically named attribute from the base type definition.";

	public const string Sch_ElementRef = "When the ref attribute is present, the type attribute and complexType, simpleType, key, keyref, and unique elements cannot be present.";

	public const string Sch_TypeMutualExclusive = "The type attribute cannot be present with either simpleType or complexType.";

	public const string Sch_ElementNameRef = "For element declaration, either the name or the ref attribute must be present.";

	public const string Sch_AttributeNameRef = "For attribute '{0}', either the name or the ref attribute must be present, but not both.";

	public const string Sch_TextNotAllowed = "The following text is not allowed in this context: '{0}'.";

	public const string Sch_UndeclaredType = "Type '{0}' is not declared.";

	public const string Sch_UndeclaredSimpleType = "Type '{0}' is not declared, or is not a simple type.";

	public const string Sch_UndeclaredEquivClass = "Substitution group refers to '{0}', an undeclared element.";

	public const string Sch_AttListPresence = "An attribute of type ID must have a declared default of either #IMPLIED or #REQUIRED.";

	public const string Sch_NotationValue = "'{0}' is not in the notation list.";

	public const string Sch_EnumerationValue = "'{0}' is not in the enumeration list.";

	public const string Sch_EmptyAttributeValue = "The attribute value cannot be empty.";

	public const string Sch_InvalidLanguageId = "'{0}' is an invalid language identifier.";

	public const string Sch_XmlSpace = "Invalid xml:space syntax.";

	public const string Sch_InvalidXsdAttributeValue = "'{1}' is an invalid value for the '{0}' attribute.";

	public const string Sch_InvalidXsdAttributeDatatypeValue = "The value for the '{0}' attribute is invalid - {1}";

	public const string Sch_ElementValueDataTypeDetailed = "The '{0}' element is invalid - The value '{1}' is invalid according to its datatype '{2}' - {3}";

	public const string Sch_InvalidElementDefaultValue = "The default value '{0}' of element '{1}' is invalid according to the type specified by xsi:type.";

	public const string Sch_NonDeterministic = "Multiple definition of element '{0}' causes the content model to become ambiguous. A content model must be formed such that during validation of an element information item sequence, the particle contained directly, indirectly or implicitly therein with which to attempt to validate each item in the sequence in turn can be uniquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence.";

	public const string Sch_NonDeterministicAnyEx = "Wildcard '{0}' allows element '{1}', and causes the content model to become ambiguous. A content model must be formed such that during validation of an element information item sequence, the particle contained directly, indirectly or implicitly therein with which to attempt to validate each item in the sequence in turn can be uniquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence.";

	public const string Sch_NonDeterministicAnyAny = "Wildcards '{0}' and '{1}' have not empty intersection, and causes the content model to become ambiguous. A content model must be formed such that during validation of an element information item sequence, the particle contained directly, indirectly or implicitly therein with which to attempt to validate each item in the sequence in turn can be uniquely determined without examining the content or attributes of that item, and without any information about the items in the remainder of the sequence.";

	public const string Sch_StandAlone = "The standalone document declaration must have a value of 'no'.";

	public const string Sch_XmlNsAttribute = "The value 'xmlns' cannot be used as the name of an attribute declaration.";

	public const string Sch_AllElement = "Element '{0}' cannot appear more than once if content model type is \"all\".";

	public const string Sch_MismatchTargetNamespaceInclude = "The targetNamespace '{0}' of included/redefined schema should be the same as the targetNamespace '{1}' of the including schema.";

	public const string Sch_MismatchTargetNamespaceImport = "The namespace attribute '{0}' of an import should be the same value as the targetNamespace '{1}' of the imported schema.";

	public const string Sch_MismatchTargetNamespaceEx = "The targetNamespace parameter '{0}' should be the same value as the targetNamespace '{1}' of the schema.";

	public const string Sch_XsiTypeNotFound = "This is an invalid xsi:type '{0}'.";

	public const string Sch_XsiTypeAbstract = "The xsi:type '{0}' cannot be abstract.";

	public const string Sch_ListFromNonatomic = "A list data type must be derived from an atomic or union data type.";

	public const string Sch_UnionFromUnion = "It is an error if a union type has a member with variety union and this member cannot be substituted with its own members. This may be due to the fact that the union member is a restriction of a union with facets.";

	public const string Sch_DupLengthFacet = "This is a duplicate Length constraining facet.";

	public const string Sch_DupMinLengthFacet = "This is a duplicate MinLength constraining facet.";

	public const string Sch_DupMaxLengthFacet = "This is a duplicate MaxLength constraining facet.";

	public const string Sch_DupWhiteSpaceFacet = "This is a duplicate WhiteSpace constraining facet.";

	public const string Sch_DupMaxInclusiveFacet = "This is a duplicate MaxInclusive constraining facet.";

	public const string Sch_DupMaxExclusiveFacet = "This is a duplicate MaxExclusive constraining facet.";

	public const string Sch_DupMinInclusiveFacet = "This is a duplicate MinInclusive constraining facet.";

	public const string Sch_DupMinExclusiveFacet = "This is a duplicate MinExclusive constraining facet.";

	public const string Sch_DupTotalDigitsFacet = "This is a duplicate TotalDigits constraining facet.";

	public const string Sch_DupFractionDigitsFacet = "This is a duplicate FractionDigits constraining facet.";

	public const string Sch_LengthFacetProhibited = "The length constraining facet is prohibited for '{0}'.";

	public const string Sch_MinLengthFacetProhibited = "The MinLength constraining facet is prohibited for '{0}'.";

	public const string Sch_MaxLengthFacetProhibited = "The MaxLength constraining facet is prohibited for '{0}'.";

	public const string Sch_PatternFacetProhibited = "The Pattern constraining facet is prohibited for '{0}'.";

	public const string Sch_EnumerationFacetProhibited = "The Enumeration constraining facet is prohibited for '{0}'.";

	public const string Sch_WhiteSpaceFacetProhibited = "The WhiteSpace constraining facet is prohibited for '{0}'.";

	public const string Sch_MaxInclusiveFacetProhibited = "The MaxInclusive constraining facet is prohibited for '{0}'.";

	public const string Sch_MaxExclusiveFacetProhibited = "The MaxExclusive constraining facet is prohibited for '{0}'.";

	public const string Sch_MinInclusiveFacetProhibited = "The MinInclusive constraining facet is prohibited for '{0}'.";

	public const string Sch_MinExclusiveFacetProhibited = "The MinExclusive constraining facet is prohibited for '{0}'.";

	public const string Sch_TotalDigitsFacetProhibited = "The TotalDigits constraining facet is prohibited for '{0}'.";

	public const string Sch_FractionDigitsFacetProhibited = "The FractionDigits constraining facet is prohibited for '{0}'.";

	public const string Sch_LengthFacetInvalid = "The Length constraining facet is invalid - {0}";

	public const string Sch_MinLengthFacetInvalid = "The MinLength constraining facet is invalid - {0}";

	public const string Sch_MaxLengthFacetInvalid = "The MaxLength constraining facet is invalid - {0}";

	public const string Sch_MaxInclusiveFacetInvalid = "The MaxInclusive constraining facet is invalid - {0}";

	public const string Sch_MaxExclusiveFacetInvalid = "The MaxExclusive constraining facet is invalid - {0}";

	public const string Sch_MinInclusiveFacetInvalid = "The MinInclusive constraining facet is invalid - {0}";

	public const string Sch_MinExclusiveFacetInvalid = "The MinExclusive constraining facet is invalid - {0}";

	public const string Sch_TotalDigitsFacetInvalid = "The TotalDigits constraining facet is invalid - {0}";

	public const string Sch_FractionDigitsFacetInvalid = "The FractionDigits constraining facet is invalid - {0}";

	public const string Sch_PatternFacetInvalid = "The Pattern constraining facet is invalid - {0}";

	public const string Sch_EnumerationFacetInvalid = "The Enumeration constraining facet is invalid - {0}";

	public const string Sch_InvalidWhiteSpace = "The whitespace character, '{0}', is invalid.";

	public const string Sch_UnknownFacet = "This is an unknown facet.";

	public const string Sch_LengthAndMinMax = "It is an error for both length and minLength or maxLength to be present.";

	public const string Sch_MinLengthGtMaxLength = "MinLength is greater than MaxLength.";

	public const string Sch_FractionDigitsGtTotalDigits = "FractionDigits is greater than TotalDigits.";

	public const string Sch_LengthConstraintFailed = "The actual length is not equal to the specified length.";

	public const string Sch_MinLengthConstraintFailed = "The actual length is less than the MinLength value.";

	public const string Sch_MaxLengthConstraintFailed = "The actual length is greater than the MaxLength value.";

	public const string Sch_PatternConstraintFailed = "The Pattern constraint failed.";

	public const string Sch_EnumerationConstraintFailed = "The Enumeration constraint failed.";

	public const string Sch_MaxInclusiveConstraintFailed = "The MaxInclusive constraint failed.";

	public const string Sch_MaxExclusiveConstraintFailed = "The MaxExclusive constraint failed.";

	public const string Sch_MinInclusiveConstraintFailed = "The MinInclusive constraint failed.";

	public const string Sch_MinExclusiveConstraintFailed = "The MinExclusive constraint failed.";

	public const string Sch_TotalDigitsConstraintFailed = "The TotalDigits constraint failed.";

	public const string Sch_FractionDigitsConstraintFailed = "The FractionDigits constraint failed.";

	public const string Sch_UnionFailedEx = "The value '{0}' is not valid according to any of the memberTypes of the union.";

	public const string Sch_NotationRequired = "NOTATION cannot be used directly in a schema; only data types derived from NOTATION by specifying an enumeration value can be used in a schema. All enumeration facet values must match the name of a notation declared in the current schema.";

	public const string Sch_DupNotationAttribute = "No element type can have more than one NOTATION attribute specified.";

	public const string Sch_MissingPublicSystemAttribute = "NOTATION must have either the Public or System attribute present.";

	public const string Sch_NotationAttributeOnEmptyElement = "An attribute of type NOTATION must not be declared on an element declared EMPTY.";

	public const string Sch_RefNotInScope = "The Keyref '{0}' cannot find the referred key or unique in scope.";

	public const string Sch_UndeclaredIdentityConstraint = "The '{0}' identity constraint is not declared.";

	public const string Sch_RefInvalidIdentityConstraint = "Reference to an invalid identity constraint, '{0}'.";

	public const string Sch_RefInvalidCardin = "Keyref '{0}' has different cardinality as the referred key or unique element.";

	public const string Sch_ReftoKeyref = "The '{0}' Keyref can refer to key or unique only.";

	public const string Sch_EmptyXPath = "The XPath for selector or field cannot be empty.";

	public const string Sch_UnresolvedPrefix = "The prefix '{0}' in XPath cannot be resolved.";

	public const string Sch_UnresolvedKeyref = "The key sequence '{0}' in '{1}' Keyref fails to refer to some key.";

	public const string Sch_ICXpathError = "'{0}' is an invalid XPath for selector or field.";

	public const string Sch_SelectorAttr = "'{0}' is an invalid XPath for selector. Selector cannot have an XPath selection with an attribute node.";

	public const string Sch_FieldSimpleTypeExpected = "The field '{0}' is expecting an element or attribute with simple type or simple content.";

	public const string Sch_FieldSingleValueExpected = "The field '{0}' is expecting at the most one value.";

	public const string Sch_MissingKey = "The identity constraint '{0}' validation has failed. Either a key is missing or the existing key has an empty node.";

	public const string Sch_DuplicateKey = "There is a duplicate key sequence '{0}' for the '{1}' key or unique identity constraint.";

	public const string Sch_TargetNamespaceXsi = "The target namespace of an attribute declaration, whether local or global, must not match http://www.w3.org/2001/XMLSchema-instance.";

	public const string Sch_UndeclaredEntity = "Reference to an undeclared entity, '{0}'.";

	public const string Sch_UnparsedEntityRef = "Reference to an unparsed entity, '{0}'.";

	public const string Sch_MaxOccursInvalidXsd = "The value for the 'maxOccurs' attribute must be xsd:nonNegativeInteger or 'unbounded'.";

	public const string Sch_MinOccursInvalidXsd = "The value for the 'minOccurs' attribute must be xsd:nonNegativeInteger.";

	public const string Sch_MaxInclusiveExclusive = "'maxInclusive' and 'maxExclusive' cannot both be specified for the same data type.";

	public const string Sch_MinInclusiveExclusive = "'minInclusive' and 'minExclusive' cannot both be specified for the same data type.";

	public const string Sch_MinInclusiveGtMaxInclusive = "The value specified for 'minInclusive' cannot be greater than the value specified for 'maxInclusive' for the same data type.";

	public const string Sch_MinExclusiveGtMaxExclusive = "The value specified for 'minExclusive' cannot be greater than the value specified for 'maxExclusive' for the same data type.";

	public const string Sch_MinInclusiveGtMaxExclusive = "The value specified for 'minInclusive' cannot be greater than the value specified for 'maxExclusive' for the same data type.";

	public const string Sch_MinExclusiveGtMaxInclusive = "The value specified for 'minExclusive' cannot be greater than the value specified for 'maxInclusive' for the same data type.";

	public const string Sch_SimpleTypeRestriction = "'simpleType' should be the first child of restriction.";

	public const string Sch_InvalidFacetPosition = "Facet should go before 'attribute', 'attributeGroup', or 'anyAttribute'.";

	public const string Sch_AttributeMutuallyExclusive = "'{0}' and content model are mutually exclusive.";

	public const string Sch_AnyAttributeLastChild = "'anyAttribute' must be the last child.";

	public const string Sch_ComplexTypeContentModel = "The content model of a complex type must consist of 'annotation' (if present); followed by zero or one of the following: 'simpleContent', 'complexContent', 'group', 'choice', 'sequence', or 'all'; followed by zero or more 'attribute' or 'attributeGroup'; followed by zero or one 'anyAttribute'.";

	public const string Sch_ComplexContentContentModel = "Complex content restriction or extension should consist of zero or one of 'group', 'choice', 'sequence', or 'all'; followed by zero or more 'attribute' or 'attributeGroup'; followed by zero or one 'anyAttribute'.";

	public const string Sch_NotNormalizedString = "Carriage return (#xD), line feed (#xA), and tab (#x9) characters are not allowed in xs:normalizedString.";

	public const string Sch_FractionDigitsNotOnDecimal = "FractionDigits should be equal to 0 on types other then decimal.";

	public const string Sch_ContentInNill = "Element '{0}' must have no character or element children.";

	public const string Sch_NoElementSchemaFound = "Could not find schema information for the element '{0}'.";

	public const string Sch_NoAttributeSchemaFound = "Could not find schema information for the attribute '{0}'.";

	public const string Sch_InvalidNamespace = "The Namespace '{0}' is an invalid URI.";

	public const string Sch_InvalidTargetNamespaceAttribute = "The targetNamespace attribute cannot have empty string as its value.";

	public const string Sch_InvalidNamespaceAttribute = "The namespace attribute cannot have empty string as its value.";

	public const string Sch_InvalidSchemaLocation = "The SchemaLocation '{0}' is an invalid URI.";

	public const string Sch_ImportTargetNamespace = "Namespace attribute of an import must not match the real value of the enclosing targetNamespace of the <schema>.";

	public const string Sch_ImportTargetNamespaceNull = "The enclosing <schema> must have a targetNamespace, if the Namespace attribute is absent on the import element.";

	public const string Sch_GroupDoubleRedefine = "Double redefine for group.";

	public const string Sch_ComponentRedefineNotFound = "Cannot find a {0} with name '{1}' to redefine.";

	public const string Sch_GroupRedefineNotFound = "No group to redefine.";

	public const string Sch_AttrGroupDoubleRedefine = "Double redefine for attribute group.";

	public const string Sch_AttrGroupRedefineNotFound = "No attribute group to redefine.";

	public const string Sch_ComplexTypeDoubleRedefine = "Double redefine for complex type.";

	public const string Sch_ComplexTypeRedefineNotFound = "No complex type to redefine.";

	public const string Sch_SimpleToComplexTypeRedefine = "Cannot redefine a simple type as complex type.";

	public const string Sch_SimpleTypeDoubleRedefine = "Double redefine for simple type.";

	public const string Sch_ComplexToSimpleTypeRedefine = "Cannot redefine a complex type as simple type.";

	public const string Sch_SimpleTypeRedefineNotFound = "No simple type to redefine.";

	public const string Sch_MinMaxGroupRedefine = "When group is redefined, the real value of both minOccurs and maxOccurs attribute must be 1 (or absent).";

	public const string Sch_MultipleGroupSelfRef = "Multiple self-reference within a group is redefined.";

	public const string Sch_MultipleAttrGroupSelfRef = "Multiple self-reference within an attribute group is redefined.";

	public const string Sch_InvalidTypeRedefine = "If type is being redefined, the base type has to be self-referenced.";

	public const string Sch_InvalidElementRef = "If ref is present, all of <complexType>, <simpleType>, <key>, <keyref>, <unique>, nillable, default, fixed, form, block, and type must be absent.";

	public const string Sch_MinGtMax = "minOccurs value cannot be greater than maxOccurs value.";

	public const string Sch_DupSelector = "Selector cannot appear twice in one identity constraint.";

	public const string Sch_IdConstraintNoSelector = "Selector must be present.";

	public const string Sch_IdConstraintNoFields = "At least one field must be present.";

	public const string Sch_IdConstraintNoRefer = "The referring attribute must be present.";

	public const string Sch_SelectorBeforeFields = "Cannot define fields before selector.";

	public const string Sch_NoSimpleTypeContent = "SimpleType content is missing.";

	public const string Sch_SimpleTypeRestRefBase = "SimpleType restriction should have either the base attribute or a simpleType child, but not both.";

	public const string Sch_SimpleTypeRestRefBaseNone = "SimpleType restriction should have either the base attribute or a simpleType child to indicate the base type for the derivation.";

	public const string Sch_SimpleTypeListRefBase = "SimpleType list should have either the itemType attribute or a simpleType child, but not both.";

	public const string Sch_SimpleTypeListRefBaseNone = "SimpleType list should have either the itemType attribute or a simpleType child to indicate the itemType of the list. ";

	public const string Sch_SimpleTypeUnionNoBase = "Either the memberTypes attribute must be non-empty or there must be at least one simpleType child.";

	public const string Sch_NoRestOrExtQName = "'restriction' or 'extension' child is required for complexType '{0}' in namespace '{1}', because it has a simpleContent or complexContent child.";

	public const string Sch_NoRestOrExt = "'restriction' or 'extension' child is required for complexType with simpleContent or complexContent child.";

	public const string Sch_NoGroupParticle = "'sequence', 'choice', or 'all' child is required.";

	public const string Sch_InvalidAllMin = "'all' must have 'minOccurs' value of 0 or 1.";

	public const string Sch_InvalidAllMax = "'all' must have {max occurs}=1.";

	public const string Sch_InvalidFacet = "The 'value' attribute must be present in facet.";

	public const string Sch_AbstractElement = "The element '{0}' is abstract or its type is abstract.";

	public const string Sch_XsiTypeBlockedEx = "The xsi:type attribute value '{0}' is not valid for the element '{1}', either because it is not a type validly derived from the type in the schema, or because it has xsi:type derivation blocked.";

	public const string Sch_InvalidXsiNill = "If the 'nillable' attribute is false in the schema, the 'xsi:nil' attribute must not be present in the instance.";

	public const string Sch_SubstitutionNotAllowed = "Element '{0}' cannot substitute in place of head element '{1}' because it has block='substitution'.";

	public const string Sch_SubstitutionBlocked = "Member element {0}'s type cannot be derived by restriction or extension from head element {1}'s type, because it has block='restriction' or 'extension'.";

	public const string Sch_InvalidElementInEmptyEx = "The element '{0}' cannot contain child element '{1}' because the parent element's content model is empty.";

	public const string Sch_InvalidElementInTextOnlyEx = "The element '{0}' cannot contain child element '{1}' because the parent element's content model is text only.";

	public const string Sch_InvalidTextInElement = "The element {0} cannot contain text.";

	public const string Sch_InvalidElementContent = "The element {0} has invalid child element {1}.";

	public const string Sch_InvalidElementContentComplex = "The element {0} has invalid child element {1} - {2}";

	public const string Sch_IncompleteContent = "The element {0} has incomplete content.";

	public const string Sch_IncompleteContentComplex = "The element {0} has incomplete content - {2}";

	public const string Sch_InvalidTextInElementExpecting = "The element {0} cannot contain text. List of possible elements expected: {1}.";

	public const string Sch_InvalidElementContentExpecting = "The element {0} has invalid child element {1}. List of possible elements expected: {2}.";

	public const string Sch_InvalidElementContentExpectingComplex = "The element {0} has invalid child element {1}. List of possible elements expected: {2}. {3}";

	public const string Sch_IncompleteContentExpecting = "The element {0} has incomplete content. List of possible elements expected: {1}.";

	public const string Sch_IncompleteContentExpectingComplex = "The element {0} has incomplete content. List of possible elements expected: {1}. {2}";

	public const string Sch_InvalidElementSubstitution = "The element {0} cannot substitute for a local element {1} expected in that position.";

	public const string Sch_ElementNameAndNamespace = "'{0}' in namespace '{1}'";

	public const string Sch_ElementName = "'{0}'";

	public const string Sch_ContinuationString = "{0}as well as ";

	public const string Sch_AnyElementNS = "any element in namespace '{0}'";

	public const string Sch_AnyElement = "any element";

	public const string Sch_InvalidTextInEmpty = "The element cannot contain text. Content model is empty.";

	public const string Sch_InvalidWhitespaceInEmpty = "The element cannot contain whitespace. Content model is empty.";

	public const string Sch_InvalidPIComment = "The element cannot contain comment or processing instruction. Content model is empty.";

	public const string Sch_InvalidAttributeRef = "If ref is present, all of 'simpleType', 'form', 'type', and 'use' must be absent.";

	public const string Sch_OptionalDefaultAttribute = "The 'use' attribute must be optional (or absent) if the default attribute is present.";

	public const string Sch_AttributeCircularRef = "Circular attribute reference.";

	public const string Sch_IdentityConstraintCircularRef = "Circular identity constraint reference.";

	public const string Sch_SubstitutionCircularRef = "Circular substitution group affiliation.";

	public const string Sch_InvalidAnyAttribute = "Invalid namespace in 'anyAttribute'.";

	public const string Sch_DupIdAttribute = "Duplicate ID attribute.";

	public const string Sch_InvalidAllElementMax = "The {max occurs} of all the particles in the {particles} of an all group must be 0 or 1.";

	public const string Sch_InvalidAny = "Invalid namespace in 'any'.";

	public const string Sch_InvalidAnyDetailed = "The value of the namespace attribute of the element or attribute wildcard is invalid - {0}";

	public const string Sch_InvalidExamplar = "Cannot be nominated as the {substitution group affiliation} of any other declaration.";

	public const string Sch_NoExamplar = "Reference to undeclared substitution group affiliation.";

	public const string Sch_InvalidSubstitutionMember = "'{0}' cannot be a member of substitution group with head element '{1}'.";

	public const string Sch_RedefineNoSchema = "'SchemaLocation' must successfully resolve if <redefine> contains any child other than <annotation>.";

	public const string Sch_ProhibitedAttribute = "The '{0}' attribute is not allowed.";

	public const string Sch_TypeCircularRef = "Circular type reference.";

	public const string Sch_TwoIdAttrUses = "Two distinct members of the attribute uses must not have type definitions which are both xs:ID or are derived from xs:ID.";

	public const string Sch_AttrUseAndWildId = "It is an error if there is a member of the attribute uses of a type definition with type xs:ID or derived from xs:ID and another attribute with type xs:ID matches an attribute wildcard.";

	public const string Sch_MoreThanOneWildId = "It is an error if more than one attribute whose type is xs:ID or is derived from xs:ID, matches an attribute wildcard on an element.";

	public const string Sch_BaseFinalExtension = "The base type is the final extension.";

	public const string Sch_NotSimpleContent = "The content type of the base type must be a simple type definition or it must be mixed, and simpleType child must be present.";

	public const string Sch_NotComplexContent = "The content type of the base type must not be a simple type definition.";

	public const string Sch_BaseFinalRestriction = "The base type is final restriction.";

	public const string Sch_BaseFinalList = "The base type is the final list.";

	public const string Sch_BaseFinalUnion = "The base type is the final union.";

	public const string Sch_UndefBaseRestriction = "Undefined complexType '{0}' is used as a base for complex type restriction.";

	public const string Sch_UndefBaseExtension = "Undefined complexType '{0}' is used as a base for complex type extension.";

	public const string Sch_DifContentType = "The derived type and the base type must have the same content type.";

	public const string Sch_InvalidContentRestriction = "Invalid content type derivation by restriction.";

	public const string Sch_InvalidContentRestrictionDetailed = "Invalid content type derivation by restriction. {0}";

	public const string Sch_InvalidBaseToEmpty = "If the derived content type is Empty, then the base content type should also be Empty or Mixed with Emptiable particle according to rule 5.3 of Schema Component Constraint: Derivation Valid (Restriction, Complex).";

	public const string Sch_InvalidBaseToMixed = "If the derived content type is Mixed, then the base content type should also be Mixed according to rule 5.4 of Schema Component Constraint: Derivation Valid (Restriction, Complex).";

	public const string Sch_DupAttributeUse = "The attribute '{0}' already exists.";

	public const string Sch_InvalidParticleRestriction = "Invalid particle derivation by restriction.";

	public const string Sch_InvalidParticleRestrictionDetailed = "Invalid particle derivation by restriction - '{0}'.";

	public const string Sch_ForbiddenDerivedParticleForAll = "'Choice' or 'any' is forbidden as derived particle when the base particle is 'all'.";

	public const string Sch_ForbiddenDerivedParticleForElem = "Only 'element' is valid as derived particle when the base particle is 'element'.";

	public const string Sch_ForbiddenDerivedParticleForChoice = "'All' or 'any' is forbidden as derived particle when the base particle is 'choice'.";

	public const string Sch_ForbiddenDerivedParticleForSeq = "'All', 'any', and 'choice' are forbidden as derived particles when the base particle is 'sequence'.";

	public const string Sch_ElementFromElement = "Derived element '{0}' is not a valid restriction of base element '{1}' according to Elt:Elt -- NameAndTypeOK.";

	public const string Sch_ElementFromAnyRule1 = "The namespace of element '{0}'is not valid with respect to the wildcard's namespace constraint in the base, Elt:Any -- NSCompat Rule 1.";

	public const string Sch_ElementFromAnyRule2 = "The occurrence range of element '{0}'is not a valid restriction of the wildcard's occurrence range in the base, Elt:Any -- NSCompat Rule2.";

	public const string Sch_AnyFromAnyRule1 = "The derived wildcard's occurrence range is not a valid restriction of the base wildcard's occurrence range, Any:Any -- NSSubset Rule 1.";

	public const string Sch_AnyFromAnyRule2 = "The derived wildcard's namespace constraint must be an intensional subset of the base wildcard's namespace constraint, Any:Any -- NSSubset Rule2.";

	public const string Sch_AnyFromAnyRule3 = "The derived wildcard's 'processContents' must be identical to or stronger than the base wildcard's 'processContents', where 'strict' is stronger than 'lax' and 'lax' is stronger than 'skip', Any:Any -- NSSubset Rule 3.";

	public const string Sch_GroupBaseFromAny1 = "Every member of the derived group particle must be a valid restriction of the base wildcard, NSRecurseCheckCardinality Rule 1.";

	public const string Sch_GroupBaseFromAny2 = "The derived particle's occurrence range at ({0}, {1}) is not a valid restriction of the base wildcard's occurrence range at ({2}, {3}), NSRecurseCheckCardinality Rule 2.";

	public const string Sch_ElementFromGroupBase1 = "The derived element {0} at ({1}, {2}) is not a valid restriction of the base sequence particle at ({3}, {4}) according to Elt:All/Choice/Sequence -- RecurseAsIfGroup.";

	public const string Sch_ElementFromGroupBase2 = "The derived element {0} at ({1}, {2}) is not a valid restriction of the base choice particle at ({3}, {4}) according to Elt:All/Choice/Sequence -- RecurseAsIfGroup.";

	public const string Sch_ElementFromGroupBase3 = "The derived element {0} at ({1}, {2}) is not a valid restriction of the base all particle at ({3}, {4}) according to Elt:All/Choice/Sequence -- RecurseAsIfGroup.";

	public const string Sch_GroupBaseRestRangeInvalid = "The derived particle's range is not a valid restriction of the base particle's range according to All:All,Sequence:Sequence -- Recurse Rule 1 or Choice:Choice -- RecurseLax.";

	public const string Sch_GroupBaseRestNoMap = "The derived particle cannot have more members than the base particle - All:All,Sequence:Sequence -- Recurse Rule 2 / Choice:Choice -- RecurseLax.";

	public const string Sch_GroupBaseRestNotEmptiable = "All particles in the {particles} of the base particle which are not mapped to by any particle in the {particles} of the derived particle should be emptiable - All:All,Sequence:Sequence -- Recurse Rule 2 / Choice:Choice -- RecurseLax.";

	public const string Sch_SeqFromAll = "The derived sequence particle at ({0}, {1}) is not a valid restriction of the base all particle at ({2}, {3}) according to Sequence:All -- RecurseUnordered.";

	public const string Sch_SeqFromChoice = "The derived sequence particle at ({0}, {1}) is not a valid restriction of the base choice particle at ({2}, {3}) according to Sequence:Choice -- MapAndSum.";

	public const string Sch_UndefGroupRef = "Reference to undeclared model group '{0}'.";

	public const string Sch_GroupCircularRef = "Circular group reference.";

	public const string Sch_AllRefNotRoot = "The group ref to 'all' is not the root particle, or it is being used as an extension.";

	public const string Sch_AllRefMinMax = "The group ref to 'all' must have {min occurs}= 0 or 1 and {max occurs}=1.";

	public const string Sch_NotAllAlone = "'all' is not the only particle in a group, or is being used as an extension.";

	public const string Sch_AttributeGroupCircularRef = "Circular attribute group reference.";

	public const string Sch_UndefAttributeGroupRef = "Reference to undeclared attribute group '{0}'.";

	public const string Sch_InvalidAttributeExtension = "Invalid attribute extension.";

	public const string Sch_InvalidAnyAttributeRestriction = "The base any attribute must be a superset of the derived 'anyAttribute'.";

	public const string Sch_AttributeRestrictionProhibited = "Invalid attribute restriction. Attribute restriction is prohibited in base type.";

	public const string Sch_AttributeRestrictionInvalid = "Invalid attribute restriction. Derived attribute's type is not a valid restriction of the base attribute's type.";

	public const string Sch_AttributeFixedInvalid = "Invalid attribute restriction. Derived attribute's fixed value must be the same as the base attribute's fixed value. ";

	public const string Sch_AttributeUseInvalid = "Derived attribute's use has to be required if base attribute's use is required.";

	public const string Sch_AttributeRestrictionInvalidFromWildcard = "The {base type definition} must have an {attribute wildcard} and the {target namespace} of the R's {attribute declaration} must be valid with respect to that wildcard.";

	public const string Sch_NoDerivedAttribute = "The base attribute '{0}' whose use = 'required' does not have a corresponding derived attribute while redefining attribute group '{1}'.";

	public const string Sch_UnexpressibleAnyAttribute = "The 'anyAttribute' is not expressible.";

	public const string Sch_RefInvalidAttribute = "Reference to invalid attribute '{0}'.";

	public const string Sch_ElementCircularRef = "Circular element reference.";

	public const string Sch_RefInvalidElement = "Reference to invalid element '{0}'.";

	public const string Sch_ElementCannotHaveValue = "Element's type does not allow fixed or default value constraint.";

	public const string Sch_ElementInMixedWithFixed = "Although the '{0}' element's content type is mixed, it cannot have element children, because it has a fixed value constraint in the schema.";

	public const string Sch_ElementTypeCollision = "Elements with the same name and in the same scope must have the same type.";

	public const string Sch_InvalidIncludeLocation = "Cannot resolve the 'schemaLocation' attribute.";

	public const string Sch_CannotLoadSchema = "Cannot load the schema for the namespace '{0}' - {1}";

	public const string Sch_CannotLoadSchemaLocation = "Cannot load the schema from the location '{0}' - {1}";

	public const string Sch_LengthGtBaseLength = "It is an error if 'length' is among the members of {facets} of {base type definition} and {value} is greater than the {value} of the parent 'length'.";

	public const string Sch_MinLengthGtBaseMinLength = "It is an error if 'minLength' is among the members of {facets} of {base type definition} and {value} is less than the {value} of the parent 'minLength'.";

	public const string Sch_MaxLengthGtBaseMaxLength = "It is an error if 'maxLength' is among the members of {facets} of {base type definition} and {value} is greater than the {value} of the parent 'maxLength'.";

	public const string Sch_MaxMinLengthBaseLength = "It is an error for both 'length' and either 'minLength' or 'maxLength' to be members of {facets}, unless they are specified in different derivation steps. In which case the following must be true: the {value} of 'minLength' <= the {value} of 'length' <= the {value} of 'maxLength'.";

	public const string Sch_MaxInclusiveMismatch = "It is an error if the derived 'maxInclusive' facet value is greater than the parent 'maxInclusive' facet value.";

	public const string Sch_MaxExclusiveMismatch = "It is an error if the derived 'maxExclusive' facet value is greater than the parent 'maxExclusive' facet value.";

	public const string Sch_MinInclusiveMismatch = "It is an error if the derived 'minInclusive' facet value is less than the parent 'minInclusive' facet value.";

	public const string Sch_MinExclusiveMismatch = "It is an error if the derived 'minExclusive' facet value is less than the parent 'minExclusive' facet value.";

	public const string Sch_MinExlIncMismatch = "It is an error if the derived 'minExclusive' facet value is less than or equal to the parent 'minInclusive' facet value.";

	public const string Sch_MinExlMaxExlMismatch = "It is an error if the derived 'minExclusive' facet value is greater than or equal to the parent 'maxExclusive' facet value.";

	public const string Sch_MinIncMaxExlMismatch = "It is an error if the derived 'minInclusive' facet value is greater than or equal to the parent 'maxExclusive' facet value.";

	public const string Sch_MinIncExlMismatch = "It is an error if the derived 'minInclusive' facet value is less than or equal to the parent 'minExclusive' facet value.";

	public const string Sch_MaxIncExlMismatch = "It is an error if the derived 'maxInclusive' facet value is greater than or equal to the parent 'maxExclusive' facet value.";

	public const string Sch_MaxExlIncMismatch = "It is an error if the derived 'maxExclusive' facet value is greater than or equal to the parent 'maxInclusive' facet value.";

	public const string Sch_TotalDigitsMismatch = "It is an error if the derived 'totalDigits' facet value is greater than the parent 'totalDigits' facet value.";

	public const string Sch_FacetBaseFixed = "Values that are declared as {fixed} in a base type can not be changed in a derived type.";

	public const string Sch_WhiteSpaceRestriction1 = "It is an error if 'whiteSpace' is among the members of {facets} of {base type definition}, {value} is 'replace' or 'preserve', and the {value} of the parent 'whiteSpace' is 'collapse'.";

	public const string Sch_WhiteSpaceRestriction2 = "It is an error if 'whiteSpace' is among the members of {facets} of {base type definition}, {value} is 'preserve', and the {value} of the parent 'whiteSpace' is 'replace'.";

	public const string Sch_XsiNilAndFixed = "There must be no fixed value when an attribute is 'xsi:nil' and has a value of 'true'.";

	public const string Sch_MixSchemaTypes = "Different schema types cannot be mixed.";

	public const string Sch_XSDSchemaOnly = "'XmlSchemaSet' can load only W3C XML Schemas.";

	public const string Sch_InvalidPublicAttribute = "Public attribute '{0}' is an invalid URI.";

	public const string Sch_InvalidSystemAttribute = "System attribute '{0}' is an invalid URI.";

	public const string Sch_TypeAfterConstraints = "'simpleType' or 'complexType' cannot follow 'unique', 'key' or 'keyref'.";

	public const string Sch_XsiNilAndType = "There can be no type value when attribute is 'xsi:nil' and has value 'true'.";

	public const string Sch_DupSimpleTypeChild = "'simpleType' should have only one child 'union', 'list', or 'restriction'.";

	public const string Sch_InvalidIdAttribute = "Invalid 'id' attribute value: {0}";

	public const string Sch_InvalidNameAttributeEx = "Invalid 'name' attribute value '{0}': '{1}'.";

	public const string Sch_InvalidAttribute = "Invalid '{0}' attribute: '{1}'.";

	public const string Sch_EmptyChoice = "Empty choice cannot be satisfied if 'minOccurs' is not equal to 0.";

	public const string Sch_DerivedNotFromBase = "The data type of the simple content is not a valid restriction of the base complex type.";

	public const string Sch_NeedSimpleTypeChild = "Simple content restriction must have a simple type child if the content type of the base type is not a simple type definition.";

	public const string Sch_InvalidCollection = "The schema items collection cannot contain an object of type 'XmlSchemaInclude', 'XmlSchemaImport', or 'XmlSchemaRedefine'.";

	public const string Sch_UnrefNS = "Namespace '{0}' is not available to be referenced in this schema.";

	public const string Sch_InvalidSimpleTypeRestriction = "Restriction of 'anySimpleType' is not allowed.";

	public const string Sch_MultipleRedefine = "Multiple redefines of the same schema will be ignored.";

	public const string Sch_NullValue = "Value cannot be null.";

	public const string Sch_ComplexContentModel = "Content model validation resulted in a large number of states, possibly due to large occurrence ranges. Therefore, content model may not be validated accurately.";

	public const string Sch_SchemaNotPreprocessed = "All schemas in the set should be successfully preprocessed prior to compilation.";

	public const string Sch_SchemaNotRemoved = "The schema could not be removed because other schemas in the set have dependencies on this schema or its imports.";

	public const string Sch_ComponentAlreadySeenForNS = "An element or attribute information item has already been validated from the '{0}' namespace. It is an error if 'xsi:schemaLocation', 'xsi:noNamespaceSchemaLocation', or an inline schema occurs for that namespace.";

	public const string Sch_DefaultAttributeNotApplied = "Default attribute '{0}' for element '{1}' could not be applied as the attribute namespace is not mapped to a prefix in the instance document.";

	public const string Sch_NotXsiAttribute = "The attribute '{0}' does not match one of the four allowed attributes in the 'xsi' namespace.";

	public const string Sch_SchemaDoesNotExist = "Schema does not exist in the set.";

	public const string XmlDocument_ValidateInvalidNodeType = "Validate method can be called only on nodes of type Document, DocumentFragment, Element, or Attribute.";

	public const string XmlDocument_NodeNotFromDocument = "Cannot validate '{0}' because its owner document is not the current document. ";

	public const string XmlDocument_NoNodeSchemaInfo = "Schema information could not be found for the node passed into Validate. The node may be invalid in its current position. Navigate to the ancestor that has schema information, then call Validate again.";

	public const string XmlDocument_NoSchemaInfo = "The XmlSchemaSet on the document is either null or has no schemas in it. Provide schema information before calling Validate.";

	public const string Sch_InvalidStartTransition = "It is invalid to call the '{0}' method in the current state of the validator. The '{1}' method must be called before proceeding with validation.";

	public const string Sch_InvalidStateTransition = "The transition from the '{0}' method to the '{1}' method is not allowed.";

	public const string Sch_InvalidEndValidation = "The 'EndValidation' method cannot not be called when all the elements have not been validated. 'ValidateEndElement' calls corresponding to 'ValidateElement' calls might be missing.";

	public const string Sch_InvalidEndElementCall = "It is invalid to call the 'ValidateEndElement' overload that takes in a 'typedValue' after 'ValidateText' or 'ValidateWhitespace' methods have been called.";

	public const string Sch_InvalidEndElementCallTyped = "It is invalid to call the 'ValidateEndElement' overload that takes in a 'typedValue' for elements with complex content.";

	public const string Sch_InvalidEndElementMultiple = "The call to the '{0}' method does not match a corresponding call to 'ValidateElement' method.";

	public const string Sch_DuplicateAttribute = "The '{0}' attribute has already been validated and is a duplicate attribute.";

	public const string Sch_InvalidPartialValidationType = "The partial validation type has to be 'XmlSchemaElement', 'XmlSchemaAttribute', or 'XmlSchemaType'.";

	public const string Sch_SchemaElementNameMismatch = "The element name '{0}' does not match the name '{1}' of the 'XmlSchemaElement' set as a partial validation type. ";

	public const string Sch_SchemaAttributeNameMismatch = "The attribute name '{0}' does not match the name '{1}' of the 'XmlSchemaAttribute' set as a partial validation type. ";

	public const string Sch_ValidateAttributeInvalidCall = "If the partial validation type is 'XmlSchemaElement' or 'XmlSchemaType', the 'ValidateAttribute' method cannot be called.";

	public const string Sch_ValidateElementInvalidCall = "If the partial validation type is 'XmlSchemaAttribute', the 'ValidateElement' method cannot be called.";

	public const string Sch_EnumNotStarted = "Enumeration has not started. Call MoveNext.";

	public const string Sch_EnumFinished = "Enumeration has already finished.";

	public const string SchInf_schema = "The supplied xml instance is a schema or contains an inline schema. This class cannot infer a schema for a schema.";

	public const string SchInf_entity = "Inference cannot handle entity references. Pass in an 'XmlReader' that expands entities.";

	public const string SchInf_simplecontent = "Expected simple content. Schema was not created using this tool.";

	public const string SchInf_extension = "Expected 'Extension' within 'SimpleContent'. Schema was not created using this tool.";

	public const string SchInf_particle = "Particle cannot exist along with 'ContentModel'.";

	public const string SchInf_ct = "Complex type expected to exist with at least one 'Element' at this point.";

	public const string SchInf_seq = "sequence expected to contain elements only. Schema was not created using this tool.";

	public const string SchInf_noseq = "The supplied schema contains particles other than Sequence and Choice. Only schemas generated by this tool are supported.";

	public const string SchInf_noct = "Expected ComplexType. Schema was not generated using this tool.";

	public const string SchInf_UnknownParticle = "Expected Element. Schema was not generated using this tool.";

	public const string SchInf_schematype = "Inference can only handle simple built-in types for 'SchemaType'.";

	public const string SchInf_NoElement = "There is no element to infer schema.";

	public const string Xp_UnclosedString = "This is an unclosed string.";

	public const string Xp_ExprExpected = "'{0}' is an invalid expression.";

	public const string Xp_InvalidArgumentType = "The argument to function '{0}' in '{1}' cannot be converted to a node-set.";

	public const string Xp_InvalidNumArgs = "Function '{0}' in '{1}' has an invalid number of arguments.";

	public const string Xp_InvalidName = "'{0}' has an invalid qualified name.";

	public const string Xp_InvalidToken = "'{0}' has an invalid token.";

	public const string Xp_NodeSetExpected = "Expression must evaluate to a node-set.";

	public const string Xp_NotSupported = "The XPath query '{0}' is not supported.";

	public const string Xp_InvalidPattern = "'{0}' is an invalid XSLT pattern.";

	public const string Xp_InvalidKeyPattern = "'{0}' is an invalid key pattern. It either contains a variable reference or 'key()' function.";

	public const string Xp_BadQueryObject = "This is an invalid object. Only objects returned from Compile() can be passed as input.";

	public const string Xp_UndefinedXsltContext = "XsltContext is needed for this query because of an unknown function.";

	public const string Xp_NoContext = "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function.";

	public const string Xp_UndefVar = "The variable '{0}' is undefined.";

	public const string Xp_UndefFunc = "The function '{0}()' is undefined.";

	public const string Xp_FunctionFailed = "Function '{0}()' has failed.";

	public const string Xp_CurrentNotAllowed = "The 'current()' function cannot be used in a pattern.";

	public const string Xp_QueryTooComplex = "The xpath query is too complex.";

	public const string Xdom_DualDocumentTypeNode = "This document already has a 'DocumentType' node.";

	public const string Xdom_DualDocumentElementNode = "This document already has a 'DocumentElement' node.";

	public const string Xdom_DualDeclarationNode = "This document already has an 'XmlDeclaration' node.";

	public const string Xdom_Import = "Cannot import nodes of type '{0}'.";

	public const string Xdom_Import_NullNode = "Cannot import a null node.";

	public const string Xdom_NoRootEle = "The document does not have a root element.";

	public const string Xdom_Attr_Name = "The attribute local name cannot be empty.";

	public const string Xdom_AttrCol_Object = "An 'Attributes' collection can only contain 'Attribute' objects.";

	public const string Xdom_AttrCol_Insert = "The reference node must be a child of the current node.";

	public const string Xdom_NamedNode_Context = "The named node is from a different document context.";

	public const string Xdom_Version = "Wrong XML version information. The XML must match production \"VersionNum ::= '1.' [0-9]+\".";

	public const string Xdom_standalone = "Wrong value for the XML declaration standalone attribute of '{0}'.";

	public const string Xdom_Ent_Innertext = "The 'InnerText' of an 'Entity' node is read-only and cannot be set.";

	public const string Xdom_EntRef_SetVal = "'EntityReference' nodes have no support for setting value.";

	public const string Xdom_WS_Char = "The string for whitespace contains an invalid character.";

	public const string Xdom_Node_SetVal = "Cannot set a value on node type '{0}'.";

	public const string Xdom_Empty_LocalName = "The local name for elements or attributes cannot be null or an empty string.";

	public const string Xdom_Set_InnerXml = "Cannot set the 'InnerXml' for the current node because it is either read-only or cannot have children.";

	public const string Xdom_Attr_InUse = "The 'Attribute' node cannot be inserted because it is already an attribute of another element.";

	public const string Xdom_Enum_ElementList = "The element list has changed. The enumeration operation failed to continue.";

	public const string Xdom_Invalid_NT_String = "'{0}' does not represent any 'XmlNodeType'.";

	public const string Xdom_InvalidCharacter_EntityReference = "Cannot create an 'EntityReference' node with a name starting with '#'.";

	public const string Xdom_IndexOutOfRange = "The index being passed in is out of range.";

	public const string Xdom_Document_Innertext = "The 'InnerText' of a 'Document' node is read-only and cannot be set.";

	public const string Xpn_BadPosition = "Operation is not valid due to the current position of the navigator.";

	public const string Xpn_MissingParent = "The current position of the navigator is missing a valid parent.";

	public const string Xpn_NoContent = "No content generated as the result of the operation.";

	public const string Xdom_Load_NoDocument = "The document to be loaded could not be found.";

	public const string Xdom_Load_NoReader = "There is no reader from which to load the document.";

	public const string Xdom_Node_Null_Doc = "Cannot create a node without an owner document.";

	public const string Xdom_Node_Insert_Child = "Cannot insert a node or any ancestor of that node as a child of itself.";

	public const string Xdom_Node_Insert_Contain = "The current node cannot contain other nodes.";

	public const string Xdom_Node_Insert_Path = "The reference node is not a child of this node.";

	public const string Xdom_Node_Insert_Context = "The node to be inserted is from a different document context.";

	public const string Xdom_Node_Insert_Location = "Cannot insert the node in the specified location.";

	public const string Xdom_Node_Insert_TypeConflict = "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type.";

	public const string Xdom_Node_Remove_Contain = "The current node cannot contain other nodes, so the node to be removed is not its child.";

	public const string Xdom_Node_Remove_Child = "The node to be removed is not a child of this node.";

	public const string Xdom_Node_Modify_ReadOnly = "This node is read-only. It cannot be modified.";

	public const string Xdom_TextNode_SplitText = "The 'Text' node is not connected in the DOM live tree. No 'SplitText' operation could be performed.";

	public const string Xdom_Attr_Reserved_XmlNS = "The namespace declaration attribute has an incorrect 'namespaceURI': '{0}'.";

	public const string Xdom_Node_Cloning = "'Entity' and 'Notation' nodes cannot be cloned.";

	public const string Xnr_ResolveEntity = "The node is not an expandable 'EntityReference' node.";

	public const string XPathDocument_MissingSchemas = "An XmlSchemaSet must be provided to validate the document.";

	public const string XPathDocument_NotEnoughSchemaInfo = "Element should have prior schema information to call this method.";

	public const string XPathDocument_ValidateInvalidNodeType = "Validate and CheckValidity are only allowed on Root or Element nodes.";

	public const string XPathDocument_SchemaSetNotAllowed = "An XmlSchemaSet is only allowed as a parameter on the Root node.";

	public const string XmlBin_MissingEndCDATA = "CDATA end token is missing.";

	public const string XmlBin_InvalidQNameID = "Invalid QName ID.";

	public const string XmlBinary_UnexpectedToken = "Unexpected BinaryXml token.";

	public const string XmlBinary_InvalidSqlDecimal = "Unable to parse data as SQL_DECIMAL.";

	public const string XmlBinary_InvalidSignature = "Invalid BinaryXml signature.";

	public const string XmlBinary_InvalidProtocolVersion = "Invalid BinaryXml protocol version.";

	public const string XmlBinary_UnsupportedCodePage = "Unsupported BinaryXml codepage.";

	public const string XmlBinary_InvalidStandalone = "Invalid BinaryXml standalone token.";

	public const string XmlBinary_NoParserContext = "BinaryXml Parser does not support initialization with XmlParserContext.";

	public const string XmlBinary_ListsOfValuesNotSupported = "Lists of BinaryXml value tokens not supported.";

	public const string XmlBinary_CastNotSupported = "Token '{0}' does not support a conversion to Clr type '{1}'.";

	public const string XmlBinary_NoRemapPrefix = "Prefix '{0}' is already assigned to namespace '{1}' and cannot be reassigned to '{2}' on this tag.";

	public const string XmlBinary_AttrWithNsNoPrefix = "Attribute '{0}' has namespace '{1}' but no prefix.";

	public const string XmlBinary_ValueTooBig = "The value is too big to fit into an Int32. The arithmetic operation resulted in an overflow.";

	public const string SqlTypes_ArithOverflow = "Arithmetic Overflow.";

	public const string XmlMissingType = "Invalid serialization assembly: Required type {0} cannot be found in the generated assembly '{1}'.";

	public const string XmlSerializerUnsupportedType = "{0} is an unsupported type. Please use [XmlIgnore] attribute to exclude members of this type from serialization graph.";

	public const string XmlSerializerUnsupportedMember = "Cannot serialize member '{0}' of type '{1}', see inner exception for more details.";

	public const string XmlUnsupportedTypeKind = "The type {0} may not be serialized.";

	public const string XmlUnsupportedSoapTypeKind = "The type {0} may not be serialized with SOAP-encoded messages. Set the Use for your message to Literal.";

	public const string XmlUnsupportedIDictionary = "The type {0} is not supported because it implements IDictionary.";

	public const string XmlUnsupportedIDictionaryDetails = "Cannot serialize member {0} of type {1}, because it implements IDictionary.";

	public const string XmlDuplicateTypeName = "A type with the name {0} has already been added in namespace {1}.";

	public const string XmlSerializableNameMissing1 = "Schema Id is missing. The schema returned from {0}.GetSchema() must have an Id.";

	public const string XmlConstructorInaccessible = "{0} cannot be serialized because it does not have a parameterless constructor.";

	public const string XmlTypeInaccessible = "{0} is inaccessible due to its protection level. Only public types can be processed.";

	public const string XmlTypeStatic = "{0} cannot be serialized. Static types cannot be used as parameters or return types.";

	public const string XmlNoDefaultAccessors = "You must implement a default accessor on {0} because it inherits from ICollection.";

	public const string XmlNoAddMethod = "To be XML serializable, types which inherit from {2} must have an implementation of Add({1}) at all levels of their inheritance hierarchy. {0} does not implement Add({1}).";

	public const string XmlReadOnlyPropertyError = "Cannot deserialize type '{0}' because it contains property '{1}' which has no public setter.";

	public const string XmlAttributeSetAgain = "'{0}.{1}' already has attributes.";

	public const string XmlIllegalWildcard = "Cannot use wildcards at the top level of a schema.";

	public const string XmlIllegalArrayElement = "An element declared at the top level of a schema cannot have maxOccurs > 1. Provide a wrapper element for '{0}' by using XmlArray or XmlArrayItem instead of XmlElementAttribute, or by using the Wrapped parameter style.";

	public const string XmlIllegalForm = "There was an error exporting '{0}': elements declared at the top level of a schema cannot be unqualified.";

	public const string XmlBareTextMember = "There was an error exporting '{0}': bare members cannot contain text content.";

	public const string XmlBareAttributeMember = "There was an error exporting '{0}': bare members cannot be attributes.";

	public const string XmlReflectionError = "There was an error reflecting '{0}'.";

	public const string XmlTypeReflectionError = "There was an error reflecting type '{0}'.";

	public const string XmlPropertyReflectionError = "There was an error reflecting property '{0}'.";

	public const string XmlFieldReflectionError = "There was an error reflecting field '{0}'.";

	public const string XmlInvalidDataTypeUsage = "'{0}' is an invalid value for the {1} property. The property may only be specified for primitive types.";

	public const string XmlInvalidXsdDataType = "Value '{0}' cannot be used for the {1} property. The datatype '{2}' is missing.";

	public const string XmlDataTypeMismatch = "'{0}' is an invalid value for the {1} property. {0} cannot be converted to {2}.";

	public const string XmlIllegalTypeContext = "{0} cannot be used as: 'xml {1}'.";

	public const string XmlUdeclaredXsdType = "The type, {0}, is undeclared.";

	public const string XmlInvalidConstantAttribute = "Only XmlEnum may be used on enumerated constants.";

	public const string XmlIllegalAttributesArrayAttribute = "XmlAttribute and XmlAnyAttribute cannot be used in conjunction with XmlElement, XmlText, XmlAnyElement, XmlArray, or XmlArrayItem.";

	public const string XmlIllegalElementsArrayAttribute = "XmlElement, XmlText, and XmlAnyElement cannot be used in conjunction with XmlAttribute, XmlAnyAttribute, XmlArray, or XmlArrayItem.";

	public const string XmlIllegalArrayArrayAttribute = "XmlArray and XmlArrayItem cannot be used in conjunction with XmlAttribute, XmlAnyAttribute, XmlElement, XmlText, or XmlAnyElement.";

	public const string XmlIllegalAttribute = "For non-array types, you may use the following attributes: XmlAttribute, XmlText, XmlElement, or XmlAnyElement.";

	public const string XmlIllegalType = "The type for {0} may not be specified for primitive types.";

	public const string XmlIllegalAttrOrText = "Cannot serialize member '{0}' of type {1}. XmlAttribute/XmlText cannot be used to encode complex types.";

	public const string XmlIllegalSoapAttribute = "Cannot serialize member '{0}' of type {1}. SoapAttribute cannot be used to encode complex types.";

	public const string XmlIllegalAttrOrTextInterface = "Cannot serialize member '{0}' of type {1}. XmlAttribute/XmlText cannot be used to encode types implementing {2}.";

	public const string XmlIllegalAttributeFlagsArray = "XmlAttribute cannot be used to encode array of {1}, because it is marked with FlagsAttribute.";

	public const string XmlIllegalAnyElement = "Cannot serialize member of type {0}: XmlAnyElement can only be used with classes of type XmlNode or a type deriving from XmlNode.";

	public const string XmlInvalidIsNullable = "IsNullable may not be 'true' for value type {0}.  Please consider using Nullable<{0}> instead.";

	public const string XmlInvalidNotNullable = "IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the {1} attribute.";

	public const string XmlInvalidFormUnqualified = "The Form property may not be 'Unqualified' when an explicit Namespace property is present.";

	public const string XmlDuplicateNamespace = "The namespace, {0}, is a duplicate.";

	public const string XmlElementHasNoName = "This element has no name. Please review schema type '{0}' from namespace '{1}'.";

	public const string XmlAttributeHasNoName = "This attribute has no name.";

	public const string XmlElementImportedTwice = "The element, {0}, from namespace, {1}, was imported in two different contexts: ({2}, {3}).";

	public const string XmlHiddenMember = "Member {0}.{1} of type {2} hides base class member {3}.{4} of type {5}. Use XmlElementAttribute or XmlAttributeAttribute to specify a new name.";

	public const string XmlInvalidXmlOverride = "Member '{0}.{1}' hides inherited member '{2}.{3}', but has different custom attributes.";

	public const string XmlMembersDeriveError = "These members may not be derived.";

	public const string XmlTypeUsedTwice = "The type '{0}' from namespace '{1}' was used in two different ways.";

	public const string XmlMissingGroup = "Group {0} is missing.";

	public const string XmlMissingAttributeGroup = "The attribute group {0} is missing.";

	public const string XmlMissingDataType = "The datatype '{0}' is missing.";

	public const string XmlInvalidEncoding = "Referenced type '{0}' is only valid for encoded SOAP.";

	public const string XmlMissingElement = "The element '{0}' is missing.";

	public const string XmlMissingAttribute = "The attribute {0} is missing.";

	public const string XmlMissingMethodEnum = "The method for enum {0} is missing.";

	public const string XmlNoAttributeHere = "Cannot write a node of type XmlAttribute as an element value. Use XmlAnyAttributeAttribute with an array of XmlNode or XmlAttribute to write the 

BepInEx/core/System.Xml.Linq.dll

Decompiled 2 weeks ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using Unity;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("System.Xml.Linq.dll")]
[assembly: AssemblyDescription("System.Xml.Linq.dll")]
[assembly: AssemblyDefaultAlias("System.Xml.Linq.dll")]
[assembly: AssemblyCompany("Mono development team")]
[assembly: AssemblyProduct("Mono Common Language Infrastructure")]
[assembly: AssemblyCopyright("(c) Various Mono authors")]
[assembly: SatelliteContractVersion("4.0.0.0")]
[assembly: AssemblyInformationalVersion("4.6.57.0")]
[assembly: AssemblyFileVersion("4.6.57.0")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: CLSCompliant(true)]
[assembly: AssemblyDelaySign(true)]
[assembly: AssemblyKeyFile("../ecma.pub")]
[assembly: AllowPartiallyTrustedCallers]
[assembly: ComVisible(false)]
[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("4.0.0.0")]
[module: UnverifiableCode]
internal static class SR
{
	public const string Argument_AddAttribute = "An attribute cannot be added to content.";

	public const string Argument_AddNode = "A node of type {0} cannot be added to content.";

	public const string Argument_AddNonWhitespace = "Non-whitespace characters cannot be added to content.";

	public const string Argument_ConvertToString = "The argument cannot be converted to a string.";

	public const string Argument_InvalidExpandedName = "'{0}' is an invalid expanded name.";

	public const string Argument_InvalidPIName = "'{0}' is an invalid name for a processing instruction.";

	public const string Argument_InvalidPrefix = "'{0}' is an invalid prefix.";

	public const string Argument_MustBeDerivedFrom = "The argument must be derived from {0}.";

	public const string Argument_NamespaceDeclarationPrefixed = "The prefix '{0}' cannot be bound to the empty namespace name.";

	public const string Argument_NamespaceDeclarationXml = "The prefix 'xml' is bound to the namespace name 'http://www.w3.org/XML/1998/namespace'. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.";

	public const string Argument_NamespaceDeclarationXmlns = "The prefix 'xmlns' is bound to the namespace name 'http://www.w3.org/2000/xmlns/'. It must not be declared. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.";

	public const string Argument_XObjectValue = "An XObject cannot be used as a value.";

	public const string InvalidOperation_DeserializeInstance = "This instance cannot be deserialized.";

	public const string InvalidOperation_DocumentStructure = "This operation would create an incorrectly structured document.";

	public const string InvalidOperation_DuplicateAttribute = "Duplicate attribute.";

	public const string InvalidOperation_ExpectedEndOfFile = "The XmlReader state should be EndOfFile after this operation.";

	public const string InvalidOperation_ExpectedInteractive = "The XmlReader state should be Interactive.";

	public const string InvalidOperation_ExpectedNodeType = "The XmlReader must be on a node of type {0} instead of a node of type {1}.";

	public const string InvalidOperation_ExternalCode = "This operation was corrupted by external code.";

	public const string InvalidOperation_MissingAncestor = "A common ancestor is missing.";

	public const string InvalidOperation_MissingParent = "The parent is missing.";

	public const string InvalidOperation_MissingRoot = "The root element is missing.";

	public const string InvalidOperation_UnexpectedNodeType = "The XmlReader should not be on a node of type {0}.";

	public const string InvalidOperation_UnresolvedEntityReference = "The XmlReader cannot resolve entity references.";

	public const string InvalidOperation_WriteAttribute = "An attribute cannot be written after content.";

	public const string NotSupported_WriteBase64 = "This XmlWriter does not support base64 encoded data.";

	public const string NotSupported_WriteEntityRef = "This XmlWriter does not support entity references.";

	public const string Argument_CreateNavigator = "This XPathNavigator cannot be created on a node of type {0}.";

	public const string InvalidOperation_BadNodeType = "This operation is not valid on a node of type {0}.";

	public const string InvalidOperation_UnexpectedEvaluation = "The XPath expression evaluated to unexpected type {0}.";

	public const string NotSupported_MoveToId = "This XPathNavigator does not support IDs.";

	internal static string GetString(string name, params object[] args)
	{
		return GetString(CultureInfo.InvariantCulture, name, args);
	}

	internal static string GetString(CultureInfo culture, string name, params object[] args)
	{
		return string.Format(culture, name, args);
	}

	internal static string GetString(string name)
	{
		return name;
	}

	internal static string GetString(CultureInfo culture, string name)
	{
		return name;
	}

	internal static string Format(string resourceFormat, params object[] args)
	{
		if (args != null)
		{
			return string.Format(CultureInfo.InvariantCulture, resourceFormat, args);
		}
		return resourceFormat;
	}

	internal static string Format(string resourceFormat, object p1)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1);
	}

	internal static string Format(string resourceFormat, object p1, object p2)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2);
	}

	internal static string Format(CultureInfo ci, string resourceFormat, object p1, object p2)
	{
		return string.Format(ci, resourceFormat, p1, p2);
	}

	internal static string Format(string resourceFormat, object p1, object p2, object p3)
	{
		return string.Format(CultureInfo.InvariantCulture, resourceFormat, p1, p2, p3);
	}

	internal static string GetResourceString(string str)
	{
		return str;
	}
}
namespace System.Runtime.CompilerServices
{
	internal class FriendAccessAllowedAttribute : Attribute
	{
	}
}
namespace System.Xml.XPath
{
	internal static class XAttributeExtensions
	{
		public static string GetPrefixOfNamespace(this XAttribute attribute, XNamespace ns)
		{
			string namespaceName = ns.NamespaceName;
			if (namespaceName.Length == 0)
			{
				return string.Empty;
			}
			if (attribute.GetParent() != null)
			{
				return ((XElement)attribute.GetParent()).GetPrefixOfNamespace(ns);
			}
			if ((object)namespaceName == XNodeNavigator.xmlPrefixNamespace)
			{
				return "xml";
			}
			if ((object)namespaceName == XNodeNavigator.xmlnsPrefixNamespace)
			{
				return "xmlns";
			}
			return null;
		}
	}
	internal class XNodeNavigator : XPathNavigator, IXmlLineInfo
	{
		internal static readonly string xmlPrefixNamespace = XNamespace.Xml.NamespaceName;

		internal static readonly string xmlnsPrefixNamespace = XNamespace.Xmlns.NamespaceName;

		private const int DocumentContentMask = 386;

		private static readonly int[] s_ElementContentMasks = new int[10] { 0, 2, 0, 0, 24, 0, 0, 128, 256, 410 };

		private const int TextMask = 24;

		private static XAttribute s_XmlNamespaceDeclaration;

		private XObject _source;

		private XElement _parent;

		private XmlNameTable _nameTable;

		public override string BaseURI
		{
			get
			{
				if (_source != null)
				{
					return _source.BaseUri;
				}
				if (_parent != null)
				{
					return _parent.BaseUri;
				}
				return string.Empty;
			}
		}

		public override bool HasAttributes
		{
			get
			{
				if (_source is XElement xElement)
				{
					foreach (XAttribute item in xElement.Attributes())
					{
						if (!item.IsNamespaceDeclaration)
						{
							return true;
						}
					}
				}
				return false;
			}
		}

		public override bool HasChildren
		{
			get
			{
				if (_source is XContainer xContainer)
				{
					foreach (XNode item in xContainer.Nodes())
					{
						if (IsContent(xContainer, item))
						{
							return true;
						}
					}
				}
				return false;
			}
		}

		public override bool IsEmptyElement
		{
			get
			{
				if (_source is XElement xElement)
				{
					return xElement.IsEmpty;
				}
				return false;
			}
		}

		public override string LocalName => _nameTable.Add(GetLocalName());

		public override string Name
		{
			get
			{
				string prefix = GetPrefix();
				if (prefix.Length == 0)
				{
					return _nameTable.Add(GetLocalName());
				}
				return _nameTable.Add(prefix + ":" + GetLocalName());
			}
		}

		public override string NamespaceURI => _nameTable.Add(GetNamespaceURI());

		public override XmlNameTable NameTable => _nameTable;

		public override XPathNodeType NodeType
		{
			get
			{
				if (_source != null)
				{
					switch (_source.NodeType)
					{
					case XmlNodeType.Element:
						return XPathNodeType.Element;
					case XmlNodeType.Attribute:
						if (!((XAttribute)_source).IsNamespaceDeclaration)
						{
							return XPathNodeType.Attribute;
						}
						return XPathNodeType.Namespace;
					case XmlNodeType.Document:
						return XPathNodeType.Root;
					case XmlNodeType.Comment:
						return XPathNodeType.Comment;
					case XmlNodeType.ProcessingInstruction:
						return XPathNodeType.ProcessingInstruction;
					default:
						return XPathNodeType.Text;
					}
				}
				return XPathNodeType.Text;
			}
		}

		public override string Prefix => _nameTable.Add(GetPrefix());

		public override object UnderlyingObject => _source;

		public override string Value
		{
			get
			{
				if (_source != null)
				{
					switch (_source.NodeType)
					{
					case XmlNodeType.Element:
						return ((XElement)_source).Value;
					case XmlNodeType.Attribute:
						return ((XAttribute)_source).Value;
					case XmlNodeType.Document:
					{
						XElement root = ((XDocument)_source).Root;
						if (root == null)
						{
							return string.Empty;
						}
						return root.Value;
					}
					case XmlNodeType.Text:
					case XmlNodeType.CDATA:
						return CollectText((XText)_source);
					case XmlNodeType.Comment:
						return ((XComment)_source).Value;
					case XmlNodeType.ProcessingInstruction:
						return ((XProcessingInstruction)_source).Data;
					default:
						return string.Empty;
					}
				}
				return string.Empty;
			}
		}

		int IXmlLineInfo.LineNumber => ((IXmlLineInfo)_source)?.LineNumber ?? 0;

		int IXmlLineInfo.LinePosition => ((IXmlLineInfo)_source)?.LinePosition ?? 0;

		public XNodeNavigator(XNode node, XmlNameTable nameTable)
		{
			_source = node;
			_nameTable = ((nameTable != null) ? nameTable : CreateNameTable());
		}

		public XNodeNavigator(XNodeNavigator other)
		{
			_source = other._source;
			_parent = other._parent;
			_nameTable = other._nameTable;
		}

		private string GetLocalName()
		{
			if (_source is XElement xElement)
			{
				return xElement.Name.LocalName;
			}
			if (_source is XAttribute xAttribute)
			{
				if (_parent != null && xAttribute.Name.NamespaceName.Length == 0)
				{
					return string.Empty;
				}
				return xAttribute.Name.LocalName;
			}
			if (_source is XProcessingInstruction xProcessingInstruction)
			{
				return xProcessingInstruction.Target;
			}
			return string.Empty;
		}

		private string GetNamespaceURI()
		{
			if (_source is XElement xElement)
			{
				return xElement.Name.NamespaceName;
			}
			if (_source is XAttribute xAttribute)
			{
				if (_parent != null)
				{
					return string.Empty;
				}
				return xAttribute.Name.NamespaceName;
			}
			return string.Empty;
		}

		private string GetPrefix()
		{
			if (_source is XElement xElement)
			{
				string prefixOfNamespace = xElement.GetPrefixOfNamespace(xElement.Name.Namespace);
				if (prefixOfNamespace != null)
				{
					return prefixOfNamespace;
				}
				return string.Empty;
			}
			if (_source is XAttribute xAttribute)
			{
				if (_parent != null)
				{
					return string.Empty;
				}
				string prefixOfNamespace2 = xAttribute.GetPrefixOfNamespace(xAttribute.Name.Namespace);
				if (prefixOfNamespace2 != null)
				{
					return prefixOfNamespace2;
				}
			}
			return string.Empty;
		}

		public override XPathNavigator Clone()
		{
			return new XNodeNavigator(this);
		}

		public override bool IsSamePosition(XPathNavigator navigator)
		{
			if (!(navigator is XNodeNavigator n))
			{
				return false;
			}
			return IsSamePosition(this, n);
		}

		public override bool MoveTo(XPathNavigator navigator)
		{
			if (navigator is XNodeNavigator xNodeNavigator)
			{
				_source = xNodeNavigator._source;
				_parent = xNodeNavigator._parent;
				return true;
			}
			return false;
		}

		public override bool MoveToAttribute(string localName, string namespaceName)
		{
			if (_source is XElement xElement)
			{
				foreach (XAttribute item in xElement.Attributes())
				{
					if (item.Name.LocalName == localName && item.Name.NamespaceName == namespaceName && !item.IsNamespaceDeclaration)
					{
						_source = item;
						return true;
					}
				}
			}
			return false;
		}

		public override bool MoveToChild(string localName, string namespaceName)
		{
			if (_source is XContainer xContainer)
			{
				foreach (XElement item in xContainer.Elements())
				{
					if (item.Name.LocalName == localName && item.Name.NamespaceName == namespaceName)
					{
						_source = item;
						return true;
					}
				}
			}
			return false;
		}

		public override bool MoveToChild(XPathNodeType type)
		{
			if (_source is XContainer xContainer)
			{
				int num = GetElementContentMask(type);
				if ((0x18u & (uint)num) != 0 && xContainer.GetParent() == null && xContainer is XDocument)
				{
					num &= -25;
				}
				foreach (XNode item in xContainer.Nodes())
				{
					if (((1 << (int)item.NodeType) & num) != 0)
					{
						_source = item;
						return true;
					}
				}
			}
			return false;
		}

		public override bool MoveToFirstAttribute()
		{
			if (_source is XElement xElement)
			{
				foreach (XAttribute item in xElement.Attributes())
				{
					if (!item.IsNamespaceDeclaration)
					{
						_source = item;
						return true;
					}
				}
			}
			return false;
		}

		public override bool MoveToFirstChild()
		{
			if (_source is XContainer xContainer)
			{
				foreach (XNode item in xContainer.Nodes())
				{
					if (IsContent(xContainer, item))
					{
						_source = item;
						return true;
					}
				}
			}
			return false;
		}

		public override bool MoveToFirstNamespace(XPathNamespaceScope scope)
		{
			if (_source is XElement xElement)
			{
				XAttribute xAttribute = null;
				switch (scope)
				{
				case XPathNamespaceScope.Local:
					xAttribute = GetFirstNamespaceDeclarationLocal(xElement);
					break;
				case XPathNamespaceScope.ExcludeXml:
					xAttribute = GetFirstNamespaceDeclarationGlobal(xElement);
					while (xAttribute != null && xAttribute.Name.LocalName == "xml")
					{
						xAttribute = GetNextNamespaceDeclarationGlobal(xAttribute);
					}
					break;
				case XPathNamespaceScope.All:
					xAttribute = GetFirstNamespaceDeclarationGlobal(xElement);
					if (xAttribute == null)
					{
						xAttribute = GetXmlNamespaceDeclaration();
					}
					break;
				}
				if (xAttribute != null)
				{
					_source = xAttribute;
					_parent = xElement;
					return true;
				}
			}
			return false;
		}

		public override bool MoveToId(string id)
		{
			throw new NotSupportedException("This XPathNavigator does not support IDs.");
		}

		public override bool MoveToNamespace(string localName)
		{
			if (_source is XElement xElement)
			{
				if (localName == "xmlns")
				{
					return false;
				}
				if (localName != null && localName.Length == 0)
				{
					localName = "xmlns";
				}
				for (XAttribute xAttribute = GetFirstNamespaceDeclarationGlobal(xElement); xAttribute != null; xAttribute = GetNextNamespaceDeclarationGlobal(xAttribute))
				{
					if (xAttribute.Name.LocalName == localName)
					{
						_source = xAttribute;
						_parent = xElement;
						return true;
					}
				}
				if (localName == "xml")
				{
					_source = GetXmlNamespaceDeclaration();
					_parent = xElement;
					return true;
				}
			}
			return false;
		}

		public override bool MoveToNext()
		{
			if (_source is XNode xNode)
			{
				XContainer parent = xNode.GetParent();
				if (parent != null)
				{
					XNode xNode2 = null;
					for (XNode xNode3 = xNode; xNode3 != null; xNode3 = xNode2)
					{
						xNode2 = xNode3.NextNode;
						if (xNode2 == null)
						{
							break;
						}
						if (IsContent(parent, xNode2) && (!(xNode3 is XText) || !(xNode2 is XText)))
						{
							_source = xNode2;
							return true;
						}
					}
				}
			}
			return false;
		}

		public override bool MoveToNext(string localName, string namespaceName)
		{
			if (_source is XNode xNode)
			{
				foreach (XElement item in xNode.ElementsAfterSelf())
				{
					if (item.Name.LocalName == localName && item.Name.NamespaceName == namespaceName)
					{
						_source = item;
						return true;
					}
				}
			}
			return false;
		}

		public override bool MoveToNext(XPathNodeType type)
		{
			if (_source is XNode xNode)
			{
				XContainer parent = xNode.GetParent();
				if (parent != null)
				{
					int num = GetElementContentMask(type);
					if ((0x18u & (uint)num) != 0 && parent.GetParent() == null && parent is XDocument)
					{
						num &= -25;
					}
					XNode xNode2 = null;
					for (XNode xNode3 = xNode; xNode3 != null; xNode3 = xNode2)
					{
						xNode2 = xNode3.NextNode;
						if (((1 << (int)xNode2.NodeType) & num) != 0 && (!(xNode3 is XText) || !(xNode2 is XText)))
						{
							_source = xNode2;
							return true;
						}
					}
				}
			}
			return false;
		}

		public override bool MoveToNextAttribute()
		{
			if (_source is XAttribute xAttribute && _parent == null && (XElement)xAttribute.GetParent() != null)
			{
				for (XAttribute nextAttribute = xAttribute.NextAttribute; nextAttribute != null; nextAttribute = nextAttribute.NextAttribute)
				{
					if (!nextAttribute.IsNamespaceDeclaration)
					{
						_source = nextAttribute;
						return true;
					}
				}
			}
			return false;
		}

		public override bool MoveToNextNamespace(XPathNamespaceScope scope)
		{
			XAttribute xAttribute = _source as XAttribute;
			if (xAttribute != null && _parent != null && !IsXmlNamespaceDeclaration(xAttribute))
			{
				switch (scope)
				{
				case XPathNamespaceScope.Local:
					if (xAttribute.GetParent() != _parent)
					{
						return false;
					}
					xAttribute = GetNextNamespaceDeclarationLocal(xAttribute);
					break;
				case XPathNamespaceScope.ExcludeXml:
					do
					{
						xAttribute = GetNextNamespaceDeclarationGlobal(xAttribute);
					}
					while (xAttribute != null && (xAttribute.Name.LocalName == "xml" || HasNamespaceDeclarationInScope(xAttribute, _parent)));
					break;
				case XPathNamespaceScope.All:
					do
					{
						xAttribute = GetNextNamespaceDeclarationGlobal(xAttribute);
					}
					while (xAttribute != null && HasNamespaceDeclarationInScope(xAttribute, _parent));
					if (xAttribute == null && !HasNamespaceDeclarationInScope(GetXmlNamespaceDeclaration(), _parent))
					{
						xAttribute = GetXmlNamespaceDeclaration();
					}
					break;
				}
				if (xAttribute != null)
				{
					_source = xAttribute;
					return true;
				}
			}
			return false;
		}

		public override bool MoveToParent()
		{
			if (_parent != null)
			{
				_source = _parent;
				_parent = null;
				return true;
			}
			XNode parent = _source.GetParent();
			if (parent != null)
			{
				_source = parent;
				return true;
			}
			return false;
		}

		public override bool MoveToPrevious()
		{
			if (_source is XNode xNode)
			{
				XContainer parent = xNode.GetParent();
				if (parent != null)
				{
					XNode xNode2 = null;
					foreach (XNode item in parent.Nodes())
					{
						if (item == xNode)
						{
							if (xNode2 != null)
							{
								_source = xNode2;
								return true;
							}
							return false;
						}
						if (IsContent(parent, item))
						{
							xNode2 = item;
						}
					}
				}
			}
			return false;
		}

		public override XmlReader ReadSubtree()
		{
			return ((_source as XContainer) ?? throw new InvalidOperationException(SR.Format("This operation is not valid on a node of type {0}.", NodeType))).CreateReader();
		}

		bool IXmlLineInfo.HasLineInfo()
		{
			return ((IXmlLineInfo)_source)?.HasLineInfo() ?? false;
		}

		private static string CollectText(XText n)
		{
			string text = n.Value;
			if (n.GetParent() != null)
			{
				using IEnumerator<XNode> enumerator = n.NodesAfterSelf().GetEnumerator();
				while (enumerator.MoveNext() && enumerator.Current is XText xText)
				{
					text += xText.Value;
				}
			}
			return text;
		}

		private static XmlNameTable CreateNameTable()
		{
			NameTable nameTable = new NameTable();
			nameTable.Add(string.Empty);
			nameTable.Add(xmlnsPrefixNamespace);
			nameTable.Add(xmlPrefixNamespace);
			return nameTable;
		}

		private static bool IsContent(XContainer c, XNode n)
		{
			if (c.GetParent() != null || c is XElement)
			{
				return true;
			}
			return ((1 << (int)n.NodeType) & 0x182) != 0;
		}

		private static bool IsSamePosition(XNodeNavigator n1, XNodeNavigator n2)
		{
			if (n1._source == n2._source)
			{
				return n1._source.GetParent() == n2._source.GetParent();
			}
			return false;
		}

		private static bool IsXmlNamespaceDeclaration(XAttribute a)
		{
			return a == GetXmlNamespaceDeclaration();
		}

		private static int GetElementContentMask(XPathNodeType type)
		{
			return s_ElementContentMasks[(int)type];
		}

		private static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e)
		{
			do
			{
				XAttribute firstNamespaceDeclarationLocal = GetFirstNamespaceDeclarationLocal(e);
				if (firstNamespaceDeclarationLocal != null)
				{
					return firstNamespaceDeclarationLocal;
				}
				e = e.Parent;
			}
			while (e != null);
			return null;
		}

		private static XAttribute GetFirstNamespaceDeclarationLocal(XElement e)
		{
			foreach (XAttribute item in e.Attributes())
			{
				if (item.IsNamespaceDeclaration)
				{
					return item;
				}
			}
			return null;
		}

		private static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a)
		{
			XElement xElement = (XElement)a.GetParent();
			if (xElement == null)
			{
				return null;
			}
			XAttribute nextNamespaceDeclarationLocal = GetNextNamespaceDeclarationLocal(a);
			if (nextNamespaceDeclarationLocal != null)
			{
				return nextNamespaceDeclarationLocal;
			}
			xElement = xElement.Parent;
			if (xElement == null)
			{
				return null;
			}
			return GetFirstNamespaceDeclarationGlobal(xElement);
		}

		private static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a)
		{
			if (a.Parent == null)
			{
				return null;
			}
			for (a = a.NextAttribute; a != null; a = a.NextAttribute)
			{
				if (a.IsNamespaceDeclaration)
				{
					return a;
				}
			}
			return null;
		}

		private static XAttribute GetXmlNamespaceDeclaration()
		{
			if (s_XmlNamespaceDeclaration == null)
			{
				Interlocked.CompareExchange(ref s_XmlNamespaceDeclaration, new XAttribute(XNamespace.Xmlns.GetName("xml"), xmlPrefixNamespace), null);
			}
			return s_XmlNamespaceDeclaration;
		}

		private static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e)
		{
			XName name = a.Name;
			while (e != null && e != a.GetParent())
			{
				if (e.Attribute(name) != null)
				{
					return true;
				}
				e = e.Parent;
			}
			return false;
		}
	}
	[StructLayout(LayoutKind.Sequential, Size = 1)]
	internal readonly struct XPathEvaluator
	{
		public object Evaluate<T>(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class
		{
			object obj = node.CreateNavigator().Evaluate(expression, resolver);
			if (obj is XPathNodeIterator result)
			{
				return EvaluateIterator<T>(result);
			}
			if (!(obj is T))
			{
				throw new InvalidOperationException(SR.Format("The XPath expression evaluated to unexpected type {0}.", obj.GetType()));
			}
			return (T)obj;
		}

		private IEnumerable<T> EvaluateIterator<T>(XPathNodeIterator result)
		{
			foreach (XPathNavigator item in result)
			{
				object r = item.UnderlyingObject;
				if (!(r is T))
				{
					throw new InvalidOperationException(SR.Format("The XPath expression evaluated to unexpected type {0}.", r.GetType()));
				}
				yield return (T)r;
				XText t = r as XText;
				if (t == null || t.GetParent() == null)
				{
					continue;
				}
				do
				{
					t = t.NextNode as XText;
					if (t == null)
					{
						break;
					}
					yield return (T)(object)t;
				}
				while (t != t.GetParent().LastNode);
			}
		}
	}
	public static class Extensions
	{
		public static XPathNavigator CreateNavigator(this XNode node)
		{
			return node.CreateNavigator(null);
		}

		public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable)
		{
			if (node == null)
			{
				throw new ArgumentNullException("node");
			}
			if (node is XDocumentType)
			{
				throw new ArgumentException(SR.Format("This XPathNavigator cannot be created on a node of type {0}.", XmlNodeType.DocumentType));
			}
			if (node is XText xText)
			{
				if (xText.GetParent() is XDocument)
				{
					throw new ArgumentException(SR.Format("This XPathNavigator cannot be created on a node of type {0}.", XmlNodeType.Whitespace));
				}
				node = CalibrateText(xText);
			}
			return new XNodeNavigator(node, nameTable);
		}

		public static object XPathEvaluate(this XNode node, string expression)
		{
			return node.XPathEvaluate(expression, null);
		}

		public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver)
		{
			if (node == null)
			{
				throw new ArgumentNullException("node");
			}
			return default(XPathEvaluator).Evaluate<object>(node, expression, resolver);
		}

		public static XElement XPathSelectElement(this XNode node, string expression)
		{
			return node.XPathSelectElement(expression, null);
		}

		public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver)
		{
			return node.XPathSelectElements(expression, resolver).FirstOrDefault();
		}

		public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression)
		{
			return node.XPathSelectElements(expression, null);
		}

		public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver)
		{
			if (node == null)
			{
				throw new ArgumentNullException("node");
			}
			return (IEnumerable<XElement>)default(XPathEvaluator).Evaluate<XElement>(node, expression, resolver);
		}

		private static XText CalibrateText(XText n)
		{
			XContainer parent = n.GetParent();
			if (parent == null)
			{
				return n;
			}
			foreach (XNode item in parent.Nodes())
			{
				if (item is XText result && item == n)
				{
					return result;
				}
			}
			return null;
		}
	}
	internal static class XObjectExtensions
	{
		public static XContainer GetParent(this XObject obj)
		{
			XContainer xContainer = obj.Parent;
			if (xContainer == null)
			{
				xContainer = obj.Document;
			}
			if (xContainer == obj)
			{
				return null;
			}
			return xContainer;
		}
	}
	public static class XDocumentExtensions
	{
		private class XDocumentNavigable : IXPathNavigable
		{
			private XNode _node;

			public XDocumentNavigable(XNode n)
			{
				_node = n;
			}

			public XPathNavigator CreateNavigator()
			{
				return _node.CreateNavigator();
			}
		}

		public static IXPathNavigable ToXPathNavigable(this XNode node)
		{
			return new XDocumentNavigable(node);
		}
	}
}
namespace System.Xml.Schema
{
	internal class XNodeValidator
	{
		private XmlSchemaSet schemas;

		private ValidationEventHandler validationEventHandler;

		private XObject source;

		private bool addSchemaInfo;

		private XmlNamespaceManager namespaceManager;

		private XmlSchemaValidator validator;

		private Dictionary<XmlSchemaInfo, XmlSchemaInfo> schemaInfos;

		private ArrayList defaultAttributes;

		private XName xsiTypeName;

		private XName xsiNilName;

		public XNodeValidator(XmlSchemaSet schemas, ValidationEventHandler validationEventHandler)
		{
			this.schemas = schemas;
			this.validationEventHandler = validationEventHandler;
			XNamespace xNamespace = XNamespace.Get("http://www.w3.org/2001/XMLSchema-instance");
			xsiTypeName = xNamespace.GetName("type");
			xsiNilName = xNamespace.GetName("nil");
		}

		public void Validate(XObject source, XmlSchemaObject partialValidationType, bool addSchemaInfo)
		{
			this.source = source;
			this.addSchemaInfo = addSchemaInfo;
			XmlSchemaValidationFlags xmlSchemaValidationFlags = XmlSchemaValidationFlags.AllowXmlAttributes;
			XmlNodeType nodeType = source.NodeType;
			if (nodeType != XmlNodeType.Element)
			{
				if (nodeType != XmlNodeType.Attribute)
				{
					if (nodeType != XmlNodeType.Document)
					{
						goto IL_007a;
					}
					source = ((XDocument)source).Root;
					if (source == null)
					{
						throw new InvalidOperationException(SR.Format("The root element is missing."));
					}
					xmlSchemaValidationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints;
				}
				else
				{
					if (((XAttribute)source).IsNamespaceDeclaration)
					{
						goto IL_007a;
					}
					if (source.Parent == null)
					{
						throw new InvalidOperationException(SR.Format("The parent is missing."));
					}
				}
			}
			namespaceManager = new XmlNamespaceManager(schemas.NameTable);
			PushAncestorsAndSelf(source.Parent);
			validator = new XmlSchemaValidator(schemas.NameTable, schemas, namespaceManager, xmlSchemaValidationFlags);
			validator.ValidationEventHandler += ValidationCallback;
			validator.XmlResolver = null;
			if (partialValidationType != null)
			{
				validator.Initialize(partialValidationType);
			}
			else
			{
				validator.Initialize();
			}
			IXmlLineInfo originalLineInfo = SaveLineInfo(source);
			if (nodeType == XmlNodeType.Attribute)
			{
				ValidateAttribute((XAttribute)source);
			}
			else
			{
				ValidateElement((XElement)source);
			}
			validator.EndValidation();
			RestoreLineInfo(originalLineInfo);
			return;
			IL_007a:
			throw new InvalidOperationException(SR.Format("This operation is not valid on a node of type {0}.", nodeType));
		}

		private XmlSchemaInfo GetDefaultAttributeSchemaInfo(XmlSchemaAttribute sa)
		{
			XmlSchemaInfo xmlSchemaInfo = new XmlSchemaInfo();
			xmlSchemaInfo.IsDefault = true;
			xmlSchemaInfo.IsNil = false;
			xmlSchemaInfo.SchemaAttribute = sa;
			XmlSchemaSimpleType xmlSchemaSimpleType = (XmlSchemaSimpleType)(xmlSchemaInfo.SchemaType = sa.AttributeSchemaType);
			if (xmlSchemaSimpleType.Datatype.Variety == XmlSchemaDatatypeVariety.Union)
			{
				string defaultValue = GetDefaultValue(sa);
				XmlSchemaSimpleType[] baseMemberTypes = ((XmlSchemaSimpleTypeUnion)xmlSchemaSimpleType.Content).BaseMemberTypes;
				foreach (XmlSchemaSimpleType xmlSchemaSimpleType2 in baseMemberTypes)
				{
					object obj = null;
					try
					{
						obj = xmlSchemaSimpleType2.Datatype.ParseValue(defaultValue, schemas.NameTable, namespaceManager);
					}
					catch (XmlSchemaException)
					{
					}
					if (obj != null)
					{
						xmlSchemaInfo.MemberType = xmlSchemaSimpleType2;
						break;
					}
				}
			}
			xmlSchemaInfo.Validity = XmlSchemaValidity.Valid;
			return xmlSchemaInfo;
		}

		private string GetDefaultValue(XmlSchemaAttribute sa)
		{
			XmlQualifiedName refName = sa.RefName;
			if (!refName.IsEmpty)
			{
				sa = schemas.GlobalAttributes[refName] as XmlSchemaAttribute;
				if (sa == null)
				{
					return null;
				}
			}
			string fixedValue = sa.FixedValue;
			if (fixedValue != null)
			{
				return fixedValue;
			}
			return sa.DefaultValue;
		}

		private string GetDefaultValue(XmlSchemaElement se)
		{
			XmlQualifiedName refName = se.RefName;
			if (!refName.IsEmpty)
			{
				se = schemas.GlobalElements[refName] as XmlSchemaElement;
				if (se == null)
				{
					return null;
				}
			}
			string fixedValue = se.FixedValue;
			if (fixedValue != null)
			{
				return fixedValue;
			}
			return se.DefaultValue;
		}

		private void ReplaceSchemaInfo(XObject o, XmlSchemaInfo schemaInfo)
		{
			if (schemaInfos == null)
			{
				schemaInfos = new Dictionary<XmlSchemaInfo, XmlSchemaInfo>(new XmlSchemaInfoEqualityComparer());
			}
			XmlSchemaInfo value = o.Annotation<XmlSchemaInfo>();
			if (value != null)
			{
				if (!schemaInfos.ContainsKey(value))
				{
					schemaInfos.Add(value, value);
				}
				o.RemoveAnnotations<XmlSchemaInfo>();
			}
			if (!schemaInfos.TryGetValue(schemaInfo, out value))
			{
				value = schemaInfo;
				schemaInfos.Add(value, value);
			}
			o.AddAnnotation(value);
		}

		private void PushAncestorsAndSelf(XElement e)
		{
			while (e != null)
			{
				XAttribute xAttribute = e.lastAttr;
				if (xAttribute != null)
				{
					do
					{
						xAttribute = xAttribute.next;
						if (xAttribute.IsNamespaceDeclaration)
						{
							string text = xAttribute.Name.LocalName;
							if (text == "xmlns")
							{
								text = string.Empty;
							}
							if (!namespaceManager.HasNamespace(text))
							{
								namespaceManager.AddNamespace(text, xAttribute.Value);
							}
						}
					}
					while (xAttribute != e.lastAttr);
				}
				e = e.parent as XElement;
			}
		}

		private void PushElement(XElement e, ref string xsiType, ref string xsiNil)
		{
			namespaceManager.PushScope();
			XAttribute xAttribute = e.lastAttr;
			if (xAttribute == null)
			{
				return;
			}
			do
			{
				xAttribute = xAttribute.next;
				if (xAttribute.IsNamespaceDeclaration)
				{
					string text = xAttribute.Name.LocalName;
					if (text == "xmlns")
					{
						text = string.Empty;
					}
					namespaceManager.AddNamespace(text, xAttribute.Value);
					continue;
				}
				XName name = xAttribute.Name;
				if (name == xsiTypeName)
				{
					xsiType = xAttribute.Value;
				}
				else if (name == xsiNilName)
				{
					xsiNil = xAttribute.Value;
				}
			}
			while (xAttribute != e.lastAttr);
		}

		private IXmlLineInfo SaveLineInfo(XObject source)
		{
			IXmlLineInfo lineInfoProvider = validator.LineInfoProvider;
			validator.LineInfoProvider = source;
			return lineInfoProvider;
		}

		private void RestoreLineInfo(IXmlLineInfo originalLineInfo)
		{
			validator.LineInfoProvider = originalLineInfo;
		}

		private void ValidateAttribute(XAttribute a)
		{
			IXmlLineInfo originalLineInfo = SaveLineInfo(a);
			XmlSchemaInfo schemaInfo = (addSchemaInfo ? new XmlSchemaInfo() : null);
			source = a;
			validator.ValidateAttribute(a.Name.LocalName, a.Name.NamespaceName, a.Value, schemaInfo);
			if (addSchemaInfo)
			{
				ReplaceSchemaInfo(a, schemaInfo);
			}
			RestoreLineInfo(originalLineInfo);
		}

		private void ValidateAttributes(XElement e)
		{
			XAttribute xAttribute = e.lastAttr;
			IXmlLineInfo originalLineInfo = SaveLineInfo(xAttribute);
			if (xAttribute != null)
			{
				do
				{
					xAttribute = xAttribute.next;
					if (!xAttribute.IsNamespaceDeclaration)
					{
						ValidateAttribute(xAttribute);
					}
				}
				while (xAttribute != e.lastAttr);
				source = e;
			}
			if (addSchemaInfo)
			{
				if (defaultAttributes == null)
				{
					defaultAttributes = new ArrayList();
				}
				else
				{
					defaultAttributes.Clear();
				}
				validator.GetUnspecifiedDefaultAttributes(defaultAttributes);
				foreach (XmlSchemaAttribute defaultAttribute in defaultAttributes)
				{
					xAttribute = new XAttribute(XNamespace.Get(defaultAttribute.QualifiedName.Namespace).GetName(defaultAttribute.QualifiedName.Name), GetDefaultValue(defaultAttribute));
					ReplaceSchemaInfo(xAttribute, GetDefaultAttributeSchemaInfo(defaultAttribute));
					e.Add(xAttribute);
				}
			}
			RestoreLineInfo(originalLineInfo);
		}

		private void ValidateElement(XElement e)
		{
			XmlSchemaInfo xmlSchemaInfo = (addSchemaInfo ? new XmlSchemaInfo() : null);
			string xsiType = null;
			string xsiNil = null;
			PushElement(e, ref xsiType, ref xsiNil);
			IXmlLineInfo originalLineInfo = SaveLineInfo(e);
			source = e;
			validator.ValidateElement(e.Name.LocalName, e.Name.NamespaceName, xmlSchemaInfo, xsiType, xsiNil, null, null);
			ValidateAttributes(e);
			validator.ValidateEndOfAttributes(xmlSchemaInfo);
			ValidateNodes(e);
			validator.ValidateEndElement(xmlSchemaInfo);
			if (addSchemaInfo)
			{
				if (xmlSchemaInfo.Validity == XmlSchemaValidity.Valid && xmlSchemaInfo.IsDefault)
				{
					e.Value = GetDefaultValue(xmlSchemaInfo.SchemaElement);
				}
				ReplaceSchemaInfo(e, xmlSchemaInfo);
			}
			RestoreLineInfo(originalLineInfo);
			namespaceManager.PopScope();
		}

		private void ValidateNodes(XElement e)
		{
			XNode xNode = e.content as XNode;
			IXmlLineInfo originalLineInfo = SaveLineInfo(xNode);
			if (xNode != null)
			{
				do
				{
					xNode = xNode.next;
					if (xNode is XElement e2)
					{
						ValidateElement(e2);
					}
					else if (xNode is XText xText)
					{
						string value = xText.Value;
						if (value.Length > 0)
						{
							validator.LineInfoProvider = xText;
							validator.ValidateText(value);
						}
					}
				}
				while (xNode != e.content);
				source = e;
			}
			else if (e.content is string text && text.Length > 0)
			{
				validator.ValidateText(text);
			}
			RestoreLineInfo(originalLineInfo);
		}

		private void ValidationCallback(object sender, ValidationEventArgs e)
		{
			if (validationEventHandler != null)
			{
				validationEventHandler(source, e);
			}
			else if (e.Severity == XmlSeverityType.Error)
			{
				throw e.Exception;
			}
		}
	}
	internal class XmlSchemaInfoEqualityComparer : IEqualityComparer<XmlSchemaInfo>
	{
		public bool Equals(XmlSchemaInfo si1, XmlSchemaInfo si2)
		{
			if (si1 == si2)
			{
				return true;
			}
			if (si1 == null || si2 == null)
			{
				return false;
			}
			if (si1.ContentType == si2.ContentType && si1.IsDefault == si2.IsDefault && si1.IsNil == si2.IsNil && si1.MemberType == si2.MemberType && si1.SchemaAttribute == si2.SchemaAttribute && si1.SchemaElement == si2.SchemaElement && si1.SchemaType == si2.SchemaType)
			{
				return si1.Validity == si2.Validity;
			}
			return false;
		}

		public int GetHashCode(XmlSchemaInfo si)
		{
			if (si == null)
			{
				return 0;
			}
			int num = (int)si.ContentType;
			if (si.IsDefault)
			{
				num ^= 1;
			}
			if (si.IsNil)
			{
				num ^= 1;
			}
			XmlSchemaSimpleType memberType = si.MemberType;
			if (memberType != null)
			{
				num ^= memberType.GetHashCode();
			}
			XmlSchemaAttribute schemaAttribute = si.SchemaAttribute;
			if (schemaAttribute != null)
			{
				num ^= schemaAttribute.GetHashCode();
			}
			XmlSchemaElement schemaElement = si.SchemaElement;
			if (schemaElement != null)
			{
				num ^= schemaElement.GetHashCode();
			}
			XmlSchemaType schemaType = si.SchemaType;
			if (schemaType != null)
			{
				num ^= schemaType.GetHashCode();
			}
			return num ^ (int)si.Validity;
		}
	}
	public static class Extensions
	{
		public static IXmlSchemaInfo GetSchemaInfo(this XElement source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return source.Annotation<IXmlSchemaInfo>();
		}

		public static IXmlSchemaInfo GetSchemaInfo(this XAttribute source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return source.Annotation<IXmlSchemaInfo>();
		}

		public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler)
		{
			source.Validate(schemas, validationEventHandler, addSchemaInfo: false);
		}

		public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (schemas == null)
			{
				throw new ArgumentNullException("schemas");
			}
			new XNodeValidator(schemas, validationEventHandler).Validate(source, null, addSchemaInfo);
		}

		public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler)
		{
			source.Validate(partialValidationType, schemas, validationEventHandler, addSchemaInfo: false);
		}

		public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (partialValidationType == null)
			{
				throw new ArgumentNullException("partialValidationType");
			}
			if (schemas == null)
			{
				throw new ArgumentNullException("schemas");
			}
			new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo);
		}

		public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler)
		{
			source.Validate(partialValidationType, schemas, validationEventHandler, addSchemaInfo: false);
		}

		public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (partialValidationType == null)
			{
				throw new ArgumentNullException("partialValidationType");
			}
			if (schemas == null)
			{
				throw new ArgumentNullException("schemas");
			}
			new XNodeValidator(schemas, validationEventHandler).Validate(source, partialValidationType, addSchemaInfo);
		}
	}
}
namespace System.Xml.Linq
{
	internal class BaseUriAnnotation
	{
		internal string baseUri;

		public BaseUriAnnotation(string baseUri)
		{
			this.baseUri = baseUri;
		}
	}
	public static class Extensions
	{
		public static IEnumerable<XAttribute> Attributes(this IEnumerable<XElement> source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return GetAttributes(source, null);
		}

		public static IEnumerable<XAttribute> Attributes(this IEnumerable<XElement> source, XName name)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (!(name != null))
			{
				return XAttribute.EmptySequence;
			}
			return GetAttributes(source, name);
		}

		public static IEnumerable<XElement> Ancestors<T>(this IEnumerable<T> source) where T : XNode
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return GetAncestors(source, null, self: false);
		}

		public static IEnumerable<XElement> Ancestors<T>(this IEnumerable<T> source, XName name) where T : XNode
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (!(name != null))
			{
				return XElement.EmptySequence;
			}
			return GetAncestors(source, name, self: false);
		}

		public static IEnumerable<XElement> AncestorsAndSelf(this IEnumerable<XElement> source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return GetAncestors(source, null, self: true);
		}

		public static IEnumerable<XElement> AncestorsAndSelf(this IEnumerable<XElement> source, XName name)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (!(name != null))
			{
				return XElement.EmptySequence;
			}
			return GetAncestors(source, name, self: true);
		}

		public static IEnumerable<XNode> Nodes<T>(this IEnumerable<T> source) where T : XContainer
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return NodesIterator(source);
		}

		private static IEnumerable<XNode> NodesIterator<T>(IEnumerable<T> source) where T : XContainer
		{
			foreach (T root in source)
			{
				if (root == null)
				{
					continue;
				}
				XNode i = root.LastNode;
				if (i != null)
				{
					do
					{
						i = i.next;
						yield return i;
					}
					while (i.parent == root && i != root.content);
				}
			}
		}

		public static IEnumerable<XNode> DescendantNodes<T>(this IEnumerable<T> source) where T : XContainer
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return GetDescendantNodes(source, self: false);
		}

		public static IEnumerable<XElement> Descendants<T>(this IEnumerable<T> source) where T : XContainer
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return GetDescendants(source, null, self: false);
		}

		public static IEnumerable<XElement> Descendants<T>(this IEnumerable<T> source, XName name) where T : XContainer
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (!(name != null))
			{
				return XElement.EmptySequence;
			}
			return GetDescendants(source, name, self: false);
		}

		public static IEnumerable<XNode> DescendantNodesAndSelf(this IEnumerable<XElement> source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return GetDescendantNodes(source, self: true);
		}

		public static IEnumerable<XElement> DescendantsAndSelf(this IEnumerable<XElement> source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return GetDescendants(source, null, self: true);
		}

		public static IEnumerable<XElement> DescendantsAndSelf(this IEnumerable<XElement> source, XName name)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (!(name != null))
			{
				return XElement.EmptySequence;
			}
			return GetDescendants(source, name, self: true);
		}

		public static IEnumerable<XElement> Elements<T>(this IEnumerable<T> source) where T : XContainer
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return GetElements(source, null);
		}

		public static IEnumerable<XElement> Elements<T>(this IEnumerable<T> source, XName name) where T : XContainer
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (!(name != null))
			{
				return XElement.EmptySequence;
			}
			return GetElements(source, name);
		}

		public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : XNode
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return DocumentOrderIterator(source);
		}

		private static IEnumerable<T> DocumentOrderIterator<T>(IEnumerable<T> source) where T : XNode
		{
			int count;
			T[] items = System.Collections.Generic.EnumerableHelpers.ToArray(source, out count);
			if (count > 0)
			{
				Array.Sort(items, 0, count, XNode.DocumentOrderComparer);
				int i = 0;
				while (i != count)
				{
					yield return items[i];
					int num = i + 1;
					i = num;
				}
			}
		}

		public static void Remove(this IEnumerable<XAttribute> source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			int length;
			XAttribute[] array = System.Collections.Generic.EnumerableHelpers.ToArray(source, out length);
			for (int i = 0; i < length; i++)
			{
				array[i]?.Remove();
			}
		}

		public static void Remove<T>(this IEnumerable<T> source) where T : XNode
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			int length;
			T[] array = System.Collections.Generic.EnumerableHelpers.ToArray(source, out length);
			for (int i = 0; i < length; i++)
			{
				array[i]?.Remove();
			}
		}

		private static IEnumerable<XAttribute> GetAttributes(IEnumerable<XElement> source, XName name)
		{
			foreach (XElement e in source)
			{
				if (e == null)
				{
					continue;
				}
				XAttribute a = e.lastAttr;
				if (a == null)
				{
					continue;
				}
				do
				{
					a = a.next;
					if (name == null || a.name == name)
					{
						yield return a;
					}
				}
				while (a.parent == e && a != e.lastAttr);
			}
		}

		private static IEnumerable<XElement> GetAncestors<T>(IEnumerable<T> source, XName name, bool self) where T : XNode
		{
			foreach (T item in source)
			{
				if (item == null)
				{
					continue;
				}
				for (XElement e = (self ? ((XNode)item) : ((XNode)item.parent)) as XElement; e != null; e = e.parent as XElement)
				{
					if (name == null || e.name == name)
					{
						yield return e;
					}
				}
			}
		}

		private static IEnumerable<XNode> GetDescendantNodes<T>(IEnumerable<T> source, bool self) where T : XContainer
		{
			foreach (T root in source)
			{
				if (root == null)
				{
					continue;
				}
				if (self)
				{
					yield return root;
				}
				XNode i = root;
				while (true)
				{
					XNode firstNode;
					if (i is XContainer xContainer && (firstNode = xContainer.FirstNode) != null)
					{
						i = firstNode;
					}
					else
					{
						while (i != null && i != root && i == i.parent.content)
						{
							i = i.parent;
						}
						if (i == null || i == root)
						{
							break;
						}
						i = i.next;
					}
					yield return i;
				}
			}
		}

		private static IEnumerable<XElement> GetDescendants<T>(IEnumerable<T> source, XName name, bool self) where T : XContainer
		{
			foreach (T root in source)
			{
				if (root == null)
				{
					continue;
				}
				if (self)
				{
					XElement xElement = (XElement)(object)root;
					if (name == null || xElement.name == name)
					{
						yield return xElement;
					}
				}
				XNode i = root;
				XContainer xContainer = root;
				while (true)
				{
					if (xContainer != null && xContainer.content is XNode)
					{
						i = ((XNode)xContainer.content).next;
					}
					else
					{
						while (i != null && i != root && i == i.parent.content)
						{
							i = i.parent;
						}
						if (i == null || i == root)
						{
							break;
						}
						i = i.next;
					}
					XElement e = i as XElement;
					if (e != null && (name == null || e.name == name))
					{
						yield return e;
					}
					xContainer = e;
				}
			}
		}

		private static IEnumerable<XElement> GetElements<T>(IEnumerable<T> source, XName name) where T : XContainer
		{
			foreach (T root in source)
			{
				if (root == null)
				{
					continue;
				}
				XNode i = root.content as XNode;
				if (i == null)
				{
					continue;
				}
				do
				{
					i = i.next;
					if (i is XElement xElement && (name == null || xElement.name == name))
					{
						yield return xElement;
					}
				}
				while (i.parent == root && i != root.content);
			}
		}
	}
	internal class LineInfoAnnotation
	{
		internal int lineNumber;

		internal int linePosition;

		public LineInfoAnnotation(int lineNumber, int linePosition)
		{
			this.lineNumber = lineNumber;
			this.linePosition = linePosition;
		}
	}
	internal class LineInfoEndElementAnnotation : LineInfoAnnotation
	{
		public LineInfoEndElementAnnotation(int lineNumber, int linePosition)
			: base(lineNumber, linePosition)
		{
		}
	}
	public class XAttribute : XObject
	{
		internal XAttribute next;

		internal XName name;

		internal string value;

		public static IEnumerable<XAttribute> EmptySequence => Array.Empty<XAttribute>();

		public bool IsNamespaceDeclaration
		{
			get
			{
				string namespaceName = name.NamespaceName;
				if (namespaceName.Length == 0)
				{
					return name.LocalName == "xmlns";
				}
				return (object)namespaceName == "http://www.w3.org/2000/xmlns/";
			}
		}

		public XName Name => name;

		public XAttribute NextAttribute
		{
			get
			{
				if (parent == null || ((XElement)parent).lastAttr == this)
				{
					return null;
				}
				return next;
			}
		}

		public override XmlNodeType NodeType => XmlNodeType.Attribute;

		public XAttribute PreviousAttribute
		{
			get
			{
				if (parent == null)
				{
					return null;
				}
				XAttribute lastAttr = ((XElement)parent).lastAttr;
				while (lastAttr.next != this)
				{
					lastAttr = lastAttr.next;
				}
				if (lastAttr == ((XElement)parent).lastAttr)
				{
					return null;
				}
				return lastAttr;
			}
		}

		public string Value
		{
			get
			{
				return value;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				ValidateAttribute(name, value);
				bool num = NotifyChanging(this, XObjectChangeEventArgs.Value);
				this.value = value;
				if (num)
				{
					NotifyChanged(this, XObjectChangeEventArgs.Value);
				}
			}
		}

		public XAttribute(XName name, object value)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			string stringValue = XContainer.GetStringValue(value);
			ValidateAttribute(name, stringValue);
			this.name = name;
			this.value = stringValue;
		}

		public XAttribute(XAttribute other)
		{
			if (other == null)
			{
				throw new ArgumentNullException("other");
			}
			name = other.name;
			value = other.value;
		}

		public void Remove()
		{
			if (parent == null)
			{
				throw new InvalidOperationException("The parent is missing.");
			}
			((XElement)parent).RemoveAttribute(this);
		}

		public void SetValue(object value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			Value = XContainer.GetStringValue(value);
		}

		public override string ToString()
		{
			using StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
			XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
			xmlWriterSettings.ConformanceLevel = ConformanceLevel.Fragment;
			using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, xmlWriterSettings))
			{
				xmlWriter.WriteAttributeString(GetPrefixOfNamespace(name.Namespace), name.LocalName, name.NamespaceName, value);
			}
			return stringWriter.ToString().Trim();
		}

		[CLSCompliant(false)]
		public static explicit operator string(XAttribute attribute)
		{
			return attribute?.value;
		}

		[CLSCompliant(false)]
		public static explicit operator bool(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant());
		}

		[CLSCompliant(false)]
		public static explicit operator bool?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant());
		}

		[CLSCompliant(false)]
		public static explicit operator int(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToInt32(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator int?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToInt32(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator uint(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToUInt32(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator uint?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToUInt32(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator long(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToInt64(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator long?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToInt64(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator ulong(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToUInt64(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator ulong?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToUInt64(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator float(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToSingle(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator float?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToSingle(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator double(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToDouble(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator double?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToDouble(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator decimal(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToDecimal(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator decimal?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToDecimal(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator DateTime(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
		}

		[CLSCompliant(false)]
		public static explicit operator DateTime?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
		}

		[CLSCompliant(false)]
		public static explicit operator DateTimeOffset(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToDateTimeOffset(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator DateTimeOffset?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToDateTimeOffset(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator TimeSpan(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToTimeSpan(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator TimeSpan?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToTimeSpan(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator Guid(XAttribute attribute)
		{
			if (attribute == null)
			{
				throw new ArgumentNullException("attribute");
			}
			return XmlConvert.ToGuid(attribute.value);
		}

		[CLSCompliant(false)]
		public static explicit operator Guid?(XAttribute attribute)
		{
			if (attribute == null)
			{
				return null;
			}
			return XmlConvert.ToGuid(attribute.value);
		}

		internal int GetDeepHashCode()
		{
			return name.GetHashCode() ^ value.GetHashCode();
		}

		internal string GetPrefixOfNamespace(XNamespace ns)
		{
			string namespaceName = ns.NamespaceName;
			if (namespaceName.Length == 0)
			{
				return string.Empty;
			}
			if (parent != null)
			{
				return ((XElement)parent).GetPrefixOfNamespace(ns);
			}
			if ((object)namespaceName == "http://www.w3.org/XML/1998/namespace")
			{
				return "xml";
			}
			if ((object)namespaceName == "http://www.w3.org/2000/xmlns/")
			{
				return "xmlns";
			}
			return null;
		}

		private static void ValidateAttribute(XName name, string value)
		{
			string namespaceName = name.NamespaceName;
			if ((object)namespaceName == "http://www.w3.org/2000/xmlns/")
			{
				if (value.Length == 0)
				{
					throw new ArgumentException(SR.Format("The prefix '{0}' cannot be bound to the empty namespace name.", name.LocalName));
				}
				if (value == "http://www.w3.org/XML/1998/namespace")
				{
					if (name.LocalName != "xml")
					{
						throw new ArgumentException("The prefix 'xml' is bound to the namespace name 'http://www.w3.org/XML/1998/namespace'. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.");
					}
					return;
				}
				if (value == "http://www.w3.org/2000/xmlns/")
				{
					throw new ArgumentException("The prefix 'xmlns' is bound to the namespace name 'http://www.w3.org/2000/xmlns/'. It must not be declared. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.");
				}
				string localName = name.LocalName;
				if (localName == "xml")
				{
					throw new ArgumentException("The prefix 'xml' is bound to the namespace name 'http://www.w3.org/XML/1998/namespace'. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.");
				}
				if (localName == "xmlns")
				{
					throw new ArgumentException("The prefix 'xmlns' is bound to the namespace name 'http://www.w3.org/2000/xmlns/'. It must not be declared. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.");
				}
			}
			else if (namespaceName.Length == 0 && name.LocalName == "xmlns")
			{
				if (value == "http://www.w3.org/XML/1998/namespace")
				{
					throw new ArgumentException("The prefix 'xml' is bound to the namespace name 'http://www.w3.org/XML/1998/namespace'. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.");
				}
				if (value == "http://www.w3.org/2000/xmlns/")
				{
					throw new ArgumentException("The prefix 'xmlns' is bound to the namespace name 'http://www.w3.org/2000/xmlns/'. It must not be declared. Other prefixes must not be bound to this namespace name, and it must not be declared as the default namespace.");
				}
			}
		}
	}
	public class XCData : XText
	{
		public override XmlNodeType NodeType => XmlNodeType.CDATA;

		public XCData(string value)
			: base(value)
		{
		}

		public XCData(XCData other)
			: base(other)
		{
		}

		internal XCData(XmlReader r)
			: base(r)
		{
		}

		public override void WriteTo(XmlWriter writer)
		{
			if (writer == null)
			{
				throw new ArgumentNullException("writer");
			}
			writer.WriteCData(text);
		}

		public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken)
		{
			if (writer == null)
			{
				throw new ArgumentNullException("writer");
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return writer.WriteCDataAsync(text);
		}

		internal override XNode CloneNode()
		{
			return new XCData(this);
		}
	}
	public class XComment : XNode
	{
		internal string value;

		public override XmlNodeType NodeType => XmlNodeType.Comment;

		public string Value
		{
			get
			{
				return value;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value");
				}
				bool num = NotifyChanging(this, XObjectChangeEventArgs.Value);
				this.value = value;
				if (num)
				{
					NotifyChanged(this, XObjectChangeEventArgs.Value);
				}
			}
		}

		public XComment(string value)
		{
			if (value == null)
			{
				throw new ArgumentNullException("value");
			}
			this.value = value;
		}

		public XComment(XComment other)
		{
			if (other == null)
			{
				throw new ArgumentNullException("other");
			}
			value = other.value;
		}

		internal XComment(XmlReader r)
		{
			value = r.Value;
			r.Read();
		}

		public override void WriteTo(XmlWriter writer)
		{
			if (writer == null)
			{
				throw new ArgumentNullException("writer");
			}
			writer.WriteComment(value);
		}

		public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken)
		{
			if (writer == null)
			{
				throw new ArgumentNullException("writer");
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return writer.WriteCommentAsync(value);
		}

		internal override XNode CloneNode()
		{
			return new XComment(this);
		}

		internal override bool DeepEquals(XNode node)
		{
			if (node is XComment xComment)
			{
				return value == xComment.value;
			}
			return false;
		}

		internal override int GetDeepHashCode()
		{
			return value.GetHashCode();
		}
	}
	public abstract class XContainer : XNode
	{
		private sealed class ContentReader
		{
			private readonly NamespaceCache _eCache;

			private readonly NamespaceCache _aCache;

			private readonly IXmlLineInfo _lineInfo;

			private XContainer _currentContainer;

			private string _baseUri;

			public ContentReader(XContainer rootContainer)
			{
				_currentContainer = rootContainer;
			}

			public ContentReader(XContainer rootContainer, XmlReader r, LoadOptions o)
			{
				_currentContainer = rootContainer;
				_baseUri = (((o & LoadOptions.SetBaseUri) != 0) ? r.BaseURI : null);
				_lineInfo = (((o & LoadOptions.SetLineInfo) != 0) ? (r as IXmlLineInfo) : null);
			}

			public bool ReadContentFrom(XContainer rootContainer, XmlReader r)
			{
				switch (r.NodeType)
				{
				case XmlNodeType.Element:
				{
					XElement xElement = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName));
					if (r.MoveToFirstAttribute())
					{
						do
						{
							xElement.AppendAttributeSkipNotify(new XAttribute(_aCache.Get((r.Prefix.Length == 0) ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value));
						}
						while (r.MoveToNextAttribute());
						r.MoveToElement();
					}
					_currentContainer.AddNodeSkipNotify(xElement);
					if (!r.IsEmptyElement)
					{
						_currentContainer = xElement;
					}
					break;
				}
				case XmlNodeType.EndElement:
					if (_currentContainer.content == null)
					{
						_currentContainer.content = string.Empty;
					}
					if (_currentContainer == rootContainer)
					{
						return false;
					}
					_currentContainer = _currentContainer.parent;
					break;
				case XmlNodeType.Text:
				case XmlNodeType.Whitespace:
				case XmlNodeType.SignificantWhitespace:
					_currentContainer.AddStringSkipNotify(r.Value);
					break;
				case XmlNodeType.CDATA:
					_currentContainer.AddNodeSkipNotify(new XCData(r.Value));
					break;
				case XmlNodeType.Comment:
					_currentContainer.AddNodeSkipNotify(new XComment(r.Value));
					break;
				case XmlNodeType.ProcessingInstruction:
					_currentContainer.AddNodeSkipNotify(new XProcessingInstruction(r.Name, r.Value));
					break;
				case XmlNodeType.DocumentType:
					_currentContainer.AddNodeSkipNotify(new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value));
					break;
				case XmlNodeType.EntityReference:
					if (!r.CanResolveEntity)
					{
						throw new InvalidOperationException("The XmlReader cannot resolve entity references.");
					}
					r.ResolveEntity();
					break;
				default:
					throw new InvalidOperationException(SR.Format("The XmlReader should not be on a node of type {0}.", r.NodeType));
				case XmlNodeType.EndEntity:
					break;
				}
				return true;
			}

			public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o)
			{
				XNode xNode = null;
				string baseURI = r.BaseURI;
				switch (r.NodeType)
				{
				case XmlNodeType.Element:
				{
					XElement xElement2 = new XElement(_eCache.Get(r.NamespaceURI).GetName(r.LocalName));
					if (_baseUri != null && _baseUri != baseURI)
					{
						xElement2.SetBaseUri(baseURI);
					}
					if (_lineInfo != null && _lineInfo.HasLineInfo())
					{
						xElement2.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
					}
					if (r.MoveToFirstAttribute())
					{
						do
						{
							XAttribute xAttribute = new XAttribute(_aCache.Get((r.Prefix.Length == 0) ? string.Empty : r.NamespaceURI).GetName(r.LocalName), r.Value);
							if (_lineInfo != null && _lineInfo.HasLineInfo())
							{
								xAttribute.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
							}
							xElement2.AppendAttributeSkipNotify(xAttribute);
						}
						while (r.MoveToNextAttribute());
						r.MoveToElement();
					}
					_currentContainer.AddNodeSkipNotify(xElement2);
					if (!r.IsEmptyElement)
					{
						_currentContainer = xElement2;
						if (_baseUri != null)
						{
							_baseUri = baseURI;
						}
					}
					break;
				}
				case XmlNodeType.EndElement:
					if (_currentContainer.content == null)
					{
						_currentContainer.content = string.Empty;
					}
					if (_currentContainer is XElement xElement && _lineInfo != null && _lineInfo.HasLineInfo())
					{
						xElement.SetEndElementLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
					}
					if (_currentContainer == rootContainer)
					{
						return false;
					}
					if (_baseUri != null && _currentContainer.HasBaseUri)
					{
						_baseUri = _currentContainer.parent.BaseUri;
					}
					_currentContainer = _currentContainer.parent;
					break;
				case XmlNodeType.Text:
				case XmlNodeType.Whitespace:
				case XmlNodeType.SignificantWhitespace:
					if ((_baseUri != null && _baseUri != baseURI) || (_lineInfo != null && _lineInfo.HasLineInfo()))
					{
						xNode = new XText(r.Value);
					}
					else
					{
						_currentContainer.AddStringSkipNotify(r.Value);
					}
					break;
				case XmlNodeType.CDATA:
					xNode = new XCData(r.Value);
					break;
				case XmlNodeType.Comment:
					xNode = new XComment(r.Value);
					break;
				case XmlNodeType.ProcessingInstruction:
					xNode = new XProcessingInstruction(r.Name, r.Value);
					break;
				case XmlNodeType.DocumentType:
					xNode = new XDocumentType(r.LocalName, r.GetAttribute("PUBLIC"), r.GetAttribute("SYSTEM"), r.Value);
					break;
				case XmlNodeType.EntityReference:
					if (!r.CanResolveEntity)
					{
						throw new InvalidOperationException("The XmlReader cannot resolve entity references.");
					}
					r.ResolveEntity();
					break;
				default:
					throw new InvalidOperationException(SR.Format("The XmlReader should not be on a node of type {0}.", r.NodeType));
				case XmlNodeType.EndEntity:
					break;
				}
				if (xNode != null)
				{
					if (_baseUri != null && _baseUri != baseURI)
					{
						xNode.SetBaseUri(baseURI);
					}
					if (_lineInfo != null && _lineInfo.HasLineInfo())
					{
						xNode.SetLineInfo(_lineInfo.LineNumber, _lineInfo.LinePosition);
					}
					_currentContainer.AddNodeSkipNotify(xNode);
					xNode = null;
				}
				return true;
			}
		}

		internal object content;

		public XNode FirstNode => LastNode?.next;

		public XNode LastNode
		{
			get
			{
				if (content == null)
				{
					return null;
				}
				if (content is XNode result)
				{
					return result;
				}
				if (content is string text)
				{
					if (text.Length == 0)
					{
						return null;
					}
					XText xText = new XText(text);
					xText.parent = this;
					xText.next = xText;
					Interlocked.CompareExchange<object>(ref content, (object)xText, (object)text);
				}
				return (XNode)content;
			}
		}

		internal XContainer()
		{
		}

		internal XContainer(XContainer other)
		{
			if (other == null)
			{
				throw new ArgumentNullException("other");
			}
			if (other.content is string)
			{
				content = other.content;
				return;
			}
			XNode xNode = (XNode)other.content;
			if (xNode != null)
			{
				do
				{
					xNode = xNode.next;
					AppendNodeSkipNotify(xNode.CloneNode());
				}
				while (xNode != other.content);
			}
		}

		public void Add(object content)
		{
			if (SkipNotify())
			{
				AddContentSkipNotify(content);
			}
			else
			{
				if (content == null)
				{
					return;
				}
				if (content is XNode n)
				{
					AddNode(n);
					return;
				}
				if (content is string s)
				{
					AddString(s);
					return;
				}
				if (content is XAttribute a)
				{
					AddAttribute(a);
					return;
				}
				if (content is XStreamingElement other)
				{
					AddNode(new XElement(other));
					return;
				}
				if (content is object[] array)
				{
					object[] array2 = array;
					foreach (object obj in array2)
					{
						Add(obj);
					}
					return;
				}
				if (content is IEnumerable enumerable)
				{
					{
						foreach (object item in enumerable)
						{
							Add(item);
						}
						return;
					}
				}
				AddString(GetStringValue(content));
			}
		}

		public void Add(params object[] content)
		{
			Add((object)content);
		}

		public void AddFirst(object content)
		{
			new Inserter(this, null).Add(content);
		}

		public void AddFirst(params object[] content)
		{
			AddFirst((object)content);
		}

		public XmlWriter CreateWriter()
		{
			XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
			xmlWriterSettings.ConformanceLevel = ((!(this is XDocument)) ? ConformanceLevel.Fragment : ConformanceLevel.Document);
			return XmlWriter.Create(new XNodeBuilder(this), xmlWriterSettings);
		}

		public IEnumerable<XNode> DescendantNodes()
		{
			return GetDescendantNodes(self: false);
		}

		public IEnumerable<XElement> Descendants()
		{
			return GetDescendants(null, self: false);
		}

		public IEnumerable<XElement> Descendants(XName name)
		{
			if (!(name != null))
			{
				return XElement.EmptySequence;
			}
			return GetDescendants(name, self: false);
		}

		public XElement Element(XName name)
		{
			XNode xNode = content as XNode;
			if (xNode != null)
			{
				do
				{
					xNode = xNode.next;
					if (xNode is XElement xElement && xElement.name == name)
					{
						return xElement;
					}
				}
				while (xNode != content);
			}
			return null;
		}

		public IEnumerable<XElement> Elements()
		{
			return GetElements(null);
		}

		public IEnumerable<XElement> Elements(XName name)
		{
			if (!(name != null))
			{
				return XElement.EmptySequence;
			}
			return GetElements(name);
		}

		public IEnumerable<XNode> Nodes()
		{
			XNode i = LastNode;
			if (i != null)
			{
				do
				{
					i = i.next;
					yield return i;
				}
				while (i.parent == this && i != content);
			}
		}

		public void RemoveNodes()
		{
			if (SkipNotify())
			{
				RemoveNodesSkipNotify();
				return;
			}
			while (content != null)
			{
				if (content is string text)
				{
					if (text.Length > 0)
					{
						ConvertTextToNode();
					}
					else if (this is XElement)
					{
						NotifyChanging(this, XObjectChangeEventArgs.Value);
						if (text != content)
						{
							throw new InvalidOperationException("This operation was corrupted by external code.");
						}
						content = null;
						NotifyChanged(this, XObjectChangeEventArgs.Value);
					}
					else
					{
						content = null;
					}
				}
				if (content is XNode xNode)
				{
					XNode xNode2 = xNode.next;
					NotifyChanging(xNode2, XObjectChangeEventArgs.Remove);
					if (xNode != content || xNode2 != xNode.next)
					{
						throw new InvalidOperationException("This operation was corrupted by external code.");
					}
					if (xNode2 != xNode)
					{
						xNode.next = xNode2.next;
					}
					else
					{
						content = null;
					}
					xNode2.parent = null;
					xNode2.next = null;
					NotifyChanged(xNode2, XObjectChangeEventArgs.Remove);
				}
			}
		}

		public void ReplaceNodes(object content)
		{
			content = GetContentSnapshot(content);
			RemoveNodes();
			Add(content);
		}

		public void ReplaceNodes(params object[] content)
		{
			ReplaceNodes((object)content);
		}

		internal virtual void AddAttribute(XAttribute a)
		{
		}

		internal virtual void AddAttributeSkipNotify(XAttribute a)
		{
		}

		internal void AddContentSkipNotify(object content)
		{
			if (content == null)
			{
				return;
			}
			if (content is XNode n)
			{
				AddNodeSkipNotify(n);
				return;
			}
			if (content is string s)
			{
				AddStringSkipNotify(s);
				return;
			}
			if (content is XAttribute a)
			{
				AddAttributeSkipNotify(a);
				return;
			}
			if (content is XStreamingElement other)
			{
				AddNodeSkipNotify(new XElement(other));
				return;
			}
			if (content is object[] array)
			{
				object[] array2 = array;
				foreach (object obj in array2)
				{
					AddContentSkipNotify(obj);
				}
				return;
			}
			if (content is IEnumerable enumerable)
			{
				{
					foreach (object item in enumerable)
					{
						AddContentSkipNotify(item);
					}
					return;
				}
			}
			AddStringSkipNotify(GetStringValue(content));
		}

		internal void AddNode(XNode n)
		{
			ValidateNode(n, this);
			if (n.parent != null)
			{
				n = n.CloneNode();
			}
			else
			{
				XNode xNode = this;
				while (xNode.parent != null)
				{
					xNode = xNode.parent;
				}
				if (n == xNode)
				{
					n = n.CloneNode();
				}
			}
			ConvertTextToNode();
			AppendNode(n);
		}

		internal void AddNodeSkipNotify(XNode n)
		{
			ValidateNode(n, this);
			if (n.parent != null)
			{
				n = n.CloneNode();
			}
			else
			{
				XNode xNode = this;
				while (xNode.parent != null)
				{
					xNode = xNode.parent;
				}
				if (n == xNode)
				{
					n = n.CloneNode();
				}
			}
			ConvertTextToNode();
			AppendNodeSkipNotify(n);
		}

		internal void AddString(string s)
		{
			ValidateString(s);
			if (content == null)
			{
				if (s.Length > 0)
				{
					AppendNode(new XText(s));
				}
				else if (this is XElement)
				{
					NotifyChanging(this, XObjectChangeEventArgs.Value);
					if (content != null)
					{
						throw new InvalidOperationException("This operation was corrupted by external code.");
					}
					content = s;
					NotifyChanged(this, XObjectChangeEventArgs.Value);
				}
				else
				{
					content = s;
				}
			}
			else if (s.Length > 0)
			{
				ConvertTextToNode();
				if (content is XText xText && !(xText is XCData))
				{
					xText.Value += s;
				}
				else
				{
					AppendNode(new XText(s));
				}
			}
		}

		internal void AddStringSkipNotify(string s)
		{
			ValidateString(s);
			if (content == null)
			{
				content = s;
			}
			else if (s.Length > 0)
			{
				if (content is string text)
				{
					content = text + s;
				}
				else if (content is XText xText && !(xText is XCData))
				{
					xText.text += s;
				}
				else
				{
					AppendNodeSkipNotify(new XText(s));
				}
			}
		}

		internal void AppendNode(XNode n)
		{
			bool num = NotifyChanging(n, XObjectChangeEventArgs.Add);
			if (n.parent != null)
			{
				throw new InvalidOperationException("This operation was corrupted by external code.");
			}
			AppendNodeSkipNotify(n);
			if (num)
			{
				NotifyChanged(n, XObjectChangeEventArgs.Add);
			}
		}

		internal void AppendNodeSkipNotify(XNode n)
		{
			n.parent = this;
			if (content == null || content is string)
			{
				n.next = n;
			}
			else
			{
				XNode xNode = (XNode)content;
				n.next = xNode.next;
				xNode.next = n;
			}
			content = n;
		}

		internal override void AppendText(StringBuilder sb)
		{
			if (content is string value)
			{
				sb.Append(value);
				return;
			}
			XNode xNode = (XNode)content;
			if (xNode != null)
			{
				do
				{
					xNode = xNode.next;
					xNode.AppendText(sb);
				}
				while (xNode != content);
			}
		}

		private string GetTextOnly()
		{
			if (content == null)
			{
				return null;
			}
			string text = content as string;
			if (text == null)
			{
				XNode xNode = (XNode)content;
				do
				{
					xNode = xNode.next;
					if (xNode.NodeType != XmlNodeType.Text)
					{
						return null;
					}
					text += ((XText)xNode).Value;
				}
				while (xNode != content);
			}
			return text;
		}

		private string CollectText(ref XNode n)
		{
			string text = "";
			while (n != null && n.NodeType == XmlNodeType.Text)
			{
				text += ((XText)n).Value;
				n = ((n != content) ? n.next : null);
			}
			return text;
		}

		internal bool ContentsEqual(XContainer e)
		{
			if (content == e.content)
			{
				return true;
			}
			string textOnly = GetTextOnly();
			if (textOnly != null)
			{
				return textOnly == e.GetTextOnly();
			}
			XNode xNode = content as XNode;
			XNode xNode2 = e.content as XNode;
			if (xNode != null && xNode2 != null)
			{
				xNode = xNode.next;
				xNode2 = xNode2.next;
				while (!(CollectText(ref xNode) != e.CollectText(ref xNode2)))
				{
					if (xNode == null && xNode2 == null)
					{
						return true;
					}
					if (xNode == null || xNode2 == null || !xNode.DeepEquals(xNode2))
					{
						break;
					}
					xNode = ((xNode != content) ? xNode.next : null);
					xNode2 = ((xNode2 != e.content) ? xNode2.next : null);
				}
			}
			return false;
		}

		internal int ContentsHashCode()
		{
			string textOnly = GetTextOnly();
			if (textOnly != null)
			{
				return textOnly.GetHashCode();
			}
			int num = 0;
			XNode n = content as XNode;
			if (n != null)
			{
				do
				{
					n = n.next;
					string text = CollectText(ref n);
					if (text.Length > 0)
					{
						num ^= text.GetHashCode();
					}
					if (n == null)
					{
						break;
					}
					num ^= n.GetDeepHashCode();
				}
				while (n != content);
			}
			return num;
		}

		internal void ConvertTextToNode()
		{
			string value = content as string;
			if (!string.IsNullOrEmpty(value))
			{
				XText xText = new XText(value);
				xText.parent = this;
				xText.next = xText;
				content = xText;
			}
		}

		internal IEnumerable<XNode> GetDescendantNodes(bool self)
		{
			if (self)
			{
				yield return this;
			}
			XNode i = this;
			while (true)
			{
				XNode firstNode;
				if (i is XContainer xContainer && (firstNode = xContainer.FirstNode) != null)
				{
					i = firstNode;
				}
				else
				{
					while (i != null && i != this && i == i.parent.content)
					{
						i = i.parent;
					}
					if (i == null || i == this)
					{
						break;
					}
					i = i.next;
				}
				yield return i;
			}
		}

		internal IEnumerable<XElement> GetDescendants(XName name, bool self)
		{
			if (self)
			{
				XElement xElement = (XElement)this;
				if (name == null || xElement.name == name)
				{
					yield return xElement;
				}
			}
			XNode i = this;
			XContainer xContainer = this;
			while (true)
			{
				if (xContainer != null && xContainer.content is XNode)
				{
					i = ((XNode)xContainer.content).next;
				}
				else
				{
					while (i != this && i == i.parent.content)
					{
						i = i.parent;
					}
					if (i == this)
					{
						break;
					}
					i = i.next;
				}
				XElement e = i as XElement;
				if (e != null && (name == null || e.name == name))
				{
					yield return e;
				}
				xContainer = e;
			}
		}

		private IEnumerable<XElement> GetElements(XName name)
		{
			XNode i = content as XNode;
			if (i == null)
			{
				yield break;
			}
			do
			{
				i = i.next;
				if (i is XElement xElement && (name == null || xElement.name == name))
				{
					yield return xElement;
				}
			}
			while (i.parent == this && i != content);
		}

		internal static string GetStringValue(object value)
		{
			if (value is string result)
			{
				return result;
			}
			string text;
			if (value is double)
			{
				text = XmlConvert.ToString((double)value);
			}
			else if (value is float)
			{
				text = XmlConvert.ToString((float)value);
			}
			else if (value is decimal)
			{
				text = XmlConvert.ToString((decimal)value);
			}
			else if (value is bool)
			{
				text = XmlConvert.ToString((bool)value);
			}
			else if (value is DateTime)
			{
				text = XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind);
			}
			else if (value is DateTimeOffset)
			{
				text = XmlConvert.ToString((DateTimeOffset)value);
			}
			else if (value is TimeSpan)
			{
				text = XmlConvert.ToString((TimeSpan)value);
			}
			else
			{
				if (value is XObject)
				{
					throw new ArgumentException("An XObject cannot be used as a value.");
				}
				text = value.ToString();
			}
			if (text == null)
			{
				throw new ArgumentException("The argument cannot be converted to a string.");
			}
			return text;
		}

		internal void ReadContentFrom(XmlReader r)
		{
			if (r.ReadState != ReadState.Interactive)
			{
				throw new InvalidOperationException("The XmlReader state should be Interactive.");
			}
			ContentReader contentReader = new ContentReader(this);
			while (contentReader.ReadContentFrom(this, r) && r.Read())
			{
			}
		}

		internal void ReadContentFrom(XmlReader r, LoadOptions o)
		{
			if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
			{
				ReadContentFrom(r);
				return;
			}
			if (r.ReadState != ReadState.Interactive)
			{
				throw new InvalidOperationException("The XmlReader state should be Interactive.");
			}
			ContentReader contentReader = new ContentReader(this, r, o);
			while (contentReader.ReadContentFrom(this, r, o) && r.Read())
			{
			}
		}

		internal async Task ReadContentFromAsync(XmlReader r, CancellationToken cancellationToken)
		{
			if (r.ReadState != ReadState.Interactive)
			{
				throw new InvalidOperationException("The XmlReader state should be Interactive.");
			}
			ContentReader cr = new ContentReader(this);
			bool flag;
			do
			{
				cancellationToken.ThrowIfCancellationRequested();
				flag = cr.ReadContentFrom(this, r);
				if (flag)
				{
					flag = await r.ReadAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
			}
			while (flag);
		}

		internal async Task ReadContentFromAsync(XmlReader r, LoadOptions o, CancellationToken cancellationToken)
		{
			if ((o & (LoadOptions.SetBaseUri | LoadOptions.SetLineInfo)) == 0)
			{
				await ReadContentFromAsync(r, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				return;
			}
			if (r.ReadState != ReadState.Interactive)
			{
				throw new InvalidOperationException("The XmlReader state should be Interactive.");
			}
			ContentReader cr = new ContentReader(this, r, o);
			bool flag;
			do
			{
				cancellationToken.ThrowIfCancellationRequested();
				flag = cr.ReadContentFrom(this, r, o);
				if (flag)
				{
					flag = await r.ReadAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
			}
			while (flag);
		}

		internal void RemoveNode(XNode n)
		{
			bool flag = NotifyChanging(n, XObjectChangeEventArgs.Remove);
			if (n.parent != this)
			{
				throw new InvalidOperationException("This operation was corrupted by external code.");
			}
			XNode xNode = (XNode)content;
			while (xNode.next != n)
			{
				xNode = xNode.next;
			}
			if (xNode == n)
			{
				content = null;
			}
			else
			{
				if (content == n)
				{
					content = xNode;
				}
				xNode.next = n.next;
			}
			n.parent = null;
			n.next = null;
			if (flag)
			{
				NotifyChanged(n, XObjectChangeEventArgs.Remove);
			}
		}

		private void RemoveNodesSkipNotify()
		{
			XNode xNode = content as XNode;
			if (xNode != null)
			{
				do
				{
					XNode xNode2 = xNode.next;
					xNode.parent = null;
					xNode.next = null;
					xNode = xNode2;
				}
				while (xNode != content);
			}
			content = null;
		}

		internal virtual void ValidateNode(XNode node, XNode previous)
		{
		}

		internal virtual void ValidateString(string s)
		{
		}

		internal void WriteContentTo(XmlWriter writer)
		{
			if (content == null)
			{
				return;
			}
			if (content is string text)
			{
				if (this is XDocument)
				{
					writer.WriteWhitespace(text);
				}
				else
				{
					writer.WriteString(text);
				}
				return;
			}
			XNode xNode = (XNode)content;
			do
			{
				xNode = xNode.next;
				xNode.WriteTo(writer);
			}
			while (xNode != content);
		}

		internal async Task WriteContentToAsync(XmlWriter writer, CancellationToken cancellationToken)
		{
			if (content == null)
			{
				return;
			}
			if (content is string text)
			{
				cancellationToken.ThrowIfCancellationRequested();
				Task task = ((!(this is XDocument)) ? writer.WriteStringAsync(text) : writer.WriteWhitespaceAsync(text));
				await task.ConfigureAwait(continueOnCapturedContext: false);
				return;
			}
			XNode i = (XNode)content;
			do
			{
				i = i.next;
				await i.WriteToAsync(writer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			while (i != content);
		}

		private static void AddContentToList(List<object> list, object content)
		{
			IEnumerable enumerable = ((content is string) ? null : (content as IEnumerable));
			if (enumerable == null)
			{
				list.Add(content);
				return;
			}
			foreach (object item in enumerable)
			{
				if (item != null)
				{
					AddContentToList(list, item);
				}
			}
		}

		internal static object GetContentSnapshot(object content)
		{
			if (content is string || !(content is IEnumerable))
			{
				return content;
			}
			List<object> list = new List<object>();
			AddContentToList(list, content);
			return list;
		}
	}
	public class XDeclaration
	{
		private string _version;

		private string _encoding;

		private string _standalone;

		public string Encoding
		{
			get
			{
				return _encoding;
			}
			set
			{
				_encoding = value;
			}
		}

		public string Standalone
		{
			get
			{
				return _standalone;
			}
			set
			{
				_standalone = value;
			}
		}

		public string Version
		{
			get
			{
				return _version;
			}
			set
			{
				_version = value;
			}
		}

		public XDeclaration(string version, string encoding, string standalone)
		{
			_version = version;
			_encoding = encoding;
			_standalone = standalone;
		}

		public XDeclaration(XDeclaration other)
		{
			if (other == null)
			{
				throw new ArgumentNullException("other");
			}
			_version = other._version;
			_encoding = other._encoding;
			_standalone = other._standalone;
		}

		internal XDeclaration(XmlReader r)
		{
			_version = r.GetAttribute("version");
			_encoding = r.GetAttribute("encoding");
			_standalone = r.GetAttribute("standalone");
			r.Read();
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = System.Text.StringBuilderCache.Acquire();
			stringBuilder.Append("<?xml");
			if (_version != null)
			{
				stringBuilder.Append(" version=\"");
				stringBuilder.Append(_version);
				stringBuilder.Append('"');
			}
			if (_encoding != null)
			{
				stringBuilder.Append(" encoding=\"");
				stringBuilder.Append(_encoding);
				stringBuilder.Append('"');
			}
			if (_standalone != null)
			{
				stringBuilder.Append(" standalone=\"");
				stringBuilder.Append(_standalone);
				stringBuilder.Append('"');
			}
			stringBuilder.Append("?>");
			return System.Text.StringBuilderCache.GetStringAndRelease(stringBuilder);
		}
	}
	public class XDocument : XContainer
	{
		private XDeclaration _declaration;

		public XDeclaration Declaration
		{
			get
			{
				return _declaration;
			}
			set
			{
				_declaration = value;
			}
		}

		public XDocumentType DocumentType => GetFirstNode<XDocumentType>();

		public override XmlNodeType NodeType => XmlNodeType.Document;

		public XElement Root => GetFirstNode<XElement>();

		public XDocument()
		{
		}

		public XDocument(params object[] content)
			: this()
		{
			AddContentSkipNotify(content);
		}

		public XDocument(XDeclaration declaration, params object[] content)
			: this(content)
		{
			_declaration = declaration;
		}

		public XDocument(XDocument other)
			: base(other)
		{
			if (other._declaration != null)
			{
				_declaration = new XDeclaration(other._declaration);
			}
		}

		public static XDocument Load(string uri)
		{
			return Load(uri, LoadOptions.None);
		}

		public static XDocument Load(string uri, LoadOptions options)
		{
			XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options);
			using XmlReader reader = XmlReader.Create(uri, xmlReaderSettings);
			return Load(reader, options);
		}

		public static XDocument Load(Stream stream)
		{
			return Load(stream, LoadOptions.None);
		}

		public static XDocument Load(Stream stream, LoadOptions options)
		{
			XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options);
			using XmlReader reader = XmlReader.Create(stream, xmlReaderSettings);
			return Load(reader, options);
		}

		public static async Task<XDocument> LoadAsync(Stream stream, LoadOptions options, CancellationToken cancellationToken)
		{
			XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options);
			xmlReaderSettings.Async = true;
			using XmlReader r = XmlReader.Create(stream, xmlReaderSettings);
			return await LoadAsync(r, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public static XDocument Load(TextReader textReader)
		{
			return Load(textReader, LoadOptions.None);
		}

		public static XDocument Load(TextReader textReader, LoadOptions options)
		{
			XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options);
			using XmlReader reader = XmlReader.Create(textReader, xmlReaderSettings);
			return Load(reader, options);
		}

		public static async Task<XDocument> LoadAsync(TextReader textReader, LoadOptions options, CancellationToken cancellationToken)
		{
			XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options);
			xmlReaderSettings.Async = true;
			using XmlReader r = XmlReader.Create(textReader, xmlReaderSettings);
			return await LoadAsync(r, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public static XDocument Load(XmlReader reader)
		{
			return Load(reader, LoadOptions.None);
		}

		public static XDocument Load(XmlReader reader, LoadOptions options)
		{
			if (reader == null)
			{
				throw new ArgumentNullException("reader");
			}
			if (reader.ReadState == ReadState.Initial)
			{
				reader.Read();
			}
			XDocument xDocument = InitLoad(reader, options);
			xDocument.ReadContentFrom(reader, options);
			if (!reader.EOF)
			{
				throw new InvalidOperationException("The XmlReader state should be EndOfFile after this operation.");
			}
			if (xDocument.Root == null)
			{
				throw new InvalidOperationException("The root element is missing.");
			}
			return xDocument;
		}

		public static Task<XDocument> LoadAsync(XmlReader reader, LoadOptions options, CancellationToken cancellationToken)
		{
			if (reader == null)
			{
				throw new ArgumentNullException("reader");
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled<XDocument>(cancellationToken);
			}
			return LoadAsyncInternal(reader, options, cancellationToken);
		}

		private static async Task<XDocument> LoadAsyncInternal(XmlReader reader, LoadOptions options, CancellationToken cancellationToken)
		{
			if (reader.ReadState == ReadState.Initial)
			{
				await reader.ReadAsync().ConfigureAwait(continueOnCapturedContext: false);
			}
			XDocument d = InitLoad(reader, options);
			await d.ReadContentFromAsync(reader, options, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (!reader.EOF)
			{
				throw new InvalidOperationException("The XmlReader state should be EndOfFile after this operation.");
			}
			if (d.Root == null)
			{
				throw new InvalidOperationException("The root element is missing.");
			}
			return d;
		}

		private static XDocument InitLoad(XmlReader reader, LoadOptions options)
		{
			XDocument xDocument = new XDocument();
			if ((options & LoadOptions.SetBaseUri) != 0)
			{
				string baseURI = reader.BaseURI;
				if (!string.IsNullOrEmpty(baseURI))
				{
					xDocument.SetBaseUri(baseURI);
				}
			}
			if ((options & LoadOptions.SetLineInfo) != 0 && reader is IXmlLineInfo xmlLineInfo && xmlLineInfo.HasLineInfo())
			{
				xDocument.SetLineInfo(xmlLineInfo.LineNumber, xmlLineInfo.LinePosition);
			}
			if (reader.NodeType == XmlNodeType.XmlDeclaration)
			{
				xDocument.Declaration = new XDeclaration(reader);
			}
			return xDocument;
		}

		public static XDocument Parse(string text)
		{
			return Parse(text, LoadOptions.None);
		}

		public static XDocument Parse(string text, LoadOptions options)
		{
			using StringReader input = new StringReader(text);
			XmlReaderSettings xmlReaderSettings = XNode.GetXmlReaderSettings(options);
			using XmlReader reader = XmlReader.Create(input, xmlReaderSettings);
			return Load(reader, options);
		}

		public void Save(Stream stream)
		{
			Save(stream, GetSaveOptionsFromAnnotations());
		}

		public void Save(Stream stream, SaveOptions options)
		{
			XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options);
			if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
			{
				try
				{
					xmlWriterSettings.Encoding = Encoding.GetEncoding(_declaration.Encoding);
				}
				catch (ArgumentException)
				{
				}
			}
			using XmlWriter writer = XmlWriter.Create(stream, xmlWriterSettings);
			Save(writer);
		}

		public async Task SaveAsync(Stream stream, SaveOptions options, CancellationToken cancellationToken)
		{
			XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options);
			xmlWriterSettings.Async = true;
			if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
			{
				try
				{
					xmlWriterSettings.Encoding = Encoding.GetEncoding(_declaration.Encoding);
				}
				catch (ArgumentException)
				{
				}
			}
			using XmlWriter w = XmlWriter.Create(stream, xmlWriterSettings);
			await WriteToAsync(w, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public void Save(TextWriter textWriter)
		{
			Save(textWriter, GetSaveOptionsFromAnnotations());
		}

		public void Save(TextWriter textWriter, SaveOptions options)
		{
			XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options);
			using XmlWriter writer = XmlWriter.Create(textWriter, xmlWriterSettings);
			Save(writer);
		}

		public void Save(XmlWriter writer)
		{
			WriteTo(writer);
		}

		public async Task SaveAsync(TextWriter textWriter, SaveOptions options, CancellationToken cancellationToken)
		{
			XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options);
			xmlWriterSettings.Async = true;
			using XmlWriter w = XmlWriter.Create(textWriter, xmlWriterSettings);
			await WriteToAsync(w, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
		}

		public void Save(string fileName)
		{
			Save(fileName, GetSaveOptionsFromAnnotations());
		}

		public Task SaveAsync(XmlWriter writer, CancellationToken cancellationToken)
		{
			return WriteToAsync(writer, cancellationToken);
		}

		public void Save(string fileName, SaveOptions options)
		{
			XmlWriterSettings xmlWriterSettings = XNode.GetXmlWriterSettings(options);
			if (_declaration != null && !string.IsNullOrEmpty(_declaration.Encoding))
			{
				try
				{
					xmlWriterSettings.Encoding = Encoding.GetEncoding(_declaration.Encoding);
				}
				catch (ArgumentException)
				{
				}
			}
			using XmlWriter writer = XmlWriter.Create(fileName, xmlWriterSettings);
			Save(writer);
		}

		public override void WriteTo(XmlWriter writer)
		{
			if (writer == null)
			{
				throw new ArgumentNullException("writer");
			}
			if (_declaration != null && _declaration.Standalone == "yes")
			{
				writer.WriteStartDocument(standalone: true);
			}
			else if (_declaration != null && _declaration.Standalone == "no")
			{
				writer.WriteStartDocument(standalone: false);
			}
			else
			{
				writer.WriteStartDocument();
			}
			WriteContentTo(writer);
			writer.WriteEndDocument();
		}

		public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellationToken)
		{
			if (writer == null)
			{
				throw new ArgumentNullException("writer");
			}
			if (cancellationToken.IsCancellationRequested)
			{
				return Task.FromCanceled(cancellationToken);
			}
			return WriteToAsyncInternal(writer, cancellationToken);
		}

		private async Task WriteToAsyncInternal(XmlWriter writer, CancellationToken cancellationToken)
		{
			Task task = ((_declaration != null && _declaration.Standalone == "yes") ? writer.WriteStartDocumentAsync(standalone: true) : ((_declaration == null || !(_declaration.Standalone == "no")) ? writer.WriteStartDocumentAsync() : writer.WriteStartDocumentAsync(standalone: false)));
			await task.ConfigureAwait(continueOnCapturedContext: false);
			await WriteContentToAsync(writer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			await writer.WriteEndDocumentAsync().ConfigureAwait(continueOnCapturedContext: false);
		}

		internal override void AddAttribute(XAttribute a)
		{
			throw new ArgumentException("An attribute cannot be added to content.");
		}

		internal override void AddAttributeSkipNotify(XAttribute a)
		{
			throw new ArgumentException("An attribute cannot be added to content.");
		}

		internal override XNode CloneNode()
		{
			return new XDocument(this);
		}

		internal override bool DeepEquals(XNode node)
		{
			if (node is XDocument e)
			{
				return ContentsEqual(e);
			}
			return false;
		}

		internal override int GetDeepHashCode()
		{
			return ContentsHashCode();
		}

		private T GetFirstNode<T>() where T : XNode
		{
			XNode xNode = content as XNode;
			if (xNode != null)
			{
				do
				{
					xNode = xNode.next;
					if (xNode is T result)
					{
						return result;
					}
				}
				while (xNode != content);
			}
			return null;
		}

		internal static bool IsWhitespace(string s)
		{
			foreach (char c in s)
			{
				if (c != ' ' && c != '\t' && c != '\r' && c != '\n')
				{
					return false;
				}
			}
			return true;
		}

		internal override void ValidateNode(XNode node, XNode previous)
		{
			switch (node.NodeType)
			{
			case XmlNodeType.Text:
				ValidateString(((XText)node).Value);
				break;
			case XmlNodeType.Element:
				ValidateDocument(previous, XmlNodeType.DocumentType, XmlNodeType.None);
				break;
			case XmlNodeType.DocumentType:
				ValidateDocument(previous, XmlNodeType.None, XmlNodeType.Element);
				break;
			case XmlNodeType.CDATA