Decompiled source of OnlineCardChoice v1.1.0

plugins/GeckVolantMarin-OnlineCardChoice.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using DiskCardGame;
using InscryptionAPI.Boons;
using InscryptionAPI.Card;
using InscryptionAPI.Helpers;
using InscryptionAPI.Nodes;
using Microsoft.CodeAnalysis;
using Pixelplacement;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("GeckVolantMarin-OnlineCardChoice")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("GeckVolantMarin-OnlineCardChoice")]
[assembly: AssemblyTitle("GeckVolantMarin-OnlineCardChoice")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace GeckVolantMarin.OnlineCardChoice
{
	public class Medal : CardAppearanceBehaviour
	{
		public static readonly Appearance id = CardAppearanceBehaviourManager.Add("GeckVolantMarin-OnlineCardChoice", "Medal", typeof(Medal)).Id;

		private Material baseMat;

		public override void ApplyAppearance()
		{
			Texture2D imageAsTexture = TextureHelper.GetImageAsTexture("GeckVolantMarin-OnlineCardChoice/assets/Cards/medal/decal.png", (FilterMode)0);
			((Texture)imageAsTexture).filterMode = (FilterMode)0;
			((CardAppearanceBehaviour)this).Card.RenderInfo.baseTextureOverride = (Texture)(object)imageAsTexture;
		}

		public override void ResetAppearance()
		{
		}
	}
	public class Shredded : CardAppearanceBehaviour
	{
		public static readonly Appearance id = CardAppearanceBehaviourManager.Add("GeckVolantMarin-OnlineCardChoice", "Shredded", typeof(Shredded)).Id;

		private Material baseMat;

		public override void ApplyAppearance()
		{
			Texture2D imageAsTexture = TextureHelper.GetImageAsTexture("GeckVolantMarin-OnlineCardChoice/assets/Cards/shredded/decal.png", (FilterMode)0);
			((Texture)imageAsTexture).filterMode = (FilterMode)0;
			((CardAppearanceBehaviour)this).Card.RenderInfo.baseTextureOverride = (Texture)(object)imageAsTexture;
		}

		public override void ResetAppearance()
		{
		}
	}
	public static class NewCards
	{
		public static CardInfo shredded;

		public static CardInfo medal;

		private static void createShredded()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected I4, but got Unknown
			shredded = CardManager.New("GeckVolantMarin-OnlineCardChoice", "Shredded", "Shredded", 0, 0, "This card was damaged during the shipping, but it is still useable.");
			CardExtensions.AddAppearances(shredded, (Appearance[])(object)new Appearance[1] { (Appearance)(int)Shredded.id });
		}

		private static void createMedal()
		{
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Expected I4, but got Unknown
			medal = CardManager.New("GeckVolantMarin-OnlineCardChoice", "Medal", "First Medal", 0, 10, "For the first player who used this mod. Thank you so much!");
			CardExtensions.AddAbilities(medal, (Ability[])(object)new Ability[1] { (Ability)105 });
			CardExtensions.AddAbilities(medal, (Ability[])(object)new Ability[1] { (Ability)8 });
			CardExtensions.AddTraits(medal, (Trait[])(object)new Trait[1] { (Trait)12 });
			CardExtensions.AddTraits(medal, (Trait[])(object)new Trait[1] { (Trait)17 });
			CardExtensions.AddTraits(medal, (Trait[])(object)new Trait[1] { (Trait)10 });
			CardExtensions.AddTraits(medal, (Trait[])(object)new Trait[1] { (Trait)14 });
			CardExtensions.AddTraits(medal, (Trait[])(object)new Trait[1] { (Trait)15 });
			CardExtensions.AddAppearances(medal, (Appearance[])(object)new Appearance[1] { (Appearance)(int)Medal.id });
		}

		public static CardInfo loadCardInfoFromString(string infoAsString, string prefix = "")
		{
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
			//IL_09f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_09fd: Expected I4, but got Unknown
			//IL_0cf5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d59: Unknown result type (might be due to invalid IL or missing references)
			//IL_1401: Unknown result type (might be due to invalid IL or missing references)
			//IL_140b: Expected O, but got Unknown
			//IL_0eaa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0eb0: Expected I4, but got Unknown
			//IL_1505: Unknown result type (might be due to invalid IL or missing references)
			//IL_150f: Expected O, but got Unknown
			//IL_10bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_10c2: Expected I4, but got Unknown
			//IL_1577: Unknown result type (might be due to invalid IL or missing references)
			//IL_1581: Expected O, but got Unknown
			//IL_121b: Unknown result type (might be due to invalid IL or missing references)
			//IL_1221: Expected I4, but got Unknown
			//IL_137a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1380: Expected I4, but got Unknown
			Dictionary<string, string> infoAsDictionary = Utils.stringToDictionnary(infoAsString);
			CardInfo val;
			if (infoAsDictionary.ContainsKey(prefix + "name") && CardManager.AllCardsCopy.Exists((CardInfo c) => ((Object)c).name.Equals(infoAsDictionary[prefix + "name"])))
			{
				val = CardExtensions.CardByName((IEnumerable<CardInfo>)CardManager.AllCardsCopy, infoAsDictionary[prefix + "name"]);
			}
			else
			{
				if (infoAsDictionary.ContainsKey(prefix + "name") && prefix == "")
				{
					StreamWriter streamWriter = new StreamWriter(Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/cards/" + infoAsDictionary[prefix + "name"]));
					streamWriter.Write(infoAsString);
					streamWriter.Close();
				}
				val = CardManager.New("", infoAsDictionary[prefix + "name"], "", 0, 0, "");
				val.metaCategories = new List<CardMetaCategory>();
				if (infoAsDictionary.ContainsKey(prefix + "metaCategories.Count"))
				{
					for (int m = 0; m < Utils.transformStringIntoInt(infoAsDictionary[prefix + "metaCategories.Count"]); m++)
					{
						if (infoAsDictionary.ContainsKey(prefix + "metaCategories[" + m + "]"))
						{
							val.metaCategories.Add((CardMetaCategory)Utils.transformStringIntoInt(infoAsDictionary[prefix + "metaCategories[" + m + "]"]));
						}
					}
				}
				if (infoAsDictionary.ContainsKey(prefix + "cardComplexity"))
				{
					val.cardComplexity = (CardComplexity)Utils.transformStringIntoInt(infoAsDictionary[prefix + "cardComplexity"]);
				}
				if (infoAsDictionary.ContainsKey(prefix + "onePerDeck"))
				{
					val.onePerDeck = Utils.transformStringIntoInt(infoAsDictionary[prefix + "onePerDeck"]) != 0;
				}
				if (infoAsDictionary.ContainsKey(prefix + "temple"))
				{
					val.temple = (CardTemple)Utils.transformStringIntoInt(infoAsDictionary[prefix + "temple"]);
				}
				if (infoAsDictionary.ContainsKey(prefix + "displayedName"))
				{
					val.displayedName = infoAsDictionary[prefix + "displayedName"];
				}
				if (infoAsDictionary.ContainsKey(prefix + "displayedNameLocId"))
				{
					val.displayedNameLocId = infoAsDictionary[prefix + "displayedNameLocId"];
				}
				if (infoAsDictionary.ContainsKey(prefix + "description"))
				{
					val.description = infoAsDictionary[prefix + "description"];
				}
				if (infoAsDictionary.ContainsKey(prefix + "hideAttackAndHealth"))
				{
					val.hideAttackAndHealth = Utils.transformStringIntoInt(infoAsDictionary[prefix + "hideAttackAndHealth"]) != 0;
				}
				if (infoAsDictionary.ContainsKey(prefix + "portraitTex"))
				{
					CardExtensions.SetPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "portraitTex.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "alternatePortrait"))
				{
					CardExtensions.SetAltPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "alternatePortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "pixelPortrait"))
				{
					CardExtensions.SetPixelPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "pixelPortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "steelTrapPortrait"))
				{
					CardExtensions.SetSteelTrapPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "steelTrapPortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "emissivePortrait"))
				{
					CardExtensions.SetEmissivePortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "emissivePortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "brokenShieldPortrait"))
				{
					CardExtensions.SetBrokenShieldPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "brokenShieldPortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "sacrificablePortrait"))
				{
					CardExtensions.SetSacrificablePortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "sacrificablePortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "emissiveAltPortrait"))
				{
					CardExtensions.SetEmissiveAltPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "emissiveAltPortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "pixelAlternatePortrait"))
				{
					CardExtensions.SetPixelAlternatePortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "pixelAlternatePortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "pixelSteelTrapPortrait"))
				{
					CardExtensions.SetPixelSteelTrapPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "pixelSteelTrapPortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "pixelBrokenShieldPortrait"))
				{
					CardExtensions.SetPixelBrokenShieldPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "pixelBrokenShieldPortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "pixelSacrificablePortrait"))
				{
					CardExtensions.SetPixelSacrificablePortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "pixelSacrificablePortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "emissiveSteelTrapPortrait"))
				{
					CardExtensions.SetEmissiveSteelTrapPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "emissiveSteelTrapPortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "emissiveBrokenShieldPortrait"))
				{
					CardExtensions.SetEmissiveBrokenShieldPortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "emissiveBrokenShieldPortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				if (infoAsDictionary.ContainsKey(prefix + "emissiveSacrificablePortrait"))
				{
					CardExtensions.SetEmissiveSacrificablePortrait(val, TextureHelper.GetImageAsTexture(infoAsDictionary[prefix + "emissiveSacrificablePortrait.path"], (FilterMode)0), (FilterMode?)null);
				}
				val.appearanceBehaviour = new List<Appearance>();
				if (infoAsDictionary.ContainsKey(prefix + "appearanceBehaviour.Count"))
				{
					int l;
					for (l = 0; l < Utils.transformStringIntoInt(infoAsDictionary[prefix + "appearanceBehaviour.Count"]); l++)
					{
						if (infoAsDictionary.ContainsKey(prefix + "appearanceBehaviour[" + l + "]") && CardAppearanceBehaviourManager.AllAppearances.Exists((FullCardAppearanceBehaviour fcab) => (int)fcab.Id == Utils.transformStringIntoInt(infoAsDictionary[prefix + "appearanceBehaviour[" + l + "]"])))
						{
							val.appearanceBehaviour.Add((Appearance)Utils.transformStringIntoInt(infoAsDictionary[prefix + "appearanceBehaviour[" + l + "]"]));
							continue;
						}
						CardExtensions.AddAppearances(val, (Appearance[])(object)new Appearance[1] { (Appearance)(int)Shredded.id });
					}
				}
				if (infoAsDictionary.ContainsKey(prefix + "baseAttack"))
				{
					val.baseAttack = Utils.transformStringIntoInt(infoAsDictionary[prefix + "baseAttack"]);
				}
				if (infoAsDictionary.ContainsKey(prefix + "baseHealth"))
				{
					val.baseHealth = Utils.transformStringIntoInt(infoAsDictionary[prefix + "baseHealth"]);
				}
				if (infoAsDictionary.ContainsKey(prefix + "cost"))
				{
					val.cost = Utils.transformStringIntoInt(infoAsDictionary[prefix + "cost"]);
				}
				if (infoAsDictionary.ContainsKey(prefix + "bonesCost"))
				{
					val.bonesCost = Utils.transformStringIntoInt(infoAsDictionary[prefix + "bonesCost"]);
				}
				if (infoAsDictionary.ContainsKey(prefix + "energyCost"))
				{
					val.energyCost = Utils.transformStringIntoInt(infoAsDictionary[prefix + "energyCost"]);
				}
				val.gemsCost = new List<GemType>();
				if (infoAsDictionary.ContainsKey(prefix + "gemsCost.Count"))
				{
					for (int n = 0; n < Utils.transformStringIntoInt(infoAsDictionary[prefix + "gemsCost.Count"]); n++)
					{
						if (infoAsDictionary.ContainsKey(prefix + "gemsCost[" + n + "]"))
						{
							val.gemsCost.Add((GemType)Utils.transformStringIntoInt(infoAsDictionary[prefix + "gemsCost[" + n + "]"]));
						}
					}
				}
				if (infoAsDictionary.ContainsKey(prefix + "specialStatIcon") && StatIconManager.AllStatIcons.Exists((FullStatIcon fsi) => (int)fsi.Id == Utils.transformStringIntoInt(infoAsDictionary[prefix + "specialStatIcon"])))
				{
					val.specialStatIcon = (SpecialStatIcon)Utils.transformStringIntoInt(infoAsDictionary[prefix + "specialStatIcon"]);
				}
				if (infoAsDictionary.ContainsKey(prefix + "boon") && BoonManager.AllFullBoons.Exists((FullBoon fb) => (int)fb.boon.type == Utils.transformStringIntoInt(infoAsDictionary[prefix + "boon"])))
				{
					val.boon = (Type)Utils.transformStringIntoInt(infoAsDictionary[prefix + "boon"]);
				}
				val.tribes = new List<Tribe>();
				if (infoAsDictionary.ContainsKey(prefix + "tribes.Count"))
				{
					for (int num = 0; num < Utils.transformStringIntoInt(infoAsDictionary[prefix + "tribes.Count"]); num++)
					{
						if (infoAsDictionary.ContainsKey(prefix + "tribes[" + num + "]") && (TribeManager.IsCustomTribe((Tribe)Utils.transformStringIntoInt(infoAsDictionary[prefix + "tribes[" + num + "]"])) || (Utils.transformStringIntoInt(infoAsDictionary[prefix + "tribes[" + num + "]"]) < 7 && Utils.transformStringIntoInt(infoAsDictionary[prefix + "tribes[" + num + "]"]) == 0)))
						{
							val.tribes.Add((Tribe)Utils.transformStringIntoInt(infoAsDictionary[prefix + "tribes[" + num + "]"]));
							continue;
						}
						CardExtensions.AddAppearances(val, (Appearance[])(object)new Appearance[1] { (Appearance)(int)Shredded.id });
					}
				}
				val.traits = new List<Trait>();
				if (infoAsDictionary.ContainsKey(prefix + "traits.Count"))
				{
					for (int num2 = 0; num2 < Utils.transformStringIntoInt(infoAsDictionary[prefix + "traits.Count"]); num2++)
					{
						if (infoAsDictionary.ContainsKey(prefix + "traits[" + num2 + "]"))
						{
							val.traits.Add((Trait)Utils.transformStringIntoInt(infoAsDictionary[prefix + "traits[" + num2 + "]"]));
						}
					}
				}
				val.specialAbilities = new List<SpecialTriggeredAbility>();
				if (infoAsDictionary.ContainsKey(prefix + "specialAbilities.Count"))
				{
					int k;
					for (k = 0; k < Utils.transformStringIntoInt(infoAsDictionary[prefix + "specialAbilities.Count"]); k++)
					{
						if (infoAsDictionary.ContainsKey(prefix + "specialAbilities[" + k + "]") && SpecialTriggeredAbilityManager.AllSpecialTriggers.Exists((FullSpecialTriggeredAbility fsta) => (int)fsta.Id == Utils.transformStringIntoInt(infoAsDictionary[prefix + "specialAbilities[" + k + "]"])))
						{
							val.specialAbilities.Add((SpecialTriggeredAbility)Utils.transformStringIntoInt(infoAsDictionary[prefix + "specialAbilities[" + k + "]"]));
							continue;
						}
						CardExtensions.AddAppearances(val, (Appearance[])(object)new Appearance[1] { (Appearance)(int)Shredded.id });
					}
				}
				val.abilities = new List<Ability>();
				if (infoAsDictionary.ContainsKey(prefix + "abilities.Count"))
				{
					int j;
					for (j = 0; j < Utils.transformStringIntoInt(infoAsDictionary[prefix + "abilities.Count"]); j++)
					{
						if (infoAsDictionary.ContainsKey(prefix + "abilities[" + j + "]") && AbilityManager.AllAbilities.Exists((FullAbility fa) => (int)fa.Id == Utils.transformStringIntoInt(infoAsDictionary[prefix + "abilities[" + j + "]"])))
						{
							val.abilities.Add((Ability)Utils.transformStringIntoInt(infoAsDictionary[prefix + "abilities[" + j + "]"]));
							continue;
						}
						CardExtensions.AddAppearances(val, (Appearance[])(object)new Appearance[1] { (Appearance)(int)Shredded.id });
					}
				}
				val.ascensionAbilities = new List<Ability>();
				if (infoAsDictionary.ContainsKey(prefix + "ascensionAbilities.Count"))
				{
					int i;
					for (i = 0; i < Utils.transformStringIntoInt(infoAsDictionary[prefix + "ascensionAbilities.Count"]); i++)
					{
						if (infoAsDictionary.ContainsKey(prefix + "ascensionAbilities[" + i + "]") && AbilityManager.AllAbilities.Exists((FullAbility fa) => (int)fa.Id == Utils.transformStringIntoInt(infoAsDictionary[prefix + "ascensionAbilities[" + i + "]"])))
						{
							val.ascensionAbilities.Add((Ability)Utils.transformStringIntoInt(infoAsDictionary[prefix + "ascensionAbilities[" + i + "]"]));
							continue;
						}
						CardExtensions.AddAppearances(val, (Appearance[])(object)new Appearance[1] { (Appearance)(int)Shredded.id });
					}
				}
				if (infoAsDictionary.ContainsKey(prefix + "evolveParams"))
				{
					val.evolveParams = new EvolveParams();
					if (infoAsDictionary.ContainsKey(prefix + "evolveParams.turnsToEvolve"))
					{
						val.evolveParams.turnsToEvolve = Utils.transformStringIntoInt(infoAsDictionary[prefix + "evolveParams.turnsToEvolve"]);
					}
					if (infoAsDictionary.ContainsKey(prefix + "evolveParams.evolution.name"))
					{
						val.evolveParams.evolution = loadCardInfoFromString(infoAsString, prefix + "evolveParams.evolution.");
					}
				}
				if (infoAsDictionary.ContainsKey(prefix + "defaultEvolutionName"))
				{
					val.defaultEvolutionName = infoAsDictionary[prefix + "defaultEvolutionName"];
				}
				if (infoAsDictionary.ContainsKey(prefix + "tailParams"))
				{
					val.tailParams = new TailParams();
					if (infoAsDictionary.ContainsKey(prefix + "tailParams.tail.name"))
					{
						val.tailParams.tail = loadCardInfoFromString(infoAsString, prefix + "tailParams.tail.");
					}
				}
				if (infoAsDictionary.ContainsKey(prefix + "iceCubeParams"))
				{
					val.iceCubeParams = new IceCubeParams();
					if (infoAsDictionary.ContainsKey(prefix + "iceCubeParams.creatureWithin.name"))
					{
						val.iceCubeParams.creatureWithin = loadCardInfoFromString(infoAsString, prefix + "iceCubeParams.creatureWithin.");
					}
				}
				if (infoAsDictionary.ContainsKey(prefix + "flipPortraitForStrafe"))
				{
					val.flipPortraitForStrafe = Utils.transformStringIntoInt(infoAsDictionary[prefix + "flipPortraitForStrafe"]) != 0;
				}
				foreach (KeyValuePair<string, string> item in infoAsDictionary.Where((KeyValuePair<string, string> pair) => pair.Key.Length > 4 && pair.Key.Remove(4) == "Ext."))
				{
					CardExtensions.SetExtendedProperty(val, item.Key.Remove(0, 4), (object)item.Value);
				}
			}
			return val;
		}

		public static void loadCardInfoFromFiles()
		{
			string[] files = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/cards"));
			string[] array = files;
			foreach (string path in array)
			{
				StreamReader streamReader = new StreamReader(path);
				string infoAsString = streamReader.ReadToEnd();
				streamReader.Close();
				loadCardInfoFromString(infoAsString);
			}
		}

		public static void createCards()
		{
			createShredded();
			createMedal();
			loadCardInfoFromFiles();
		}
	}
	public static class Utils
	{
		public static double transformStringIntoDouble(string stringToTransform)
		{
			switch (stringToTransform)
			{
			case "lucky":
				return 10.0;
			case "unlucky":
				return -10.0;
			case "pi":
				return 3.141592;
			case "I like my pizza with extra sauce.":
				return 450.7534;
			case "What are the nuclear launch codes?":
				return 103551.546423275;
			default:
			{
				double num = 0.0;
				bool flag = false;
				int num2 = 0;
				bool flag2 = false;
				foreach (char c in stringToTransform)
				{
					if (c == '-')
					{
						flag2 = !flag2;
					}
					else if (c == '.')
					{
						flag = true;
					}
					else if (c >= '0' && c <= '9')
					{
						double num3 = c - 48;
						if (flag)
						{
							num2++;
							num += num3 * Math.Pow(10.0, -num2);
						}
						else
						{
							num *= 10.0;
							num += num3;
						}
					}
				}
				if (flag2)
				{
					num *= -1.0;
				}
				return num;
			}
			}
		}

		public static int transformStringIntoInt(string stringToTransform)
		{
			switch (stringToTransform)
			{
			case "single":
				return 1;
			case "multiple":
				return 2;
			case "+que2":
				return 3;
			default:
			{
				int num = 0;
				bool flag = false;
				foreach (char c in stringToTransform)
				{
					if (c == '-')
					{
						flag = !flag;
					}
					else if (c >= '0' && c <= '9')
					{
						num *= 10;
						num += c - 48;
					}
				}
				if (flag)
				{
					num *= -1;
				}
				return num;
			}
			}
		}

		public static string[] splitString(string stringToSplit, char[] separator)
		{
			List<string> list = new List<string>();
			string text = "";
			for (int i = 0; i < stringToSplit.Length; i++)
			{
				char c = stringToSplit[i];
				bool flag = false;
				if (c == '\\')
				{
					i++;
					text += c;
					c = stringToSplit[i];
				}
				else
				{
					foreach (char c2 in separator)
					{
						if (c == c2)
						{
							string item = text;
							list.Add(item);
							text = "";
							flag = true;
						}
					}
				}
				if (!flag)
				{
					text += c;
				}
			}
			if (text.Length > 0)
			{
				string item2 = text;
				list.Add(item2);
			}
			return list.ToArray();
		}

		public static Dictionary<string, string> stringToDictionnary(string infoAsString)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>();
			char[] separator = new char[2] { ':', ',' };
			string[] array = splitString(infoAsString, separator);
			for (int i = 0; i < array.Count(); i += 2)
			{
				dictionary.Add(replaceLineWithSpace(array[i]), replaceLineWithSpace(array[i + 1]));
			}
			return dictionary;
		}

		public static string replaceSpaceWithLine(string toTransform)
		{
			return toTransform.Replace("\\", "\\\\").Replace(":", "\\:").Replace(",", "\\,");
		}

		public static string replaceLineWithSpace(string toTransform)
		{
			return toTransform.Replace("\\:", ":").Replace("\\,", ",").Replace("\\\\", "\\");
		}

		public static string objectToString(Object obj, string prefix = "")
		{
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Expected I4, but got Unknown
			string text = prefix + "hideFlags:" + (int)obj.hideFlags;
			if (obj.name != null)
			{
				text += ",";
				text = text + prefix + "name:" + obj.name;
			}
			return text;
		}

		public static string textureToString(Texture texture, string prefix = "")
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Expected I4, but got Unknown
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Expected I4, but got Unknown
			//IL_00f4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Expected I4, but got Unknown
			//IL_012b: 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_011c: Expected I4, but got Unknown
			//IL_0162: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Expected I4, but got Unknown
			//IL_0184: Unknown result type (might be due to invalid IL or missing references)
			//IL_018a: Expected I4, but got Unknown
			string text = prefix + "width:" + texture.width;
			_ = texture.height;
			if (true)
			{
				text += ",";
				text = text + prefix + "height:" + texture.height;
			}
			_ = texture.dimension;
			if (true)
			{
				text += ",";
				text = text + prefix + "dimension:" + (int)texture.dimension;
			}
			_ = texture.wrapMode;
			if (true)
			{
				text += ",";
				text = text + prefix + "wrapMode:" + (int)texture.wrapMode;
			}
			_ = texture.wrapModeU;
			if (true)
			{
				text += ",";
				text = text + prefix + "wrapModeU:" + (int)texture.wrapModeU;
			}
			_ = texture.wrapModeV;
			if (true)
			{
				text += ",";
				text = text + prefix + "wrapModeV:" + (int)texture.wrapModeV;
			}
			_ = texture.wrapModeW;
			if (true)
			{
				text += ",";
				text = text + prefix + "wrapModeW:" + (int)texture.wrapModeW;
			}
			_ = texture.filterMode;
			if (true)
			{
				text += ",";
				text = text + prefix + "filterMode:" + (int)texture.filterMode;
			}
			_ = texture.anisoLevel;
			if (true)
			{
				text += ",";
				text = text + prefix + "anisoLevel:" + texture.anisoLevel;
			}
			_ = texture.mipMapBias;
			if (true)
			{
				text += ",";
				text = text + prefix + "mipMapBias:" + texture.mipMapBias;
			}
			text += ",";
			return text + objectToString((Object)(object)texture, prefix);
		}

		public static Texture2D getShenaningansReadableTexture(Texture2D texture)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Expected O, but got Unknown
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)7, (RenderTextureReadWrite)1);
			Graphics.Blit((Texture)(object)texture, temporary);
			RenderTexture active = RenderTexture.active;
			RenderTexture.active = temporary;
			Texture2D val = new Texture2D(((Texture)texture).width, ((Texture)texture).height);
			val.ReadPixels(new Rect(0f, 0f, (float)((Texture)temporary).width, (float)((Texture)temporary).height), 0, 0);
			val.Apply();
			RenderTexture.active = active;
			RenderTexture.ReleaseTemporary(temporary);
			return val;
		}

		public static string texture2DToString(CardInfo info, Texture2D texture, string fileAdder = "", string prefix = "")
		{
			string text = prefix.Remove(prefix.Length - 1) + ":" + 1;
			Texture2D shenaningansReadableTexture = getShenaningansReadableTexture(texture);
			byte[] bytes = ImageConversion.EncodeToPNG(shenaningansReadableTexture);
			File.WriteAllBytes(Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/cards/assets/" + ((Object)info).name + "." + fileAdder + "png"), bytes);
			File.WriteAllBytes(Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/cards/assets/current/" + ((Object)info).name + "." + fileAdder + "png"), bytes);
			text += ",";
			return text + prefix + "path:" + replaceSpaceWithLine(Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/cards/assets/" + ((Object)info).name + "." + fileAdder + "png"));
		}

		public static string cardInfoToString(CardInfo info, string prefix = "", List<string> alreadySentInCardName = null)
		{
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_018d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0194: Expected I4, but got Unknown
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Expected I4, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Expected I4, but got Unknown
			//IL_159a: Unknown result type (might be due to invalid IL or missing references)
			//IL_159f: Unknown result type (might be due to invalid IL or missing references)
			//IL_15ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_15ee: Expected I4, but got Unknown
			//IL_16a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_16ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_16f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_16fc: Expected I4, but got Unknown
			//IL_1928: Unknown result type (might be due to invalid IL or missing references)
			//IL_192d: Unknown result type (might be due to invalid IL or missing references)
			//IL_1978: Unknown result type (might be due to invalid IL or missing references)
			//IL_197c: Expected I4, but got Unknown
			//IL_1b1e: Unknown result type (might be due to invalid IL or missing references)
			//IL_1b64: Unknown result type (might be due to invalid IL or missing references)
			//IL_1b6b: Expected I4, but got Unknown
			//IL_1a9a: Unknown result type (might be due to invalid IL or missing references)
			//IL_1a9f: Unknown result type (might be due to invalid IL or missing references)
			//IL_1aea: Unknown result type (might be due to invalid IL or missing references)
			//IL_1aee: Expected I4, but got Unknown
			//IL_08d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_08d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_0912: Unknown result type (might be due to invalid IL or missing references)
			//IL_0916: Expected I4, but got Unknown
			//IL_1f57: Unknown result type (might be due to invalid IL or missing references)
			//IL_1fa2: Unknown result type (might be due to invalid IL or missing references)
			//IL_1fa9: Expected I4, but got Unknown
			//IL_0b7c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bbe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ba3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0baa: Expected I4, but got Unknown
			//IL_0be5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bec: Expected I4, but got Unknown
			//IL_0b06: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b0b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b44: Unknown result type (might be due to invalid IL or missing references)
			//IL_0b48: Expected I4, but got Unknown
			//IL_23c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_2414: Unknown result type (might be due to invalid IL or missing references)
			//IL_241b: Expected I4, but got Unknown
			//IL_0c72: Unknown result type (might be due to invalid IL or missing references)
			//IL_0c77: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cb0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0cb4: Expected I4, but got Unknown
			//IL_0d5a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d5f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d98: Unknown result type (might be due to invalid IL or missing references)
			//IL_0d9c: Expected I4, but got Unknown
			//IL_0e42: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e47: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e80: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e84: Expected I4, but got Unknown
			//IL_0f2a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f2f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f68: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f6c: Expected I4, but got Unknown
			//IL_1012: Unknown result type (might be due to invalid IL or missing references)
			//IL_1017: Unknown result type (might be due to invalid IL or missing references)
			//IL_1050: Unknown result type (might be due to invalid IL or missing references)
			//IL_1054: Expected I4, but got Unknown
			int num = 0;
			int num2 = 0;
			string text = prefix + "name:" + replaceSpaceWithLine(((Object)info).name);
			if (alreadySentInCardName == null || !alreadySentInCardName.Exists((string s) => s == ((Object)info).name))
			{
				if (alreadySentInCardName == null)
				{
					alreadySentInCardName = new List<string>();
				}
				alreadySentInCardName.Add(((Object)info).name);
				if (info.metaCategories != null && info.metaCategories.Count > 0)
				{
					text += ",";
					text = text + prefix + "metaCategories.Count:" + info.metaCategories.Count;
					num = 0;
					foreach (CardMetaCategory metaCategory in info.metaCategories)
					{
						text += ",";
						text = text + prefix + "metaCategories[" + num + "]:" + (int)metaCategory;
						num++;
					}
				}
				_ = info.cardComplexity;
				if (true)
				{
					text += ",";
					text = text + prefix + "cardComplexity:" + (int)info.cardComplexity;
				}
				_ = info.onePerDeck;
				if (true)
				{
					text += ",";
					text = text + prefix + "onePerDeck:" + (info.onePerDeck ? 1 : 0);
				}
				_ = info.temple;
				if (true)
				{
					text += ",";
					text = text + prefix + "temple:" + (int)info.temple;
				}
				if (info.displayedName != null)
				{
					text += ",";
					text = text + prefix + "displayedName:" + replaceSpaceWithLine(info.displayedName);
				}
				if (info.displayedNameLocId != null)
				{
					text += ",";
					text = text + prefix + "displayedNameLocId:" + replaceSpaceWithLine(info.displayedNameLocId);
				}
				if (info.description != null && info.description.Length > 0)
				{
					text += ",";
					text = text + prefix + "description:" + replaceSpaceWithLine(info.description);
				}
				else
				{
					text += ",";
					text = text + prefix + "description:" + replaceSpaceWithLine("This card sure exist.");
				}
				_ = info.hideAttackAndHealth;
				if (true)
				{
					text += ",";
					text = text + prefix + "hideAttackAndHealth:" + (info.hideAttackAndHealth ? 1 : 0);
				}
				if ((Object)(object)info.portraitTex != (Object)null)
				{
					text += ",";
					text += texture2DToString(info, info.portraitTex.texture, "portraitTex.", prefix + "portraitTex.");
				}
				if ((Object)(object)info.alternatePortrait != (Object)null)
				{
					text += ",";
					text += texture2DToString(info, info.alternatePortrait.texture, "alternatePortrait.", prefix + "alternatePortrait.");
				}
				if ((Object)(object)info.pixelPortrait != (Object)null)
				{
					text += ",";
					text += texture2DToString(info, info.pixelPortrait.texture, "pixelPortrait.", prefix + "pixelPortrait.");
				}
				if (CardExtensions.HasSteelTrapPortrait(info))
				{
					text += ",";
					text += texture2DToString(info, CardManager.SteelTrapPortrait(info).texture, "steelTrapPortrait.", prefix + "steelTrapPortrait.");
				}
				if ((Object)(object)CardExtensions.GetEmissivePortrait(info) != (Object)null)
				{
					text += ",";
					text += texture2DToString(info, CardExtensions.GetEmissivePortrait(info).texture, "emissivePortrait.", prefix + "emissivePortrait.");
				}
				if (CardExtensions.HasBrokenShieldPortrait(info))
				{
					text += ",";
					text += texture2DToString(info, CardManager.BrokenShieldPortrait(info).texture, "brokenShieldPortrait.", prefix + "brokenShieldPortrait.");
				}
				if (CardExtensions.HasSacrificablePortrait(info))
				{
					text += ",";
					text += texture2DToString(info, CardManager.SacrificablePortrait(info).texture, "sacrificablePortrait.", prefix + "sacrificablePortrait.");
				}
				if ((Object)(object)CardExtensions.GetEmissiveAltPortrait(info) != (Object)null)
				{
					text += ",";
					text += texture2DToString(info, CardExtensions.GetEmissiveAltPortrait(info).texture, "emissiveAltPortrait.", prefix + "emissiveAltPortrait.");
				}
				if (CardExtensions.HasPixelAlternatePortrait(info))
				{
					text += ",";
					text += texture2DToString(info, CardManager.PixelAlternatePortrait(info).texture, "pixelAlternatePortrait.", prefix + "pixelAlternatePortrait.");
				}
				if (CardExtensions.HasPixelSteelTrapPortrait(info))
				{
					text += ",";
					text += texture2DToString(info, CardManager.PixelSteelTrapPortrait(info).texture, "pixelSteelTrapPortrait.", prefix + "pixelSteelTrapPortrait.");
				}
				if (CardExtensions.HasPixelBrokenShieldPortrait(info))
				{
					text += ",";
					text += texture2DToString(info, CardManager.PixelBrokenShieldPortrait(info).texture, "pixelBrokenShieldPortrait.", prefix + "pixelBrokenShieldPortrait.");
				}
				if (CardExtensions.HasPixelSacrificablePortrait(info))
				{
					text += ",";
					text += texture2DToString(info, CardManager.PixelSacrificablePortrait(info).texture, "pixelSacrificablePortrait.", prefix + "pixelSacrificablePortrait.");
				}
				if ((Object)(object)CardManager.EmissiveSteelTrapPortrait(info) != (Object)null)
				{
					text += ",";
					text += texture2DToString(info, CardManager.EmissiveSteelTrapPortrait(info).texture, "emissiveSteelTrapPortrait.", prefix + "emissiveSteelTrapPortrait.");
				}
				if ((Object)(object)CardManager.EmissiveBrokenShieldPortrait(info) != (Object)null)
				{
					text += ",";
					text += texture2DToString(info, CardManager.EmissiveBrokenShieldPortrait(info).texture, "emissiveBrokenShieldPortrait.", prefix + "emissiveBrokenShieldPortrait.");
				}
				if ((Object)(object)CardManager.EmissiveSacrificablePortrait(info) != (Object)null)
				{
					text += ",";
					text += texture2DToString(info, CardManager.EmissiveSacrificablePortrait(info).texture, "emissiveSacrificablePortrait.", prefix + "emissiveSacrificablePortrait.");
				}
				if (info.appearanceBehaviour != null && info.appearanceBehaviour.Count > 0)
				{
					text += ",";
					text = text + prefix + "appearanceBehaviour.Count:" + info.appearanceBehaviour.Count;
					num = 0;
					foreach (Appearance item in info.appearanceBehaviour)
					{
						text += ",";
						text = text + prefix + "appearanceBehaviour[" + num + "]:" + (int)item;
						num++;
					}
				}
				_ = info.baseAttack;
				if (true)
				{
					text += ",";
					string text2 = text;
					int baseAttack = info.baseAttack;
					text = text2 + prefix + "baseAttack:" + baseAttack;
				}
				_ = info.baseHealth;
				if (true)
				{
					text += ",";
					string text3 = text;
					int baseAttack = info.baseHealth;
					text = text3 + prefix + "baseHealth:" + baseAttack;
				}
				_ = info.cost;
				if (true)
				{
					text += ",";
					string text4 = text;
					int baseAttack = info.cost;
					text = text4 + prefix + "cost:" + baseAttack;
				}
				_ = info.bonesCost;
				if (true)
				{
					text += ",";
					string text5 = text;
					int baseAttack = info.bonesCost;
					text = text5 + prefix + "bonesCost:" + baseAttack;
				}
				_ = info.energyCost;
				if (true)
				{
					text += ",";
					string text6 = text;
					int baseAttack = info.energyCost;
					text = text6 + prefix + "energyCost:" + baseAttack;
				}
				if (info.gemsCost != null && info.gemsCost.Count > 0)
				{
					text += ",";
					text = text + prefix + "gemsCost.Count:" + info.gemsCost.Count;
					num = 0;
					foreach (GemType item2 in info.gemsCost)
					{
						text += ",";
						text = text + prefix + "gemsCost[" + num + "]:" + (int)item2;
						num++;
					}
				}
				_ = info.specialStatIcon;
				if (true)
				{
					text += ",";
					text = text + prefix + "specialStatIcon:" + (int)info.specialStatIcon;
				}
				_ = info.boon;
				if (true)
				{
					text += ",";
					text = text + prefix + "boon:" + (int)info.boon;
				}
				if (info.tribes != null && info.tribes.Count > 0)
				{
					text += ",";
					text = text + prefix + "tribes.Count:" + info.tribes.Count;
					num = 0;
					foreach (Tribe tribe in info.tribes)
					{
						text += ",";
						text = text + prefix + "tribes[" + num + "]:" + (int)tribe;
						num++;
					}
				}
				if (info.traits != null && info.traits.Count > 0)
				{
					text += ",";
					text = text + prefix + "traits.Count:" + info.traits.Count;
					num = 0;
					foreach (Trait trait in info.traits)
					{
						text += ",";
						text = text + prefix + "traits[" + num + "]:" + (int)trait;
						num++;
					}
				}
				if (info.specialAbilities != null && info.specialAbilities.Count > 0)
				{
					text += ",";
					text = text + prefix + "specialAbilities.Count:" + info.specialAbilities.Count;
					num = 0;
					foreach (SpecialTriggeredAbility specialAbility in info.specialAbilities)
					{
						text += ",";
						text = text + prefix + "specialAbilities[" + num + "]:" + (int)specialAbility;
						num++;
					}
				}
				if (info.abilities != null && info.abilities.Count > 0)
				{
					text += ",";
					text = text + prefix + "abilities.Count:" + info.abilities.Count;
					num = 0;
					foreach (Ability ability in info.abilities)
					{
						text += ",";
						text = text + prefix + "abilities[" + num + "]:" + (int)ability;
						num++;
					}
				}
				if (info.ascensionAbilities != null && info.ascensionAbilities.Count > 0)
				{
					text += ",";
					text = text + prefix + "ascensionAbilities.Count:" + info.ascensionAbilities.Count;
					num = 0;
					foreach (Ability ascensionAbility in info.ascensionAbilities)
					{
						text += ",";
						text = text + prefix + "ascensionAbilities[" + num + "]:" + (int)ascensionAbility;
						num++;
					}
				}
				if (info.evolveParams != null)
				{
					text += ",";
					text = text + prefix + "evolveParams:" + 1;
					_ = info.evolveParams.turnsToEvolve;
					if (true)
					{
						text += ",";
						string text7 = text;
						int baseAttack = info.evolveParams.turnsToEvolve;
						text = text7 + prefix + "evolveParams.turnsToEvolve:" + baseAttack;
					}
					if ((Object)(object)info.evolveParams.evolution != (Object)null)
					{
						text += ",";
						alreadySentInCardName.Add(((Object)info).name);
						text += cardInfoToString(info.evolveParams.evolution, prefix + "evolveParams.evolution.", alreadySentInCardName);
					}
				}
				if (info.defaultEvolutionName != null && info.defaultEvolutionName.Length > 0)
				{
					text += ",";
					text = text + prefix + "defaultEvolutionName:" + replaceSpaceWithLine(info.defaultEvolutionName);
				}
				if (info.tailParams != null)
				{
					text += ",";
					text = text + prefix + "tailParams:" + 1;
					if ((Object)(object)info.tailParams.tail != (Object)null)
					{
						text += ",";
						text += cardInfoToString(info.tailParams.tail, prefix + "tailParams.tail.", alreadySentInCardName);
					}
				}
				if (info.iceCubeParams != null)
				{
					text += ",";
					text = text + prefix + "iceCubeParams:" + 1;
					if ((Object)(object)info.iceCubeParams.creatureWithin != (Object)null)
					{
						text += ",";
						text += cardInfoToString(info.iceCubeParams.creatureWithin, prefix + "iceCubeParams.creatureWithin.", alreadySentInCardName);
					}
				}
				_ = info.flipPortraitForStrafe;
				if (true)
				{
					text += ",";
					text = text + prefix + "flipPortraitForStrafe:" + (info.flipPortraitForStrafe ? 1 : 0);
				}
			}
			if (info.mods != null && info.mods.Count > 0)
			{
				text += ",";
				text = text + prefix + "mods.Count:" + info.mods.Count;
				num = 0;
				foreach (CardModificationInfo mod in info.mods)
				{
					if (mod.singletonId != null)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].singletonId:" + replaceSpaceWithLine(mod.singletonId);
					}
					if (mod.nameReplacement != null)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].nameReplacement:" + replaceSpaceWithLine(mod.nameReplacement);
					}
					_ = mod.attackAdjustment;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].attackAdjustment:" + mod.attackAdjustment;
					}
					_ = mod.healthAdjustment;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].healthAdjustment:" + mod.healthAdjustment;
					}
					if (mod.abilities != null && mod.abilities.Count > 0)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].abilities.Count:" + mod.abilities.Count;
						num2 = 0;
						foreach (Ability ability2 in mod.abilities)
						{
							text += ",";
							text = text + prefix + "mods[" + num + "].abilities[" + num2 + "]:" + (int)ability2;
							num2++;
						}
					}
					if (mod.negateAbilities != null && mod.negateAbilities.Count > 0)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].negateAbilities.Count:" + mod.negateAbilities.Count;
						num2 = 0;
						foreach (Ability negateAbility in mod.negateAbilities)
						{
							text += ",";
							text = text + prefix + "mods[" + num + "].negateAbilities[" + num2 + "]:" + (int)negateAbility;
							num2++;
						}
					}
					_ = mod.bloodCostAdjustment;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].bloodCostAdjustment:" + mod.bloodCostAdjustment;
					}
					_ = mod.bonesCostAdjustment;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].bonesCostAdjustment:" + mod.bonesCostAdjustment;
					}
					_ = mod.energyCostAdjustment;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].energyCostAdjustment:" + mod.energyCostAdjustment;
					}
					_ = mod.nullifyGemsCost;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].nullifyGemsCost:" + (mod.nullifyGemsCost ? 1 : 0);
					}
					if (mod.addGemCost != null && mod.addGemCost.Count > 0)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].addGemCost.Count:" + mod.addGemCost.Count;
						num2 = 0;
						foreach (GemType item3 in mod.addGemCost)
						{
							text += ",";
							text = text + prefix + "mods[" + num + "].addGemCost[" + num2 + "]:" + (int)item3;
							num2++;
						}
					}
					_ = mod.gemify;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].gemify:" + (mod.gemify ? 1 : 0);
					}
					if (mod.specialAbilities != null && mod.specialAbilities.Count > 0)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].specialAbilities.Count:" + mod.specialAbilities.Count;
						num2 = 0;
						foreach (SpecialTriggeredAbility specialAbility2 in mod.specialAbilities)
						{
							text += ",";
							text = text + prefix + "mods[" + num + "].specialAbilities[" + num2 + "]:" + (int)specialAbility2;
							num2++;
						}
					}
					_ = mod.statIcon;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].statIcon:" + (int)mod.statIcon;
					}
					_ = mod.fromCardMerge;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].fromCardMerge:" + (mod.fromCardMerge ? 1 : 0);
					}
					_ = mod.fromDuplicateMerge;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].fromDuplicateMerge:" + (mod.fromDuplicateMerge ? 1 : 0);
					}
					_ = mod.fromTotem;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].fromTotem:" + (mod.fromTotem ? 1 : 0);
					}
					_ = mod.fromLatch;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].fromLatch:" + (mod.fromLatch ? 1 : 0);
					}
					_ = mod.fromOverclock;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].fromOverclock:" + (mod.fromOverclock ? 1 : 0);
					}
					_ = mod.sideDeckMod;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].sideDeckMod:" + (mod.sideDeckMod ? 1 : 0);
					}
					_ = mod.nonCopyable;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].nonCopyable:" + (mod.nonCopyable ? 1 : 0);
					}
					_ = mod.fromEvolve;
					if (true)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].fromEvolve:" + (mod.fromEvolve ? 1 : 0);
					}
					if (mod.transformerBeastCardId != null)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].transformerBeastCardId:" + replaceSpaceWithLine(mod.transformerBeastCardId);
					}
					if (mod.deathCardInfo != null)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].deathCardInfo:" + 1;
						_ = mod.deathCardInfo.headType;
						if (true)
						{
							text += ",";
							text = text + prefix + "mods[" + num + "].deathCardInfo.headType:" + (int)mod.deathCardInfo.headType;
						}
						_ = mod.deathCardInfo.mouthIndex;
						if (true)
						{
							text += ",";
							string[] obj = new string[6]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].deathCardInfo.mouthIndex:",
								null
							};
							int baseAttack = mod.deathCardInfo.mouthIndex;
							obj[5] = baseAttack.ToString();
							text = string.Concat(obj);
						}
						_ = mod.deathCardInfo.eyesIndex;
						if (true)
						{
							text += ",";
							string[] obj2 = new string[6]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].deathCardInfo.eyesIndex:",
								null
							};
							int baseAttack = mod.deathCardInfo.eyesIndex;
							obj2[5] = baseAttack.ToString();
							text = string.Concat(obj2);
						}
						_ = mod.deathCardInfo.lostEye;
						if (true)
						{
							text += ",";
							text = text + prefix + "mods[" + num + "].deathCardInfo.lostEye:" + (mod.deathCardInfo.lostEye ? 1 : 0);
						}
					}
					if (mod.bountyHunterInfo != null)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].bountyHunterInfo:" + 1;
						_ = mod.bountyHunterInfo.faceIndex;
						if (true)
						{
							text += ",";
							string[] obj3 = new string[6]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].bountyHunterInfo.faceIndex:",
								null
							};
							int baseAttack = mod.bountyHunterInfo.faceIndex;
							obj3[5] = baseAttack.ToString();
							text = string.Concat(obj3);
						}
						_ = mod.bountyHunterInfo.hatIndex;
						if (true)
						{
							text += ",";
							string[] obj4 = new string[6]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].bountyHunterInfo.hatIndex:",
								null
							};
							int baseAttack = mod.bountyHunterInfo.hatIndex;
							obj4[5] = baseAttack.ToString();
							text = string.Concat(obj4);
						}
						_ = mod.bountyHunterInfo.mouthIndex;
						if (true)
						{
							text += ",";
							string[] obj5 = new string[6]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].bountyHunterInfo.mouthIndex:",
								null
							};
							int baseAttack = mod.bountyHunterInfo.mouthIndex;
							obj5[5] = baseAttack.ToString();
							text = string.Concat(obj5);
						}
						_ = mod.bountyHunterInfo.eyesIndex;
						if (true)
						{
							text += ",";
							string[] obj6 = new string[6]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].bountyHunterInfo.eyesIndex:",
								null
							};
							int baseAttack = mod.bountyHunterInfo.eyesIndex;
							obj6[5] = baseAttack.ToString();
							text = string.Concat(obj6);
						}
						_ = mod.bountyHunterInfo.tier;
						if (true)
						{
							text += ",";
							string[] obj7 = new string[6]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].bountyHunterInfo.tier:",
								null
							};
							int baseAttack = mod.bountyHunterInfo.tier;
							obj7[5] = baseAttack.ToString();
							text = string.Concat(obj7);
						}
						_ = mod.bountyHunterInfo.dialogueIndex;
						if (true)
						{
							text += ",";
							string[] obj8 = new string[6]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].bountyHunterInfo.dialogueIndex:",
								null
							};
							int baseAttack = mod.bountyHunterInfo.dialogueIndex;
							obj8[5] = baseAttack.ToString();
							text = string.Concat(obj8);
						}
						_ = mod.bountyHunterInfo.status;
						if (true)
						{
							text += ",";
							text = text + prefix + "mods[" + num + "].bountyHunterInfo.status:" + (int)mod.bountyHunterInfo.status;
						}
					}
					if (mod.buildACardPortraitInfo != null && mod.buildACardPortraitInfo.spriteIndices != null && mod.buildACardPortraitInfo.spriteIndices.Length != 0)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].buildACardPortraitInfo.spriteIndices.Length:" + mod.buildACardPortraitInfo.spriteIndices.Length;
						num2 = 0;
						int[] spriteIndices = mod.buildACardPortraitInfo.spriteIndices;
						foreach (int num3 in spriteIndices)
						{
							text += ",";
							string[] obj9 = new string[8]
							{
								text,
								prefix,
								"mods[",
								num.ToString(),
								"].buildACardPortraitInfo.spriteIndices[",
								num2.ToString(),
								"]:",
								null
							};
							int baseAttack = num3;
							obj9[7] = baseAttack.ToString();
							text = string.Concat(obj9);
							num2++;
						}
					}
					if (mod.decalIds != null && mod.decalIds.Count > 0)
					{
						text += ",";
						text = text + prefix + "mods[" + num + "].decalIds.Count:" + mod.decalIds.Count;
						num2 = 0;
						foreach (string decalId in mod.decalIds)
						{
							text += ",";
							text = text + prefix + "mods[" + num + "].decalIds[" + num2 + "]:" + decalId;
							num2++;
						}
					}
					num++;
				}
			}
			return text;
		}

		public static CardInfo stringToCardInfo(string infoAsString)
		{
			//IL_00af: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Expected O, but got Unknown
			//IL_0c0b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0bff: Unknown result type (might be due to invalid IL or missing references)
			//IL_1473: Unknown result type (might be due to invalid IL or missing references)
			//IL_147d: Expected O, but got Unknown
			//IL_1160: Unknown result type (might be due to invalid IL or missing references)
			//IL_116a: Expected O, but got Unknown
			//IL_1850: Unknown result type (might be due to invalid IL or missing references)
			//IL_185a: Expected O, but got Unknown
			//IL_139e: Unknown result type (might be due to invalid IL or missing references)
			//IL_13a8: Expected O, but got Unknown
			//IL_1805: Unknown result type (might be due to invalid IL or missing references)
			//IL_17f4: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<string, string> infoAsDictionary = stringToDictionnary(infoAsString);
			CardInfo val = ((!infoAsDictionary.ContainsKey("name") || !CardManager.AllCardsCopy.Exists((CardInfo c) => ((Object)c).name.Equals(infoAsDictionary["name"]))) ? NewCards.loadCardInfoFromString(infoAsString) : CardExtensions.CardByName((IEnumerable<CardInfo>)CardManager.AllCardsCopy, infoAsDictionary["name"]));
			if (infoAsDictionary.ContainsKey("mods.Count"))
			{
				val.mods = new List<CardModificationInfo>();
				int i;
				for (i = 0; i < transformStringIntoInt(infoAsDictionary["mods.Count"]); i++)
				{
					CardModificationInfo val2 = new CardModificationInfo();
					if (infoAsDictionary.ContainsKey("mods[" + i + "].singletonId") && infoAsDictionary["mods[" + i + "].singletonId"] != "ShreddedMod")
					{
						val2.singletonId = infoAsDictionary["mods[" + i + "].singletonId"];
					}
					else
					{
						val2.singletonId = null;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].nameReplacement"))
					{
						val2.nameReplacement = infoAsDictionary["mods[" + i + "].nameReplacement"];
					}
					else
					{
						val2.nameReplacement = null;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].attackAdjustment"))
					{
						val2.attackAdjustment = transformStringIntoInt(infoAsDictionary["mods[" + i + "].attackAdjustment"]);
					}
					else
					{
						val2.attackAdjustment = 0;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].healthAdjustment"))
					{
						val2.healthAdjustment = transformStringIntoInt(infoAsDictionary["mods[" + i + "].healthAdjustment"]);
					}
					else
					{
						val2.healthAdjustment = 0;
					}
					val2.abilities = new List<Ability>();
					if (infoAsDictionary.ContainsKey("mods[" + i + "].abilities.Count"))
					{
						int l;
						for (l = 0; l < transformStringIntoInt(infoAsDictionary["mods[" + i + "].abilities.Count"]); l++)
						{
							if (infoAsDictionary.ContainsKey("mods[" + i + "].abilities[" + l + "]") && AbilityManager.AllAbilities.Exists((FullAbility fa) => (int)fa.Id == transformStringIntoInt(infoAsDictionary["mods[" + i + "].abilities[" + l + "]"])))
							{
								val2.abilities.Add((Ability)transformStringIntoInt(infoAsDictionary["mods[" + i + "].abilities[" + l + "]"]));
							}
						}
					}
					val2.negateAbilities = new List<Ability>();
					if (infoAsDictionary.ContainsKey("mods[" + i + "].negateAbilities.Count"))
					{
						int k;
						for (k = 0; k < transformStringIntoInt(infoAsDictionary["mods[" + i + "].negateAbilities.Count"]); k++)
						{
							if (infoAsDictionary.ContainsKey("mods[" + i + "].negateAbilities[" + k + "]") && AbilityManager.AllAbilities.Exists((FullAbility fa) => (int)fa.Id == transformStringIntoInt(infoAsDictionary["mods[" + i + "].negateAbilities[" + k + "]"])))
							{
								val2.negateAbilities.Add((Ability)transformStringIntoInt(infoAsDictionary["mods[" + i + "].negateAbilities[" + k + "]"]));
							}
						}
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].bloodCostAdjustment"))
					{
						val2.bloodCostAdjustment = transformStringIntoInt(infoAsDictionary["mods[" + i + "].bloodCostAdjustment"]);
					}
					else
					{
						val2.bloodCostAdjustment = 0;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].bonesCostAdjustment"))
					{
						val2.bonesCostAdjustment = transformStringIntoInt(infoAsDictionary["mods[" + i + "].bonesCostAdjustment"]);
					}
					else
					{
						val2.bonesCostAdjustment = 0;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].energyCostAdjustment"))
					{
						val2.energyCostAdjustment = transformStringIntoInt(infoAsDictionary["mods[" + i + "].energyCostAdjustment"]);
					}
					else
					{
						val2.energyCostAdjustment = 0;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].nullifyGemsCost"))
					{
						val2.nullifyGemsCost = transformStringIntoInt(infoAsDictionary["mods[" + i + "].nullifyGemsCost"]) != 0;
					}
					else
					{
						val2.nullifyGemsCost = false;
					}
					val2.addGemCost = new List<GemType>();
					if (infoAsDictionary.ContainsKey("mods[" + i + "].addGemCost.Count"))
					{
						for (int m = 0; m < transformStringIntoInt(infoAsDictionary["mods[" + i + "].addGemCost.Count"]); m++)
						{
							if (infoAsDictionary.ContainsKey("mods[" + i + "].addGemCost[" + m + "]"))
							{
								val2.addGemCost.Add((GemType)transformStringIntoInt(infoAsDictionary["mods[" + i + "].addGemCost[" + m + "]"]));
							}
						}
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].gemify"))
					{
						val2.gemify = transformStringIntoInt(infoAsDictionary["mods[" + i + "].gemify"]) != 0;
					}
					else
					{
						val2.gemify = false;
					}
					val2.specialAbilities = new List<SpecialTriggeredAbility>();
					if (infoAsDictionary.ContainsKey("mods[" + i + "].specialAbilities.Count"))
					{
						int j;
						for (j = 0; j < transformStringIntoInt(infoAsDictionary["mods[" + i + "].specialAbilities.Count"]); j++)
						{
							if (infoAsDictionary.ContainsKey("mods[" + i + "].specialAbilities[" + j + "]") && SpecialTriggeredAbilityManager.AllSpecialTriggers.Exists((FullSpecialTriggeredAbility fa) => (int)fa.Id == transformStringIntoInt(infoAsDictionary["mods[" + i + "].specialAbilities[" + j + "]"])))
							{
								val2.specialAbilities.Add((SpecialTriggeredAbility)transformStringIntoInt(infoAsDictionary["mods[" + i + "].specialAbilities[" + j + "]"]));
							}
						}
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].statIcon") && StatIconManager.AllStatIcons.Exists((FullStatIcon fsi) => (int)fsi.Id == transformStringIntoInt(infoAsDictionary["mods[" + i + "].statIcon"])))
					{
						val2.statIcon = (SpecialStatIcon)transformStringIntoInt(infoAsDictionary["mods[" + i + "].statIcon"]);
					}
					else
					{
						val2.statIcon = (SpecialStatIcon)0;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].fromCardMerge"))
					{
						val2.fromCardMerge = transformStringIntoInt(infoAsDictionary["mods[" + i + "].fromCardMerge"]) != 0;
					}
					else
					{
						val2.fromCardMerge = false;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].fromDuplicateMerge"))
					{
						val2.fromDuplicateMerge = transformStringIntoInt(infoAsDictionary["mods[" + i + "].fromDuplicateMerge"]) != 0;
					}
					else
					{
						val2.fromDuplicateMerge = false;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].fromTotem"))
					{
						val2.fromTotem = transformStringIntoInt(infoAsDictionary["mods[" + i + "].fromTotem"]) != 0;
					}
					else
					{
						val2.fromTotem = false;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].fromLatch"))
					{
						val2.fromLatch = transformStringIntoInt(infoAsDictionary["mods[" + i + "].fromLatch"]) != 0;
					}
					else
					{
						val2.fromLatch = false;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].fromOverclock"))
					{
						val2.fromOverclock = transformStringIntoInt(infoAsDictionary["mods[" + i + "].fromOverclock"]) != 0;
					}
					else
					{
						val2.fromOverclock = false;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].sideDeckMod"))
					{
						val2.sideDeckMod = transformStringIntoInt(infoAsDictionary["mods[" + i + "].sideDeckMod"]) != 0;
					}
					else
					{
						val2.sideDeckMod = false;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].nonCopyable"))
					{
						val2.nonCopyable = transformStringIntoInt(infoAsDictionary["mods[" + i + "].nonCopyable"]) != 0;
					}
					else
					{
						val2.nonCopyable = false;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].fromEvolve"))
					{
						val2.fromEvolve = transformStringIntoInt(infoAsDictionary["mods[" + i + "].fromEvolve"]) != 0;
					}
					else
					{
						val2.fromEvolve = false;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].transformerBeastCardId"))
					{
						val2.transformerBeastCardId = infoAsDictionary["mods[" + i + "].transformerBeastCardId"];
					}
					else
					{
						val2.transformerBeastCardId = null;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo"))
					{
						if (infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo.headType") && infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo.lostEye"))
						{
							val2.deathCardInfo = new DeathCardInfo((FigurineType)transformStringIntoInt(infoAsDictionary["mods[" + i + "].deathCardInfo.headType"]), transformStringIntoInt(infoAsDictionary["mods[" + i + "].deathCardInfo.lostEye"]) != 0);
							if (infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo.mouthIndex"))
							{
								val2.deathCardInfo.mouthIndex = transformStringIntoInt(infoAsDictionary["mods[" + i + "].deathCardInfo.mouthIndex"]);
							}
							else
							{
								val2.deathCardInfo.mouthIndex = 0;
							}
							if (infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo.eyesIndex"))
							{
								val2.deathCardInfo.eyesIndex = transformStringIntoInt(infoAsDictionary["mods[" + i + "].deathCardInfo.eyesIndex"]);
							}
							else
							{
								val2.deathCardInfo.eyesIndex = 0;
							}
						}
						else if (infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo.headType") && infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo.mouthIndex") && infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo.eyesIndex"))
						{
							val2.deathCardInfo = new DeathCardInfo((FigurineType)transformStringIntoInt(infoAsDictionary["mods[" + i + "].deathCardInfo.headType"]), transformStringIntoInt(infoAsDictionary["mods[" + i + "].deathCardInfo.mouthIndex"]), transformStringIntoInt(infoAsDictionary["mods[" + i + "].deathCardInfo.eyesIndex"]));
							if (infoAsDictionary.ContainsKey("mods[" + i + "].deathCardInfo.lostEye"))
							{
								val2.deathCardInfo.lostEye = transformStringIntoInt(infoAsDictionary["mods[" + i + "].deathCardInfo.lostEye"]) != 0;
							}
							else
							{
								val2.deathCardInfo.lostEye = false;
							}
						}
					}
					else
					{
						val2.deathCardInfo = null;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].bountyHunterInfo"))
					{
						val2.bountyHunterInfo = new BountyHunterInfo();
						if (infoAsDictionary.ContainsKey("mods[" + i + "].bountyHunterInfo.faceIndex"))
						{
							val2.bountyHunterInfo.faceIndex = transformStringIntoInt(infoAsDictionary["mods[" + i + "].bountyHunterInfo.faceIndex"]);
						}
						else
						{
							val2.bountyHunterInfo.faceIndex = 0;
						}
						if (infoAsDictionary.ContainsKey("mods[" + i + "].bountyHunterInfo.hatIndex"))
						{
							val2.bountyHunterInfo.hatIndex = transformStringIntoInt(infoAsDictionary["mods[" + i + "].bountyHunterInfo.hatIndex"]);
						}
						else
						{
							val2.bountyHunterInfo.hatIndex = 0;
						}
						if (infoAsDictionary.ContainsKey("mods[" + i + "].bountyHunterInfo.mouthIndex"))
						{
							val2.bountyHunterInfo.mouthIndex = transformStringIntoInt(infoAsDictionary["mods[" + i + "].bountyHunterInfo.mouthIndex"]);
						}
						else
						{
							val2.bountyHunterInfo.mouthIndex = 0;
						}
						if (infoAsDictionary.ContainsKey("mods[" + i + "].bountyHunterInfo.eyesIndex"))
						{
							val2.bountyHunterInfo.eyesIndex = transformStringIntoInt(infoAsDictionary["mods[" + i + "].bountyHunterInfo.eyesIndex"]);
						}
						else
						{
							val2.bountyHunterInfo.eyesIndex = 0;
						}
						if (infoAsDictionary.ContainsKey("mods[" + i + "].bountyHunterInfo.tier"))
						{
							val2.bountyHunterInfo.tier = transformStringIntoInt(infoAsDictionary["mods[" + i + "].bountyHunterInfo.tier"]);
						}
						else
						{
							val2.bountyHunterInfo.tier = 0;
						}
						if (infoAsDictionary.ContainsKey("mods[" + i + "].bountyHunterInfo.dialogueIndex"))
						{
							val2.bountyHunterInfo.dialogueIndex = transformStringIntoInt(infoAsDictionary["mods[" + i + "].bountyHunterInfo.dialogueIndex"]);
						}
						else
						{
							val2.bountyHunterInfo.dialogueIndex = 0;
						}
						if (infoAsDictionary.ContainsKey("mods[" + i + "].bountyHunterInfo.status"))
						{
							val2.bountyHunterInfo.status = (Status)transformStringIntoInt(infoAsDictionary["mods[" + i + "].bountyHunterInfo.status"]);
						}
						else
						{
							val2.bountyHunterInfo.status = (Status)0;
						}
					}
					else
					{
						val2.bountyHunterInfo = null;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].buildACardPortraitInfo.spriteIndices.Length"))
					{
						val2.buildACardPortraitInfo = new BuildACardPortraitInfo();
						val2.buildACardPortraitInfo.spriteIndices = new int[transformStringIntoInt(infoAsDictionary["mods[" + i + "].buildACardPortraitInfo.spriteIndices.Length"])];
						for (int n = 0; n < transformStringIntoInt(infoAsDictionary["mods[" + i + "].buildACardPortraitInfo.spriteIndices.Length"]); n++)
						{
							if (infoAsDictionary.ContainsKey("mods[" + i + "].buildACardPortraitInfo.spriteIndices[" + n + "]"))
							{
								val2.buildACardPortraitInfo.spriteIndices[n] = transformStringIntoInt(infoAsDictionary["mods[" + i + "].buildACardPortraitInfo.spriteIndices[" + n + "]"]);
							}
						}
					}
					else
					{
						val2.buildACardPortraitInfo = null;
					}
					if (infoAsDictionary.ContainsKey("mods[" + i + "].decalIds.Count"))
					{
						val2.decalIds = new List<string>();
						for (int num = 0; num < transformStringIntoInt(infoAsDictionary["mods[" + i + "].decalIds.Count"]); num++)
						{
							if (infoAsDictionary.ContainsKey("mods[" + i + "].decalIds[" + num + "]"))
							{
								val2.decalIds.Add(infoAsDictionary["mods[" + i + "].decalIds[" + num + "]"]);
							}
						}
					}
					else
					{
						val2.decalIds = null;
					}
					val.mods.Add(val2);
				}
			}
			return val;
		}
	}
	public static class NewNodes
	{
		public static void createNodes()
		{
			YouveGotMailed.register();
		}
	}
	public class YouveGotMailed : CardChoicesSequencer, ICustomNodeSequencer
	{
		public static FullNode youveGotMailed;

		[SerializeField]
		private Animator stoneCircleAnim;

		[SerializeField]
		private SelectCardFromDeckSlot chooseSlot;

		[SerializeField]
		private ConfirmStoneButton confirmStone;

		private GameObject cardHolder;

		protected CardInfo choosenSendInfo;

		protected SelectableCard chosenReward;

		private bool didIntroSequence = false;

		private void IntroSequence()
		{
			base.selectableCards = new List<SelectableCard>();
			GameObject val = Object.Instantiate<GameObject>(ResourceBank.Get<GameObject>("Prefabs/SpecialNodeSequences/CardRemoveSequencer"), ((Component)Singleton<SpecialNodeHandler>.Instance).transform);
			CardRemoveSequencer component = val.GetComponent<CardRemoveSequencer>();
			base.gamepadGrid = ((CardChoicesSequencer)component).gamepadGrid;
			stoneCircleAnim = component.stoneCircleAnim;
			Plugin.Logger.LogInfo((object)"This object have those Components:");
			((Component)val.transform.GetChild(2).GetChild(0).GetChild(1)).gameObject.SetActive(false);
			((Component)val.transform.GetChild(2).GetChild(0).GetChild(2)).gameObject.SetActive(false);
			((Component)val.transform.GetChild(2).GetChild(0).GetChild(3)).gameObject.SetActive(false);
			((Component)val.transform.GetChild(2).GetChild(1)).gameObject.SetActive(false);
			((Component)val.transform.GetChild(2).GetChild(2)).gameObject.SetActive(false);
			((Component)val.transform.GetChild(2).GetChild(3)).gameObject.SetActive(false);
			((Component)val.transform.GetChild(2).GetChild(4)).gameObject.SetActive(false);
			((Component)val.transform.GetChild(2).GetChild(5)).gameObject.SetActive(false);
			cardHolder = ((Component)val.transform.GetChild(2).GetChild(0).GetChild(0)).gameObject;
			confirmStone = component.confirmStone;
			chooseSlot = component.sacrificeSlot;
			base.deckPile = ((CardChoicesSequencer)component).deckPile;
			Object.Destroy((Object)(object)component);
			didIntroSequence = true;
		}

		public IEnumerator DoCustomSequence(CustomSpecialNodeData node)
		{
			if (!didIntroSequence)
			{
				IntroSequence();
			}
			yield return Singleton<TextDisplayer>.Instance.ShowMessage("There could be a lag spike (online stuff), hold on...", (Emotion)0, (LetterAnimation)1, (Speaker)0, (string[])null);
			Process.Start(new ProcessStartInfo
			{
				Arguments = "Load",
				FileName = Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/GeckVolantMarin-OnlineCardChoice-Loader.exe"),
				WindowStyle = ProcessWindowStyle.Hidden,
				CreateNoWindow = false
			});
			chooseSlot.Disable();
			Singleton<TableRuleBook>.Instance.SetOnBoard(true);
			Singleton<ViewManager>.Instance.Controller.SwitchToControlMode((ControlMode)5, false);
			Singleton<ViewManager>.Instance.Controller.LockState = (ViewLockState)1;
			yield return (object)new WaitForSeconds(0.3f);
			((Component)stoneCircleAnim).gameObject.SetActive(true);
			yield return (object)new WaitForSeconds(0.5f);
			yield return base.deckPile.SpawnCards(RunState.DeckList.Count, 0.5f);
			Singleton<ViewManager>.Instance.SwitchToView((View)8, false, false);
			yield return Singleton<TextDisplayer>.Instance.ShowUntilInput("Choose a card to send to \"The Web\"", -2.5f, 0.5f, (Emotion)0, (LetterAnimation)1, (Speaker)0, (string[])null, true);
			chooseSlot.RevealAndEnable();
			((InteractableBase)chooseSlot).ClearDelegates();
			SelectCardFromDeckSlot selectCardFromDeckSlot = chooseSlot;
			((MainInputInteractable)selectCardFromDeckSlot).CursorSelectStarted = (Action<MainInputInteractable>)Delegate.Combine(((MainInputInteractable)selectCardFromDeckSlot).CursorSelectStarted, new Action<MainInputInteractable>(OnSlotSelected));
			chooseSlot.backOutInputPressed = null;
			SelectCardFromDeckSlot selectCardFromDeckSlot2 = chooseSlot;
			selectCardFromDeckSlot2.backOutInputPressed = (Action)Delegate.Combine(selectCardFromDeckSlot2.backOutInputPressed, (Action)delegate
			{
				if (((InteractableBase)chooseSlot).Enabled)
				{
					OnSlotSelected((MainInputInteractable)(object)chooseSlot);
				}
			});
			((Behaviour)base.gamepadGrid).enabled = true;
			yield return confirmStone.WaitUntilConfirmation();
			yield return ((CardChoicesSequencer)this).ExamineCardWithDialogue(chooseSlot.Card, "Your " + ((Card)chooseSlot.Card).Info.displayedName + " will be sent to \"The Web\".");
			choosenSendInfo = ((Card)chooseSlot.Card).Info;
			Object.Destroy((Object)(object)((Component)chooseSlot.Card).gameObject);
			yield return base.deckPile.DestroyCards(0.5f);
			stoneCircleAnim.SetTrigger("exit");
			Singleton<ExplorableAreaManager>.Instance.ResetHangingLightsToZoneColors(0.25f);
			yield return (object)new WaitForSeconds(0.25f);
			confirmStone.Exit();
			yield return (object)new WaitForSeconds(0.75f);
			((Component)stoneCircleAnim).gameObject.SetActive(false);
			confirmStone.SetStoneInactive();
			int chosenCardId = 0;
			yield return Singleton<TextDisplayer>.Instance.ShowUntilInput("A package just arrived.", -2.5f, 0.5f, (Emotion)1, (LetterAnimation)1, (Speaker)0, (string[])null, true);
			string[] cardInfosAsStrings = new string[3] { "", "", "" };
			chosenReward = null;
			GameObject cardRemoveSequencerObj = Object.Instantiate<GameObject>(ResourceBank.Get<GameObject>("Prefabs/SpecialNodeSequences/CardRemoveSequencer"), ((Component)Singleton<SpecialNodeHandler>.Instance).transform);
			CardRemoveSequencer oldRemoveSequencer = cardRemoveSequencerObj.GetComponent<CardRemoveSequencer>();
			base.selectableCards = ((CardChoicesSequencer)oldRemoveSequencer).SpawnCards(3, ((Component)this).transform, new Vector3(-1.5f, 5.01f, 0f), 1.5f);
			Object.Destroy((Object)(object)oldRemoveSequencer);
			Object.Destroy((Object)(object)cardRemoveSequencerObj);
			for (int l = 0; l < 3; l++)
			{
				StreamReader sr = new StreamReader(Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/cardData" + l));
				cardInfosAsStrings[l] = sr.ReadToEnd();
				CardInfo cardInfo = Utils.stringToCardInfo(cardInfosAsStrings[l]);
				sr.Close();
				SelectableCard card = base.selectableCards[l];
				((Component)card).gameObject.SetActive(true);
				card.SetParticlesEnabled(true);
				((InteractableBase)card).SetEnabled(false);
				if ((Object)(object)cardInfo != (Object)null)
				{
					card.Initialize(cardInfo, (Action<SelectableCard>)OnRewardChosen, (Action<SelectableCard>)OnCardFlipped, true, (Action<SelectableCard>)base.OnCardInspected);
				}
				SpecialCardBehaviour[] components = ((Component)card).GetComponents<SpecialCardBehaviour>();
				for (int m = 0; m < components.Length; m++)
				{
					components[m].OnShownForCardChoiceNode();
				}
				((Card)card).SetFaceDown(true, true);
				Vector3 position = ((Component)card).transform.position;
				((Component)card).transform.position = ((Component)card).transform.position + Vector3.forward * 5f + new Vector3(-0.5f + Random.value * 1f, 0f, 0f);
				Tween.Position(((Component)card).transform, position, 0.3f, 0f, Tween.EaseInOut, (LoopType)0, (Action)null, (Action)null, true);
				Tween.Rotate(((Component)card).transform, new Vector3(0f, 0f, Random.value * 1.5f), (Space)1, 0.4f, 0f, Tween.EaseOut, (LoopType)0, (Action)null, (Action)null, true);
				yield return (object)new WaitForSeconds(0.2f);
				ParticleSystem componentInChildren = ((Component)card).GetComponentInChildren<ParticleSystem>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					EmissionModule emission = componentInChildren.emission;
					((EmissionModule)(ref emission)).rateOverTime = MinMaxCurve.op_Implicit(0f);
					emission = default(EmissionModule);
				}
			}
			yield return (object)new WaitForSeconds(0.2f);
			if (base.selectableCards.Exists((SelectableCard sc) => ((Card)sc).Info.appearanceBehaviour.Exists((Appearance a) => a == Shredded.id)))
			{
				yield return Singleton<TextDisplayer>.Instance.ShowUntilInput("The package was damaged during shipping, some cards could be different.", 4.5f, 0.5f, (Emotion)2, (LetterAnimation)1, (Speaker)0, (string[])null, true);
				yield return Singleton<TextDisplayer>.Instance.ShowUntilInput("I should really think of a new shipping method...", 4.5f, 0.5f, (Emotion)3, (LetterAnimation)1, (Speaker)0, (string[])null, true);
			}
			yield return Singleton<TextDisplayer>.Instance.ShowUntilInput("Choose a card", 4.5f, 0.5f, (Emotion)0, (LetterAnimation)1, (Speaker)0, (string[])null, true);
			((CardChoicesSequencer)this).SetCollidersEnabled(true);
			((CardChoicesSequencer)this).EnableViewDeck((ControlMode)11, ((Component)this).transform.position);
			yield return (object)new WaitUntil((Func<bool>)(() => (Object)(object)chosenReward != (Object)null));
			yield return ((CardChoicesSequencer)this).ExamineCardWithDialogue(chosenReward, ((Card)chosenReward).Info.description);
			for (int k = 0; k < 3; k++)
			{
				if (((Component)chosenReward).transform.position == ((Component)base.selectableCards[k]).transform.position)
				{
					chosenCardId = k;
				}
			}
			((CardCollectionInfo)RunState.Run.playerDeck).RemoveCard(choosenSendInfo);
			((CardCollectionInfo)RunState.Run.playerDeck).AddCard(((Card)chosenReward).Info);
			Tween.Position(((Component)chosenReward).transform, ((Component)chosenReward).transform.position + Vector3.forward * 20f, 0.5f, 0f, Tween.EaseInOut, (LoopType)0, (Action)null, (Action)null, true);
			Object.Destroy((Object)(object)((Component)chosenReward).gameObject, 0.5f);
			yield return Singleton<TextDisplayer>.Instance.ShowMessage("There could be another lag spike (you know, online stuff), hold on...", (Emotion)0, (LetterAnimation)1, (Speaker)0, (string[])null);
			string[] allCardInfoPaths = Directory.GetFiles(Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/cards/assets/current"));
			string[] array = allCardInfoPaths;
			foreach (string path in array)
			{
				File.Delete(path);
			}
			StreamWriter[] sw = new StreamWriter[3];
			for (int j = 0; j < 3; j++)
			{
				sw[j] = new StreamWriter(Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/cardData" + j));
			}
			if (chosenCardId == 0)
			{
				sw[0].Write(Utils.cardInfoToString(choosenSendInfo));
			}
			else
			{
				sw[0].Write(Utils.cardInfoToString(((Card)base.selectableCards[0]).Info));
			}
			if (chosenCardId == 1)
			{
				sw[1].Write(Utils.cardInfoToString(choosenSendInfo));
			}
			else
			{
				sw[1].Write(Utils.cardInfoToString(((Card)base.selectableCards[1]).Info));
			}
			if (chosenCardId == 2)
			{
				sw[2].Write(Utils.cardInfoToString(choosenSendInfo));
			}
			else
			{
				sw[2].Write(Utils.cardInfoToString(((Card)base.selectableCards[2]).Info));
			}
			for (int i = 0; i < 3; i++)
			{
				sw[i].Close();
			}
			Process.Start(new ProcessStartInfo
			{
				Arguments = "Save",
				FileName = Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/GeckVolantMarin-OnlineCardChoice-Loader.exe"),
				WindowStyle = ProcessWindowStyle.Hidden,
				CreateNoWindow = false
			});
			yield return Singleton<TextDisplayer>.Instance.ShowUntilInput("You take your card from \"The Web\" and carry onward.", -2.5f, 0.5f, (Emotion)1, (LetterAnimation)1, (Speaker)0, (string[])null, true);
			((CardChoicesSequencer)this).DisableViewDeck();
			CleanUpCards();
			yield return NotAddCardToDeckAndCleanUp(chosenReward);
		}

		private void OnSlotSelected(MainInputInteractable slot)
		{
			((Behaviour)base.gamepadGrid).enabled = false;
			((InteractableBase)chooseSlot).SetEnabled(false);
			((HighlightedInteractable)chooseSlot).ShowState((State)1, false, 0.15f);
			confirmStone.Exit();
			((SelectCardFromDeckSlot)((slot is SelectCardFromDeckSlot) ? slot : null)).SelectFromCards(GetValidCards(), (Action)OnSelectionEnded, false);
		}

		private void OnSelectionEnded()
		{
			((Behaviour)base.gamepadGrid).enabled = true;
			((HighlightedInteractable)chooseSlot).SetShown(true, false);
			((HighlightedInteractable)chooseSlot).ShowState((State)2, false, 0.15f);
			Singleton<ViewManager>.Instance.SwitchToView((View)8, false, true);
			if ((Object)(object)chooseSlot.Card != (Object)null)
			{
				confirmStone.Enter();
			}
		}

		private List<CardInfo> GetValidCards()
		{
			List<CardInfo> list = new List<CardInfo>(RunState.DeckList);
			list.RemoveAll((CardInfo c) => c.appearanceBehaviour.Exists((Appearance a) => a == Shredded.id) || ((Object)(object)c.animatedPortrait != (Object)null && ((Object)c).name != "!DEATHCARD_BASE" && ((Object)c).name != "!STATIC!GLITCH" && ((Object)c).name != "Stinkbug_Talking" && ((Object)c).name != "Stoat_Talking" && ((Object)c).name != "Wolf_Talking"));
			return list;
		}

		protected void OnRewardChosen(SelectableCard card)
		{
			if (!ProgressionData.LearnedMechanic((MechanicsConcept)14) && !AllCardsFlippedUp())
			{
				HintsHandler.OnClickCardChoiceWhileOtherFlipped();
			}
			else if ((Object)(object)chosenReward == (Object)null)
			{
				((CardChoicesSequencer)this).SetCollidersEnabled(false);
				chosenReward = card;
			}
		}

		private bool AllCardsFlippedUp()
		{
			return !base.selectableCards.Exists((SelectableCard x) => x.Flipped);
		}

		protected void OnCardFlipped(SelectableCard card)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			card.SetLocalPosition(Vector3.zero, 0f, true);
			if ((Object)(object)Singleton<InteractionCursor>.Instance.CurrentInteractable == (Object)(object)card)
			{
				((CardChoicesSequencer)this).OnCardInspected(card);
			}
		}

		protected void CleanUpCards(bool doTween = true)
		{
			//IL_004e: 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_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			((CardChoicesSequencer)this).ResetLocalRotations();
			foreach (SelectableCard selectableCard in base.selectableCards)
			{
				((Card)selectableCard).SetInteractionEnabled(false);
				if ((Object)(object)selectableCard != (Object)(object)chosenReward)
				{
					if (doTween)
					{
						Tween.Position(((Component)selectableCard).transform, ((Component)selectableCard).transform.position + Vector3.forward * 20f, 0.5f, 0f, Tween.EaseInOut, (LoopType)0, (Action)null, (Action)null, true);
					}
					Object.Destroy((Object)(object)((Component)selectableCard).gameObject, doTween ? 0.5f : 0f);
				}
			}
			base.selectableCards.Clear();
		}

		protected virtual IEnumerator NotAddCardToDeckAndCleanUp(SelectableCard card)
		{
			Singleton<RuleBookController>.Instance.SetShown(false, true);
			ProgressionData.SetMechanicLearned((MechanicsConcept)14);
			Singleton<TextDisplayer>.Instance.Clear();
			yield return (object)new WaitForSeconds(0.1f);
		}

		private IEnumerator RewardChosenSequence(SelectableCard card)
		{
			card.OnCardAddedToDeck();
			yield return (object)new WaitForSeconds(0.5f);
		}

		public static void register()
		{
			ProcessStartInfo processStartInfo = new ProcessStartInfo();
			processStartInfo.Arguments = "Load";
			processStartInfo.FileName = Path.Combine(Path.GetDirectoryName(Plugin.directory), "OnlineShenanigans/GeckVolantMarin-OnlineCardChoice-Loader.exe");
			processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
			processStartInfo.CreateNoWindow = false;
			Process.Start(processStartInfo);
			youveGotMailed = NewNodeManager.New("GeckVolantMarin-OnlineCardChoice", "YouveGotMailed", (GenerationType)1, typeof(YouveGotMailed), new List<Texture2D>
			{
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_1.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_1.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_1.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_1.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_1.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_1g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_5g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_1.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_1g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_5g.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_2.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_3.png"), (FilterMode)0),
				TextureHelper.GetImageAsTexture(Path.Combine(Path.GetDirectoryName(Plugin.directory), "assets/Nodes/youveGotMailed/icon_4.png"), (FilterMode)0)
			}, (List<SelectionCondition>)null, (List<SelectionCondition>)null, (Action<CustomSpecialNodeData>)null, (Action<CustomSpecialNodeData, MapNode2D>)null, (GameObject)null, (GameObject)null);
		}
	}
	[BepInPlugin("GeckVolantMarin-OnlineCardChoice", "GeckVolantMarin-OnlineCardChoice", "1.0.0")]
	[BepInProcess("Inscryption.exe")]
	public class Plugin : BaseUnityPlugin
	{
		internal static ManualLogSource Logger;

		public static string directory;

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			directory = ((BaseUnityPlugin)this).Info.Location;
			NewCards.createCards();
			NewNodes.createNodes();
			Logger.LogInfo((object)"Reussi?");
			Logger.LogInfo((object)"Plugin GeckVolantMarin-OnlineCardChoice is loaded!");
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "GeckVolantMarin-OnlineCardChoice";

		public const string PLUGIN_NAME = "GeckVolantMarin-OnlineCardChoice";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}

plugins/OnlineShenanigans/GeckVolantMarin-OnlineCardChoice-Loader.dll

Decompiled 2 years ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Sockets;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(/*Could not decode attribute arguments.*/)]
[assembly: TargetFramework(".NETCoreApp,Version=v8.0", FrameworkDisplayName = ".NET 8.0")]
[assembly: AssemblyCompany("GeckVolantMarin-OnlineCardChoice-Loader")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("GeckVolantMarin-OnlineCardChoice-Loader")]
[assembly: AssemblyTitle("GeckVolantMarin-OnlineCardChoice-Loader")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
public class FileTransferClient
{
	private static readonly string ClientDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

	private static readonly byte[] ack = new byte[1] { 1 };

	private static bool confirmation = false;

	public static void Main(string[] args)
	{
		if (args.Length < 1)
		{
			Console.WriteLine("Usage: client <Save/Load>");
			return;
		}
		string action = args[0];
		StartClient(action);
	}

	private static void StartClient(string action)
	{
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0024: Expected O, but got Unknown
		//IL_002a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Expected O, but got Unknown
		TcpClient val = new TcpClient("74.15.144.244", 43857);
		NetworkStream stream = val.GetStream();
		StreamReader reader = new StreamReader((Stream)(object)stream, Encoding.UTF8);
		StreamWriter val2 = new StreamWriter((Stream)(object)stream, Encoding.UTF8);
		confirmation = false;
		while (!confirmation)
		{
			confirmation = true;
			((TextWriter)val2).WriteLine(action);
			((TextWriter)val2).Flush();
			byte[] array = new byte[1];
			if (((Stream)stream).Read(array, 0, array.Length) == 0)
			{
				Console.WriteLine("Server disconnected while waiting for ACK.");
				return;
			}
			if (array[0] == 1)
			{
				Console.WriteLine("Chunk acknowledged.");
			}
			else
			{
				confirmation = false;
			}
		}
		if (action == "Save")
		{
			SendFiles(stream, val2);
		}
		else if (action == "Load")
		{
			ReceiveFiles(stream, reader);
		}
		val.Close();
	}

	private static void SendFiles(NetworkStream stream, StreamWriter writer)
	{
		//IL_0110: Unknown result type (might be due to invalid IL or missing references)
		//IL_0115: Unknown result type (might be due to invalid IL or missing references)
		//IL_01ca: Unknown result type (might be due to invalid IL or missing references)
		//IL_01d1: Expected O, but got Unknown
		//IL_0261: Unknown result type (might be due to invalid IL or missing references)
		//IL_0268: Expected O, but got Unknown
		List<string> val = new List<string>();
		for (int i = 0; i < 3; i++)
		{
			val.Add(Path.Combine(ClientDirectory, $"cardData{i}"));
		}
		string text = Path.Combine(ClientDirectory, "cards/assets/current");
		if (Directory.Exists(text))
		{
			val.AddRange((global::System.Collections.Generic.IEnumerable<string>)Directory.GetFiles(text, "*.png"));
		}
		confirmation = false;
		while (!confirmation)
		{
			confirmation = true;
			((TextWriter)writer).WriteLine(val.Count);
			((TextWriter)writer).Flush();
			byte[] array = new byte[1];
			if (((Stream)stream).Read(array, 0, array.Length) == 0)
			{
				Console.WriteLine("Server disconnected while waiting for ACK.");
				return;
			}
			if (array[0] == 1)
			{
				Console.WriteLine("Chunk acknowledged.");
			}
			else
			{
				confirmation = false;
			}
		}
		Enumerator<string> enumerator = val.GetEnumerator();
		try
		{
			while (enumerator.MoveNext())
			{
				string current = enumerator.Current;
				if (!File.Exists(current))
				{
					continue;
				}
				confirmation = false;
				while (!confirmation)
				{
					confirmation = true;
					((TextWriter)writer).WriteLine(Path.GetFileName(current));
					((TextWriter)writer).Flush();
					byte[] array2 = new byte[1];
					if (((Stream)stream).Read(array2, 0, array2.Length) == 0)
					{
						Console.WriteLine("Server disconnected while waiting for ACK.");
						return;
					}
					if (array2[0] == 1)
					{
						Console.WriteLine("Chunk acknowledged.");
					}
					else
					{
						confirmation = false;
					}
				}
				FileInfo val2 = new FileInfo(current);
				confirmation = false;
				while (!confirmation)
				{
					confirmation = true;
					((TextWriter)writer).WriteLine(val2.Length);
					((TextWriter)writer).Flush();
					byte[] array3 = new byte[1];
					if (((Stream)stream).Read(array3, 0, array3.Length) == 0)
					{
						Console.WriteLine("Server disconnected while waiting for ACK.");
						return;
					}
					if (array3[0] == 1)
					{
						Console.WriteLine("Chunk acknowledged.");
					}
					else
					{
						confirmation = false;
					}
				}
				FileStream val3 = new FileStream(current, (FileMode)3);
				try
				{
					confirmation = false;
					while (!confirmation)
					{
						confirmation = true;
						((Stream)val3).CopyTo((Stream)(object)stream);
						((Stream)val3).Flush();
						byte[] array4 = new byte[1];
						if (((Stream)stream).Read(array4, 0, array4.Length) == 0)
						{
							Console.WriteLine("Server disconnected while waiting for ACK.");
							return;
						}
						if (array4[0] == 1)
						{
							Console.WriteLine("Chunk acknowledged.");
						}
						else
						{
							confirmation = false;
						}
					}
				}
				finally
				{
					((global::System.IDisposable)val3)?.Dispose();
				}
			}
		}
		finally
		{
			((global::System.IDisposable)enumerator).Dispose();
		}
	}

	private static void ReceiveFiles(NetworkStream stream, StreamReader reader)
	{
		//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00be: Expected O, but got Unknown
		int num = int.Parse(((TextReader)reader).ReadLine());
		((Stream)stream).Write(ack, 0, ack.Length);
		((Stream)stream).Flush();
		for (int i = 0; i < num; i++)
		{
			string text = ((TextReader)reader).ReadLine();
			((Stream)stream).Write(ack, 0, ack.Length);
			((Stream)stream).Flush();
			long num2 = long.Parse(((TextReader)reader).ReadLine());
			((Stream)stream).Write(ack, 0, ack.Length);
			((Stream)stream).Flush();
			string text2 = ((!text.EndsWith(".png")) ? Path.Combine(ClientDirectory, text) : Path.Combine(ClientDirectory, "cards/assets/" + text));
			FileStream val = new FileStream(text2, (FileMode)2);
			try
			{
				byte[] array = new byte[4096];
				long num3 = num2;
				while (num3 > 0)
				{
					int num4 = ((Stream)stream).Read(array, 0, (int)Math.Min(num3, (long)array.Length));
					((Stream)stream).Write(ack, 0, ack.Length);
					((Stream)stream).Flush();
					((Stream)val).Write(array, 0, num4);
					num3 -= num4;
				}
			}
			finally
			{
				((global::System.IDisposable)val)?.Dispose();
			}
			Console.WriteLine("Received file: " + text);
		}
	}
}

plugins/OnlineShenanigans/Microsoft.Bcl.AsyncInterfaces.dll

Decompiled 2 years ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading.Tasks.Sources;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: CLSCompliant(true)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyDefaultAlias("Microsoft.Bcl.AsyncInterfaces")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[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.\r\n\r\nCommonly Used Types:\r\nSystem.IAsyncDisposable\r\nSystem.Collections.Generic.IAsyncEnumerable\r\nSystem.Collections.Generic.IAsyncEnumerator")]
[assembly: AssemblyFileVersion("6.0.21.52210")]
[assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Bcl.AsyncInterfaces")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("6.0.0.0")]
[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))]

plugins/OnlineShenanigans/Microsoft.Extensions.DependencyInjection.Abstractions.dll

Decompiled 2 years ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
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(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: CLSCompliant(true)]
[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.System32 | DllImportSearchPath.AssemblyDirectory)]
[assembly: AssemblyDefaultAlias("Microsoft.Extensions.DependencyInjection.Abstractions")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyMetadata(".NETFrameworkAssembly", "")]
[assembly: AssemblyMetadata("Serviceable", "True")]
[assembly: AssemblyMetadata("PreferInbox", "True")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[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("6.0.21.52210")]
[assembly: AssemblyInformationalVersion("6.0.0+4822e3c3aa77eb82b2fb33c9321f923cf11ddde6")]
[assembly: AssemblyProduct("Microsoft® .NET")]
[assembly: AssemblyTitle("Microsoft.Extensions.DependencyInjection.Abstractions")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/runtime")]
[assembly: AssemblyVersion("6.0.0.0")]
[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;
		}
	}
}
namespace FxResources.Microsoft.Extensions.DependencyInjection.Abstractions
{
	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 AmbiguousConstructorMatch => GetResourceString("AmbiguousConstructorMatch");

		internal static string CannotLocateImplementation => GetResourceString("CannotLocateImplementation");

		internal static string CannotResolveService => GetResourceString("CannotResolveService");

		internal static string NoConstructorMatch => GetResourceString("NoConstructorMatch");

		internal static string NoServiceRegistered => GetResourceString("NoServiceRegistered");

		internal static string TryAddIndistinguishableTypeToEnumerable => GetResourceString("TryAddIndistinguishableTypeToEnumerable");

		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 Microsoft.Extensions.Internal
{
	internal static class ParameterDefaultValue
	{
		public static bool TryGetDefaultValue(ParameterInfo parameter, out object? defaultValue)
		{
			bool tryToGetDefaultValue;
			bool flag = CheckHasDefaultValue(parameter, out tryToGetDefaultValue);
			defaultValue = null;
			if (flag)
			{
				if (tryToGetDefaultValue)
				{
					defaultValue = parameter.DefaultValue;
				}
				bool flag2 = parameter.ParameterType.IsGenericType && parameter.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>);
				if (defaultValue == null && parameter.ParameterType.IsValueType && !flag2)
				{
					defaultValue = CreateValueType(parameter.ParameterType);
				}
				if (defaultValue != null && flag2)
				{
					Type underlyingType = Nullable.GetUnderlyingType(parameter.ParameterType);
					if (underlyingType != null && underlyingType.IsEnum)
					{
						defaultValue = Enum.ToObject(underlyingType, defaultValue);
					}
				}
			}
			return flag;
			[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;
			return parameter.HasDefaultValue;
		}
	}
}
namespace Microsoft.Extensions.DependencyInjection
{
	public static class ActivatorUtilities
	{
		private struct ConstructorMatcher
		{
			private readonly ConstructorInfo _constructor;

			private readonly ParameterInfo[] _parameters;

			private readonly object[] _parameterValues;

			public ConstructorMatcher(ConstructorInfo constructor)
			{
				_constructor = constructor;
				_parameters = _constructor.GetParameters();
				_parameterValues = new object[_parameters.Length];
			}

			public int Match(object[] givenParameters)
			{
				int num = 0;
				int result = 0;
				for (int i = 0; i != givenParameters.Length; i++)
				{
					Type c = givenParameters[i]?.GetType();
					bool flag = false;
					int num2 = num;
					while (!flag && num2 != _parameters.Length)
					{
						if (_parameterValues[num2] == null && _parameters[num2].ParameterType.IsAssignableFrom(c))
						{
							flag = true;
							_parameterValues[num2] = givenParameters[i];
							if (num == num2)
							{
								num++;
								if (num2 == i)
								{
									result = num2;
								}
							}
						}
						num2++;
					}
					if (!flag)
					{
						return -1;
					}
				}
				return result;
			}

			public object CreateInstance(IServiceProvider provider)
			{
				for (int i = 0; i != _parameters.Length; i++)
				{
					if (_parameterValues[i] != null)
					{
						continue;
					}
					object service = provider.GetService(_parameters[i].ParameterType);
					if (service == null)
					{
						if (!ParameterDefaultValue.TryGetDefaultValue(_parameters[i], out object defaultValue))
						{
							throw new InvalidOperationException($"Unable to resolve service for type '{_parameters[i].ParameterType}' while attempting to activate '{_constructor.DeclaringType}'.");
						}
						_parameterValues[i] = defaultValue;
					}
					else
					{
						_parameterValues[i] = service;
					}
				}
				return _constructor.Invoke(BindingFlags.DoNotWrapExceptions, null, _parameterValues, null);
			}
		}

		private static readonly MethodInfo GetServiceInfo = GetMethodInfo<Func<IServiceProvider, Type, Type, bool, object>>((IServiceProvider sp, Type t, Type r, bool c) => GetService(sp, t, r, c));

		public static object CreateInstance(IServiceProvider provider, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, params object[] parameters)
		{
			int num = -1;
			bool flag = false;
			ConstructorMatcher constructorMatcher = default(ConstructorMatcher);
			if (!instanceType.IsAbstract)
			{
				ConstructorInfo[] constructors = instanceType.GetConstructors();
				foreach (ConstructorInfo constructorInfo in constructors)
				{
					ConstructorMatcher constructorMatcher2 = new ConstructorMatcher(constructorInfo);
					bool flag2 = constructorInfo.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false);
					int num2 = constructorMatcher2.Match(parameters);
					if (flag2)
					{
						if (flag)
						{
							ThrowMultipleCtorsMarkedWithAttributeException();
						}
						if (num2 == -1)
						{
							ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
						}
					}
					if (flag2 || num < num2)
					{
						num = num2;
						constructorMatcher = constructorMatcher2;
					}
					flag = flag || flag2;
				}
			}
			if (num == -1)
			{
				string message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided.";
				throw new InvalidOperationException(message);
			}
			return constructorMatcher.CreateInstance(provider);
		}

		public static ObjectFactory CreateFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes)
		{
			FindApplicableConstructor(instanceType, argumentTypes, out var matchingConstructor, out var matchingParameterMap);
			ParameterExpression parameterExpression = Expression.Parameter(typeof(IServiceProvider), "provider");
			ParameterExpression parameterExpression2 = Expression.Parameter(typeof(object[]), "argumentArray");
			Expression body = BuildFactoryExpression(matchingConstructor, matchingParameterMap, parameterExpression, parameterExpression2);
			Expression<Func<IServiceProvider, object[], object>> expression = Expression.Lambda<Func<IServiceProvider, object[], object>>(body, new ParameterExpression[2] { parameterExpression, parameterExpression2 });
			Func<IServiceProvider, object[], object> @object = expression.Compile();
			return @object.Invoke;
		}

		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 MethodInfo GetMethodInfo<T>(Expression<T> expr)
		{
			MethodCallExpression methodCallExpression = (MethodCallExpression)expr.Body;
			return methodCallExpression.Method;
		}

		private static object GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
		{
			object service = sp.GetService(type);
			if (service == null && !isDefaultParameterRequired)
			{
				string message = $"Unable to resolve service for type '{type}' while attempting to activate '{requiredBy}'.";
				throw new InvalidOperationException(message);
			}
			return service;
		}

		private static Expression 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
				{
					Expression[] arguments = new Expression[4]
					{
						serviceProvider,
						Expression.Constant(parameterType, typeof(Type)),
						Expression.Constant(constructor.DeclaringType, typeof(Type)),
						Expression.Constant(flag)
					};
					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.New(constructor, array);
		}

		private static void FindApplicableConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, out ConstructorInfo matchingConstructor, out int?[] matchingParameterMap)
		{
			ConstructorInfo matchingConstructor2 = null;
			int?[] parameterMap = null;
			if (!TryFindPreferredConstructor(instanceType, argumentTypes, ref matchingConstructor2, ref parameterMap) && !TryFindMatchingConstructor(instanceType, argumentTypes, ref matchingConstructor2, ref parameterMap))
			{
				string message = $"A suitable constructor for type '{instanceType}' could not be located. Ensure the type is concrete and all parameters of a public constructor are either registered as services or passed as arguments. Also ensure no extraneous arguments are provided.";
				throw new InvalidOperationException(message);
			}
			matchingConstructor = matchingConstructor2;
			matchingParameterMap = parameterMap;
		}

		private static bool TryFindMatchingConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] ref ConstructorInfo matchingConstructor, [NotNullWhen(true)] ref int?[] parameterMap)
		{
			ConstructorInfo[] constructors = instanceType.GetConstructors();
			foreach (ConstructorInfo constructorInfo in constructors)
			{
				if (TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2))
				{
					if (matchingConstructor != null)
					{
						throw new InvalidOperationException($"Multiple constructors accepting all given argument types have been found in type '{instanceType}'. There should only be one applicable constructor.");
					}
					matchingConstructor = constructorInfo;
					parameterMap = parameterMap2;
				}
			}
			if (matchingConstructor != null)
			{
				return true;
			}
			return false;
		}

		private static bool TryFindPreferredConstructor([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type instanceType, Type[] argumentTypes, [NotNullWhen(true)] ref ConstructorInfo matchingConstructor, [NotNullWhen(true)] ref int?[] parameterMap)
		{
			bool flag = false;
			ConstructorInfo[] constructors = instanceType.GetConstructors();
			foreach (ConstructorInfo constructorInfo in constructors)
			{
				if (constructorInfo.IsDefined(typeof(ActivatorUtilitiesConstructorAttribute), inherit: false))
				{
					if (flag)
					{
						ThrowMultipleCtorsMarkedWithAttributeException();
					}
					if (!TryCreateParameterMap(constructorInfo.GetParameters(), argumentTypes, out var parameterMap2))
					{
						ThrowMarkedCtorDoesNotTakeAllProvidedArguments();
					}
					matchingConstructor = constructorInfo;
					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("Multiple constructors were marked with ActivatorUtilitiesConstructorAttribute.");
		}

		private static void ThrowMarkedCtorDoesNotTakeAllProvidedArguments()
		{
			throw new InvalidOperationException("Constructor marked with ActivatorUtilitiesConstructorAttribute does not accept all given argument types.");
		}
	}
	[AttributeUsage(AttributeTargets.All)]
	public class ActivatorUtilitiesConstructorAttribute : Attribute
	{
	}
	public readonly struct AsyncServiceScope : IServiceScope, IDisposable, IAsyncDisposable
	{
		private readonly IServiceScope _serviceScope;

		public IServiceProvider ServiceProvider => _serviceScope.ServiceProvider;

		public AsyncServiceScope(IServiceScope serviceScope)
		{
			_serviceScope = serviceScope ?? throw new ArgumentNullException("serviceScope");
		}

		public void Dispose()
		{
			_serviceScope.Dispose();
		}

		public ValueTask DisposeAsync()
		{
			if (_serviceScope is IAsyncDisposable asyncDisposable)
			{
				return asyncDisposable.DisposeAsync();
			}
			_serviceScope.Dispose();
			return default(ValueTask);
		}
	}
	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 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 class ServiceCollection : IServiceCollection, IList<ServiceDescriptor>, ICollection<ServiceDescriptor>, IEnumerable<ServiceDescriptor>, IEnumerable
	{
		private readonly List<ServiceDescriptor> _descriptors = new List<ServiceDescriptor>();

		public int Count => _descriptors.Count;

		public bool IsReadOnly => false;

		public ServiceDescriptor this[int index]
		{
			get
			{
				return _descriptors[index];
			}
			set
			{
				_descriptors[index] = value;
			}
		}

		public void Clear()
		{
			_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)
		{
			return _descriptors.Remove(item);
		}

		public IEnumerator<ServiceDescriptor> GetEnumerator()
		{
			return _descriptors.GetEnumerator();
		}

		void ICollection<ServiceDescriptor>.Add(ServiceDescriptor item)
		{
			_descriptors.Add(item);
		}

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

		public int IndexOf(ServiceDescriptor item)
		{
			return _descriptors.IndexOf(item);
		}

		public void Insert(int index, ServiceDescriptor item)
		{
			_descriptors.Insert(index, item);
		}

		public void RemoveAt(int index)
		{
			_descriptors.RemoveAt(index);
		}
	}
	public static class ServiceCollectionServiceExtensions
	{
		public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			return Add(services, serviceType, implementationType, ServiceLifetime.Transient);
		}

		public static IServiceCollection AddTransient(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("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
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			return services.AddTransient(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddTransient(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			return services.AddTransient(serviceType, serviceType);
		}

		public static IServiceCollection AddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			return services.AddTransient(typeof(TService));
		}

		public static IServiceCollection AddTransient<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("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
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return services.AddTransient(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			return Add(services, serviceType, implementationType, ServiceLifetime.Scoped);
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("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
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			return services.AddScoped(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddScoped(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			return services.AddScoped(serviceType, serviceType);
		}

		public static IServiceCollection AddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			return services.AddScoped(typeof(TService));
		}

		public static IServiceCollection AddScoped<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("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
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return services.AddScoped(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			return Add(services, serviceType, implementationType, ServiceLifetime.Singleton);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("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
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			return services.AddSingleton(typeof(TService), typeof(TImplementation));
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type serviceType)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			return services.AddSingleton(serviceType, serviceType);
		}

		public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services) where TService : class
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			return services.AddSingleton(typeof(TService));
		}

		public static IServiceCollection AddSingleton<TService>(this IServiceCollection services, Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("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
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return services.AddSingleton(typeof(TService), implementationFactory);
		}

		public static IServiceCollection AddSingleton(this IServiceCollection services, Type serviceType, object implementationInstance)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationInstance == null)
			{
				throw new ArgumentNullException("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
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (implementationInstance == null)
			{
				throw new ArgumentNullException("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;
		}
	}
	[DebuggerDisplay("Lifetime = {Lifetime}, ServiceType = {ServiceType}, ImplementationType = {ImplementationType}")]
	public class ServiceDescriptor
	{
		public ServiceLifetime Lifetime { get; }

		public Type ServiceType { get; }

		[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)]
		public Type? ImplementationType { get; }

		public object? ImplementationInstance { get; }

		public Func<IServiceProvider, object>? ImplementationFactory { get; }

		public ServiceDescriptor(Type serviceType, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType, ServiceLifetime lifetime)
			: this(serviceType, lifetime)
		{
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			ImplementationType = implementationType;
		}

		public ServiceDescriptor(Type serviceType, object instance)
			: this(serviceType, ServiceLifetime.Singleton)
		{
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (instance == null)
			{
				throw new ArgumentNullException("instance");
			}
			ImplementationInstance = instance;
		}

		public ServiceDescriptor(Type serviceType, Func<IServiceProvider, object> factory, ServiceLifetime lifetime)
			: this(serviceType, lifetime)
		{
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (factory == null)
			{
				throw new ArgumentNullException("factory");
			}
			ImplementationFactory = factory;
		}

		private ServiceDescriptor(Type serviceType, ServiceLifetime lifetime)
		{
			Lifetime = lifetime;
			ServiceType = serviceType;
		}

		public override string ToString()
		{
			string text = $"{"ServiceType"}: {ServiceType} {"Lifetime"}: {Lifetime} ";
			if (ImplementationType != null)
			{
				return text + $"{"ImplementationType"}: {ImplementationType}";
			}
			if (ImplementationFactory != null)
			{
				return text + $"{"ImplementationFactory"}: {ImplementationFactory.Method}";
			}
			return text + $"{"ImplementationInstance"}: {ImplementationInstance}";
		}

		internal Type GetImplementationType()
		{
			if (ImplementationType != null)
			{
				return ImplementationType;
			}
			if (ImplementationInstance != null)
			{
				return ImplementationInstance.GetType();
			}
			if (ImplementationFactory != null)
			{
				Type[] genericTypeArguments = ImplementationFactory.GetType().GenericTypeArguments;
				return genericTypeArguments[1];
			}
			return null;
		}

		public static ServiceDescriptor Transient<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return Describe<TService, TImplementation>(ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			return Describe(service, implementationType, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Transient(Type service, Func<IServiceProvider, object> implementationFactory)
		{
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(service, implementationFactory, ServiceLifetime.Transient);
		}

		public static ServiceDescriptor Scoped<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return Describe<TService, TImplementation>(ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			return Describe(service, implementationType, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Scoped(Type service, Func<IServiceProvider, object> implementationFactory)
		{
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(service, implementationFactory, ServiceLifetime.Scoped);
		}

		public static ServiceDescriptor Singleton<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>() where TService : class where TImplementation : class, TService
		{
			return Describe<TService, TImplementation>(ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton(Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			return Describe(service, implementationType, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService, TImplementation>(Func<IServiceProvider, TImplementation> implementationFactory) where TService : class where TImplementation : class, TService
		{
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService>(Func<IServiceProvider, TService> implementationFactory) where TService : class
		{
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(typeof(TService), implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton(Type serviceType, Func<IServiceProvider, object> implementationFactory)
		{
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			return Describe(serviceType, implementationFactory, ServiceLifetime.Singleton);
		}

		public static ServiceDescriptor Singleton<TService>(TService implementationInstance) where TService : class
		{
			if (implementationInstance == null)
			{
				throw new ArgumentNullException("implementationInstance");
			}
			return Singleton(typeof(TService), implementationInstance);
		}

		public static ServiceDescriptor Singleton(Type serviceType, object implementationInstance)
		{
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (implementationInstance == null)
			{
				throw new ArgumentNullException("implementationInstance");
			}
			return new ServiceDescriptor(serviceType, implementationInstance);
		}

		private static ServiceDescriptor Describe<TService, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TImplementation>(ServiceLifetime lifetime) where TService : class where TImplementation : class, TService
		{
			return Describe(typeof(TService), 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 Describe(Type serviceType, Func<IServiceProvider, object> implementationFactory, ServiceLifetime lifetime)
		{
			return new ServiceDescriptor(serviceType, implementationFactory, lifetime);
		}
	}
	public enum ServiceLifetime
	{
		Singleton,
		Scoped,
		Transient
	}
	public static class ServiceProviderServiceExtensions
	{
		public static T? GetService<T>(this IServiceProvider provider)
		{
			if (provider == null)
			{
				throw new ArgumentNullException("provider");
			}
			return (T)provider.GetService(typeof(T));
		}

		public static object GetRequiredService(this IServiceProvider provider, Type serviceType)
		{
			if (provider == null)
			{
				throw new ArgumentNullException("provider");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			if (provider is ISupportRequiredService supportRequiredService)
			{
				return supportRequiredService.GetRequiredService(serviceType);
			}
			object service = provider.GetService(serviceType);
			if (service == null)
			{
				throw new InvalidOperationException(System.SR.Format(System.SR.NoServiceRegistered, serviceType));
			}
			return service;
		}

		public static T GetRequiredService<T>(this IServiceProvider provider) where T : notnull
		{
			if (provider == null)
			{
				throw new ArgumentNullException("provider");
			}
			return (T)provider.GetRequiredService(typeof(T));
		}

		public static IEnumerable<T> GetServices<T>(this IServiceProvider provider)
		{
			if (provider == null)
			{
				throw new ArgumentNullException("provider");
			}
			return provider.GetRequiredService<IEnumerable<T>>();
		}

		public static IEnumerable<object?> GetServices(this IServiceProvider provider, Type serviceType)
		{
			if (provider == null)
			{
				throw new ArgumentNullException("provider");
			}
			if (serviceType == null)
			{
				throw new ArgumentNullException("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)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (descriptor == null)
			{
				throw new ArgumentNullException("descriptor");
			}
			collection.Add(descriptor);
			return collection;
		}

		public static IServiceCollection Add(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (descriptors == null)
			{
				throw new ArgumentNullException("descriptors");
			}
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				collection.Add(descriptor);
			}
			return collection;
		}

		public static void TryAdd(this IServiceCollection collection, ServiceDescriptor descriptor)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (descriptor == null)
			{
				throw new ArgumentNullException("descriptor");
			}
			int count = collection.Count;
			for (int i = 0; i < count; i++)
			{
				if (collection[i].ServiceType == descriptor.ServiceType)
				{
					return;
				}
			}
			collection.Add(descriptor);
		}

		public static void TryAdd(this IServiceCollection collection, IEnumerable<ServiceDescriptor> descriptors)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (descriptors == null)
			{
				throw new ArgumentNullException("descriptors");
			}
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				collection.TryAdd(descriptor);
			}
		}

		public static void TryAddTransient(this IServiceCollection collection, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type service)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Transient(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddTransient<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			if (collection == null)
			{
				throw new ArgumentNullException("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
		{
			if (collection == null)
			{
				throw new ArgumentNullException("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)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Scoped(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddScoped<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			if (collection == null)
			{
				throw new ArgumentNullException("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
		{
			if (collection == null)
			{
				throw new ArgumentNullException("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)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, service);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton(this IServiceCollection collection, Type service, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type implementationType)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationType == null)
			{
				throw new ArgumentNullException("implementationType");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationType);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton(this IServiceCollection collection, Type service, Func<IServiceProvider, object> implementationFactory)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (service == null)
			{
				throw new ArgumentNullException("service");
			}
			if (implementationFactory == null)
			{
				throw new ArgumentNullException("implementationFactory");
			}
			ServiceDescriptor descriptor = ServiceDescriptor.Singleton(service, implementationFactory);
			collection.TryAdd(descriptor);
		}

		public static void TryAddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection collection) where TService : class
		{
			if (collection == null)
			{
				throw new ArgumentNullException("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
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			collection.TryAddSingleton(typeof(TService), typeof(TImplementation));
		}

		public static void TryAddSingleton<TService>(this IServiceCollection collection, TService instance) where TService : class
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (instance == null)
			{
				throw new ArgumentNullException("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)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (descriptor == null)
			{
				throw new ArgumentNullException("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)
				{
					return;
				}
			}
			services.Add(descriptor);
		}

		public static void TryAddEnumerable(this IServiceCollection services, IEnumerable<ServiceDescriptor> descriptors)
		{
			if (services == null)
			{
				throw new ArgumentNullException("services");
			}
			if (descriptors == null)
			{
				throw new ArgumentNullException("descriptors");
			}
			foreach (ServiceDescriptor descriptor in descriptors)
			{
				services.TryAddEnumerable(descriptor);
			}
		}

		public static IServiceCollection Replace(this IServiceCollection collection, ServiceDescriptor descriptor)
		{
			if (collection == null)
			{
				throw new ArgumentNullException("collection");
			}
			if (descriptor == null)
			{
				throw new ArgumentNullException("descriptor");
			}
			int count = collection.Count;
			for (int i = 0; i < count; i++)
			{
				if (collection[i].ServiceType == descriptor.ServiceType)
				{
					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(this IServiceCollection collection, Type serviceType)
		{
			if (serviceType == null)
			{
				throw new ArgumentNullException("serviceType");
			}
			for (int num = collection.Count - 1; num >= 0; num--)
			{
				ServiceDescriptor serviceDescriptor = collection[num];
				if (serviceDescriptor.ServiceType == serviceType)
				{
					collection.RemoveAt(num);
				}
			}
			return collection;
		}
	}
}

plugins/OnlineShenanigans/Newtonsoft.Json.dll

Decompiled 2 years ago
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.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Numerics;
using System.Reflection;
using System.Reflection.Emit;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Versioning;
using System.Security;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Linq.JsonPath;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AllowPartiallyTrustedCallers]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Schema, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f561df277c6c0b497d629032b410cdcf286e537c054724f7ffa0164345f62b3e642029d7a80cc351918955328c4adc8a048823ef90b0cf38ea7db0d729caf2b633c3babe08b0310198c1081995c19029bc675193744eab9d7345b8a67258ec17d112cebdbbb2a281487dceeafb9d83aa930f32103fbe1d2911425bc5744002c7")]
[assembly: InternalsVisibleTo("Newtonsoft.Json.Dynamic, PublicKey=0024000004800000940000000602000000240000525341310004000001000100cbd8d53b9d7de30f1f1278f636ec462cf9c254991291e66ebb157a885638a517887633b898ccbcf0d5c5ff7be85a6abe9e765d0ac7cd33c68dac67e7e64530e8222101109f154ab14a941c490ac155cd1d4fcba0fabb49016b4ef28593b015cab5937da31172f03f67d09edda404b88a60023f062ae71d0b2e4438b74cc11dc9")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("9ca358aa-317b-4925-8ada-4a29e943a363")]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Newtonsoft")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright © James Newton-King 2008")]
[assembly: AssemblyDescription("Json.NET is a popular high-performance JSON framework for .NET")]
[assembly: AssemblyFileVersion("13.0.3.27908")]
[assembly: AssemblyInformationalVersion("13.0.3+0a2e291c0d9c0c7675d445703e51750363a549ef")]
[assembly: AssemblyProduct("Json.NET")]
[assembly: AssemblyTitle("Json.NET .NET 6.0")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/JamesNK/Newtonsoft.Json")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion("13.0.0.0")]
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;
		}
	}
}
namespace Newtonsoft.Json
{
	public enum ConstructorHandling
	{
		Default,
		AllowNonPublicDefaultConstructor
	}
	public enum DateFormatHandling
	{
		IsoDateFormat,
		MicrosoftDateFormat
	}
	public enum DateParseHandling
	{
		None,
		DateTime,
		DateTimeOffset
	}
	public enum DateTimeZoneHandling
	{
		Local,
		Utc,
		Unspecified,
		RoundtripKind
	}
	public class DefaultJsonNameTable : JsonNameTable
	{
		private class Entry
		{
			internal readonly string Value;

			internal readonly int HashCode;

			internal Entry Next;

			internal Entry(string value, int hashCode, Entry next)
			{
				Value = value;
				HashCode = hashCode;
				Next = next;
			}
		}

		private static readonly int HashCodeRandomizer;

		private int _count;

		private Entry[] _entries;

		private int _mask = 31;

		static DefaultJsonNameTable()
		{
			HashCodeRandomizer = Environment.TickCount;
		}

		public DefaultJsonNameTable()
		{
			_entries = new Entry[_mask + 1];
		}

		public override string? Get(char[] key, int start, int length)
		{
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			num += (num << 7) ^ key[start];
			int num2 = start + length;
			for (int i = start + 1; i < num2; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			int num3 = Volatile.Read(ref _mask);
			int num4 = num & num3;
			for (Entry entry = _entries[num4]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && TextEquals(entry.Value, key, start, length))
				{
					return entry.Value;
				}
			}
			return null;
		}

		public string Add(string key)
		{
			if (key == null)
			{
				throw new ArgumentNullException("key");
			}
			int length = key.Length;
			if (length == 0)
			{
				return string.Empty;
			}
			int num = length + HashCodeRandomizer;
			for (int i = 0; i < key.Length; i++)
			{
				num += (num << 7) ^ key[i];
			}
			num -= num >> 17;
			num -= num >> 11;
			num -= num >> 5;
			for (Entry entry = _entries[num & _mask]; entry != null; entry = entry.Next)
			{
				if (entry.HashCode == num && entry.Value.Equals(key, StringComparison.Ordinal))
				{
					return entry.Value;
				}
			}
			return AddEntry(key, num);
		}

		private string AddEntry(string str, int hashCode)
		{
			int num = hashCode & _mask;
			Entry entry = new Entry(str, hashCode, _entries[num]);
			_entries[num] = entry;
			if (_count++ == _mask)
			{
				Grow();
			}
			return entry.Value;
		}

		private void Grow()
		{
			Entry[] entries = _entries;
			int num = _mask * 2 + 1;
			Entry[] array = new Entry[num + 1];
			for (int i = 0; i < entries.Length; i++)
			{
				Entry entry = entries[i];
				while (entry != null)
				{
					int num2 = entry.HashCode & num;
					Entry next = entry.Next;
					entry.Next = array[num2];
					array[num2] = entry;
					entry = next;
				}
			}
			_entries = array;
			Volatile.Write(ref _mask, num);
		}

		private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
		{
			if (str1.Length != str2Length)
			{
				return false;
			}
			for (int i = 0; i < str1.Length; i++)
			{
				if (str1[i] != str2[str2Start + i])
				{
					return false;
				}
			}
			return true;
		}
	}
	[Flags]
	public enum DefaultValueHandling
	{
		Include = 0,
		Ignore = 1,
		Populate = 2,
		IgnoreAndPopulate = 3
	}
	public enum FloatFormatHandling
	{
		String,
		Symbol,
		DefaultValue
	}
	public enum FloatParseHandling
	{
		Double,
		Decimal
	}
	public enum Formatting
	{
		None,
		Indented
	}
	public interface IArrayPool<T>
	{
		T[] Rent(int minimumLength);

		void Return(T[]? array);
	}
	public interface IJsonLineInfo
	{
		int LineNumber { get; }

		int LinePosition { get; }

		bool HasLineInfo();
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonArrayAttribute : JsonContainerAttribute
	{
		private bool _allowNullItems;

		public bool AllowNullItems
		{
			get
			{
				return _allowNullItems;
			}
			set
			{
				_allowNullItems = value;
			}
		}

		public JsonArrayAttribute()
		{
		}

		public JsonArrayAttribute(bool allowNullItems)
		{
			_allowNullItems = allowNullItems;
		}

		public JsonArrayAttribute(string id)
			: base(id)
		{
		}
	}
	[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)]
	public sealed class JsonConstructorAttribute : Attribute
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public abstract class JsonContainerAttribute : Attribute
	{
		internal bool? _isReference;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		private Type? _namingStrategyType;

		private object[]? _namingStrategyParameters;

		public string? Id { get; set; }

		public string? Title { get; set; }

		public string? Description { get; set; }

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType
		{
			get
			{
				return _namingStrategyType;
			}
			set
			{
				_namingStrategyType = value;
				NamingStrategyInstance = null;
			}
		}

		public object[]? NamingStrategyParameters
		{
			get
			{
				return _namingStrategyParameters;
			}
			set
			{
				_namingStrategyParameters = value;
				NamingStrategyInstance = null;
			}
		}

		internal NamingStrategy? NamingStrategyInstance { get; set; }

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		protected JsonContainerAttribute()
		{
		}

		protected JsonContainerAttribute(string id)
		{
			Id = id;
		}
	}
	public static class JsonConvert
	{
		public static readonly string True = "true";

		public static readonly string False = "false";

		public static readonly string Null = "null";

		public static readonly string Undefined = "undefined";

		public static readonly string PositiveInfinity = "Infinity";

		public static readonly string NegativeInfinity = "-Infinity";

		public static readonly string NaN = "NaN";

		public static Func<JsonSerializerSettings>? DefaultSettings { get; set; }

		public static string ToString(DateTime value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat, DateTimeZoneHandling.RoundtripKind);
		}

		public static string ToString(DateTime value, DateFormatHandling format, DateTimeZoneHandling timeZoneHandling)
		{
			DateTime value2 = DateTimeUtils.EnsureDateTime(value, timeZoneHandling);
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeString(stringWriter, value2, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(DateTimeOffset value)
		{
			return ToString(value, DateFormatHandling.IsoDateFormat);
		}

		public static string ToString(DateTimeOffset value, DateFormatHandling format)
		{
			using StringWriter stringWriter = StringUtils.CreateStringWriter(64);
			stringWriter.Write('"');
			DateTimeUtils.WriteDateTimeOffsetString(stringWriter, value, format, null, CultureInfo.InvariantCulture);
			stringWriter.Write('"');
			return stringWriter.ToString();
		}

		public static string ToString(bool value)
		{
			if (!value)
			{
				return False;
			}
			return True;
		}

		public static string ToString(char value)
		{
			return ToString(char.ToString(value));
		}

		public static string ToString(Enum value)
		{
			return value.ToString("D");
		}

		public static string ToString(int value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(short value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ushort value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(uint value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(long value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		private static string ToStringInternal(BigInteger value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(ulong value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(float value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(float value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureFloatFormat(double value, string text, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			if (floatFormatHandling == FloatFormatHandling.Symbol || (!double.IsInfinity(value) && !double.IsNaN(value)))
			{
				return text;
			}
			if (floatFormatHandling == FloatFormatHandling.DefaultValue)
			{
				if (nullable)
				{
					return Null;
				}
				return "0.0";
			}
			return quoteChar + text + quoteChar;
		}

		public static string ToString(double value)
		{
			return EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture));
		}

		internal static string ToString(double value, FloatFormatHandling floatFormatHandling, char quoteChar, bool nullable)
		{
			return EnsureFloatFormat(value, EnsureDecimalPlace(value, value.ToString("R", CultureInfo.InvariantCulture)), floatFormatHandling, quoteChar, nullable);
		}

		private static string EnsureDecimalPlace(double value, string text)
		{
			if (double.IsNaN(value) || double.IsInfinity(value) || StringUtils.IndexOf(text, '.') != -1 || StringUtils.IndexOf(text, 'E') != -1 || StringUtils.IndexOf(text, 'e') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		private static string EnsureDecimalPlace(string text)
		{
			if (StringUtils.IndexOf(text, '.') != -1)
			{
				return text;
			}
			return text + ".0";
		}

		public static string ToString(byte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		[CLSCompliant(false)]
		public static string ToString(sbyte value)
		{
			return value.ToString(null, CultureInfo.InvariantCulture);
		}

		public static string ToString(decimal value)
		{
			return EnsureDecimalPlace(value.ToString(null, CultureInfo.InvariantCulture));
		}

		public static string ToString(Guid value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(Guid value, char quoteChar)
		{
			string text = value.ToString("D", CultureInfo.InvariantCulture);
			string text2 = quoteChar.ToString(CultureInfo.InvariantCulture);
			return text2 + text + text2;
		}

		public static string ToString(TimeSpan value)
		{
			return ToString(value, '"');
		}

		internal static string ToString(TimeSpan value, char quoteChar)
		{
			return ToString(value.ToString(), quoteChar);
		}

		public static string ToString(Uri? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ToString(value, '"');
		}

		internal static string ToString(Uri value, char quoteChar)
		{
			return ToString(value.OriginalString, quoteChar);
		}

		public static string ToString(string? value)
		{
			return ToString(value, '"');
		}

		public static string ToString(string? value, char delimiter)
		{
			return ToString(value, delimiter, StringEscapeHandling.Default);
		}

		public static string ToString(string? value, char delimiter, StringEscapeHandling stringEscapeHandling)
		{
			if (delimiter != '"' && delimiter != '\'')
			{
				throw new ArgumentException("Delimiter must be a single or double quote.", "delimiter");
			}
			return JavaScriptUtils.ToEscapedJavaScriptString(value, delimiter, appendDelimiters: true, stringEscapeHandling);
		}

		public static string ToString(object? value)
		{
			if (value == null)
			{
				return Null;
			}
			return ConvertUtils.GetTypeCode(value.GetType()) switch
			{
				PrimitiveTypeCode.String => ToString((string)value), 
				PrimitiveTypeCode.Char => ToString((char)value), 
				PrimitiveTypeCode.Boolean => ToString((bool)value), 
				PrimitiveTypeCode.SByte => ToString((sbyte)value), 
				PrimitiveTypeCode.Int16 => ToString((short)value), 
				PrimitiveTypeCode.UInt16 => ToString((ushort)value), 
				PrimitiveTypeCode.Int32 => ToString((int)value), 
				PrimitiveTypeCode.Byte => ToString((byte)value), 
				PrimitiveTypeCode.UInt32 => ToString((uint)value), 
				PrimitiveTypeCode.Int64 => ToString((long)value), 
				PrimitiveTypeCode.UInt64 => ToString((ulong)value), 
				PrimitiveTypeCode.Single => ToString((float)value), 
				PrimitiveTypeCode.Double => ToString((double)value), 
				PrimitiveTypeCode.DateTime => ToString((DateTime)value), 
				PrimitiveTypeCode.Decimal => ToString((decimal)value), 
				PrimitiveTypeCode.DBNull => Null, 
				PrimitiveTypeCode.DateTimeOffset => ToString((DateTimeOffset)value), 
				PrimitiveTypeCode.Guid => ToString((Guid)value), 
				PrimitiveTypeCode.Uri => ToString((Uri)value), 
				PrimitiveTypeCode.TimeSpan => ToString((TimeSpan)value), 
				PrimitiveTypeCode.BigInteger => ToStringInternal((BigInteger)value), 
				_ => throw new ArgumentException("Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType())), 
			};
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value)
		{
			return SerializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting)
		{
			return SerializeObject(value, formatting, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings)
		{
			return SerializeObject(value, null, formatting, settings);
		}

		[DebuggerStepThrough]
		public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			jsonSerializer.Formatting = formatting;
			return SerializeObjectInternal(value, type, jsonSerializer);
		}

		private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer)
		{
			StringWriter stringWriter = new StringWriter(new StringBuilder(256), CultureInfo.InvariantCulture);
			using (JsonTextWriter jsonTextWriter = new JsonTextWriter(stringWriter))
			{
				jsonTextWriter.Formatting = jsonSerializer.Formatting;
				jsonSerializer.Serialize(jsonTextWriter, value, type);
			}
			return stringWriter.ToString();
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value)
		{
			return DeserializeObject(value, (Type?)null, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, JsonSerializerSettings settings)
		{
			return DeserializeObject(value, null, settings);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, Type type)
		{
			return DeserializeObject(value, type, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value)
		{
			return JsonConvert.DeserializeObject<T>(value, (JsonSerializerSettings?)null);
		}

		[DebuggerStepThrough]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject)
		{
			return DeserializeObject<T>(value);
		}

		[DebuggerStepThrough]
		public static T? DeserializeAnonymousType<T>(string value, T anonymousTypeObject, JsonSerializerSettings settings)
		{
			return DeserializeObject<T>(value, settings);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value, params JsonConverter[] converters)
		{
			return (T)DeserializeObject(value, typeof(T), converters);
		}

		[DebuggerStepThrough]
		public static T? DeserializeObject<T>(string value, JsonSerializerSettings? settings)
		{
			return (T)DeserializeObject(value, typeof(T), settings);
		}

		[DebuggerStepThrough]
		public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters)
		{
			JsonSerializerSettings settings = ((converters != null && converters.Length != 0) ? new JsonSerializerSettings
			{
				Converters = converters
			} : null);
			return DeserializeObject(value, type, settings);
		}

		public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings)
		{
			ValidationUtils.ArgumentNotNull(value, "value");
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			if (!jsonSerializer.IsCheckAdditionalContentSet())
			{
				jsonSerializer.CheckAdditionalContent = true;
			}
			using JsonTextReader reader = new JsonTextReader(new StringReader(value));
			return jsonSerializer.Deserialize(reader, type);
		}

		[DebuggerStepThrough]
		public static void PopulateObject(string value, object target)
		{
			PopulateObject(value, target, null);
		}

		public static void PopulateObject(string value, object target, JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings);
			using JsonReader jsonReader = new JsonTextReader(new StringReader(value));
			jsonSerializer.Populate(jsonReader, target);
			if (settings == null || !settings.CheckAdditionalContent)
			{
				return;
			}
			while (jsonReader.Read())
			{
				if (jsonReader.TokenType != JsonToken.Comment)
				{
					throw JsonSerializationException.Create(jsonReader, "Additional text found in JSON string after finishing deserializing object.");
				}
			}
		}

		public static string SerializeXmlNode(XmlNode? node)
		{
			return SerializeXmlNode(node, Formatting.None);
		}

		public static string SerializeXmlNode(XmlNode? node, Formatting formatting)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static XmlDocument? DeserializeXmlNode(string value)
		{
			return DeserializeXmlNode(value, null);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XmlDocument)DeserializeObject(value, typeof(XmlDocument), xmlNodeConverter);
		}

		public static string SerializeXNode(XObject? node)
		{
			return SerializeXNode(node, Formatting.None);
		}

		public static string SerializeXNode(XObject? node, Formatting formatting)
		{
			return SerializeXNode(node, formatting, omitRootObject: false);
		}

		public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter
			{
				OmitRootObject = omitRootObject
			};
			return SerializeObject(node, formatting, xmlNodeConverter);
		}

		public static XDocument? DeserializeXNode(string value)
		{
			return DeserializeXNode(value, null);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute: false);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute)
		{
			return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, encodeSpecialCharacters: false);
		}

		public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters)
		{
			XmlNodeConverter xmlNodeConverter = new XmlNodeConverter();
			xmlNodeConverter.DeserializeRootElementName = deserializeRootElementName;
			xmlNodeConverter.WriteArrayAttribute = writeArrayAttribute;
			xmlNodeConverter.EncodeSpecialCharacters = encodeSpecialCharacters;
			return (XDocument)DeserializeObject(value, typeof(XDocument), xmlNodeConverter);
		}
	}
	public abstract class JsonConverter
	{
		public virtual bool CanRead => true;

		public virtual bool CanWrite => true;

		public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer);

		public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer);

		public abstract bool CanConvert(Type objectType);
	}
	public abstract class JsonConverter<T> : JsonConverter
	{
		public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
		{
			if (!((value != null) ? (value is T) : ReflectionUtils.IsNullable(typeof(T))))
			{
				throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			WriteJson(writer, (T)value, serializer);
		}

		public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer);

		public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
		{
			bool flag = existingValue == null;
			if (!flag && !(existingValue is T))
			{
				throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
			}
			return ReadJson(reader, objectType, flag ? default(T) : ((T)existingValue), !flag, serializer);
		}

		public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer);

		public sealed override bool CanConvert(Type objectType)
		{
			return typeof(T).IsAssignableFrom(objectType);
		}
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonConverterAttribute : Attribute
	{
		private readonly Type _converterType;

		public Type ConverterType => _converterType;

		public object[]? ConverterParameters { get; }

		public JsonConverterAttribute(Type converterType)
		{
			if (converterType == null)
			{
				throw new ArgumentNullException("converterType");
			}
			_converterType = converterType;
		}

		public JsonConverterAttribute(Type converterType, params object[] converterParameters)
			: this(converterType)
		{
			ConverterParameters = converterParameters;
		}
	}
	public class JsonConverterCollection : Collection<JsonConverter>
	{
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonDictionaryAttribute : JsonContainerAttribute
	{
		public JsonDictionaryAttribute()
		{
		}

		public JsonDictionaryAttribute(string id)
			: base(id)
		{
		}
	}
	[Serializable]
	public class JsonException : Exception
	{
		public JsonException()
		{
		}

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

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

		public JsonException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			return new JsonException(message);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public class JsonExtensionDataAttribute : Attribute
	{
		public bool WriteData { get; set; }

		public bool ReadData { get; set; }

		public JsonExtensionDataAttribute()
		{
			WriteData = true;
			ReadData = true;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonIgnoreAttribute : Attribute
	{
	}
	public abstract class JsonNameTable
	{
		public abstract string? Get(char[] key, int start, int length);
	}
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
	public sealed class JsonObjectAttribute : JsonContainerAttribute
	{
		private MemberSerialization _memberSerialization;

		internal MissingMemberHandling? _missingMemberHandling;

		internal Required? _itemRequired;

		internal NullValueHandling? _itemNullValueHandling;

		public MemberSerialization MemberSerialization
		{
			get
			{
				return _memberSerialization;
			}
			set
			{
				_memberSerialization = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public NullValueHandling ItemNullValueHandling
		{
			get
			{
				return _itemNullValueHandling.GetValueOrDefault();
			}
			set
			{
				_itemNullValueHandling = value;
			}
		}

		public Required ItemRequired
		{
			get
			{
				return _itemRequired.GetValueOrDefault();
			}
			set
			{
				_itemRequired = value;
			}
		}

		public JsonObjectAttribute()
		{
		}

		public JsonObjectAttribute(MemberSerialization memberSerialization)
		{
			MemberSerialization = memberSerialization;
		}

		public JsonObjectAttribute(string id)
			: base(id)
		{
		}
	}
	internal enum JsonContainerType
	{
		None,
		Object,
		Array,
		Constructor
	}
	internal struct JsonPosition
	{
		private static readonly char[] SpecialCharacters = new char[18]
		{
			'.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t',
			'\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029'
		};

		internal JsonContainerType Type;

		internal int Position;

		internal string? PropertyName;

		internal bool HasIndex;

		public JsonPosition(JsonContainerType type)
		{
			Type = type;
			HasIndex = TypeHasIndex(type);
			Position = -1;
			PropertyName = null;
		}

		internal int CalculateLength()
		{
			switch (Type)
			{
			case JsonContainerType.Object:
				return PropertyName.Length + 5;
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				return MathUtils.IntLength((ulong)Position) + 2;
			default:
				throw new ArgumentOutOfRangeException("Type");
			}
		}

		internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer)
		{
			switch (Type)
			{
			case JsonContainerType.Object:
			{
				string propertyName = PropertyName;
				if (propertyName.IndexOfAny(SpecialCharacters) != -1)
				{
					sb.Append("['");
					if (writer == null)
					{
						writer = new StringWriter(sb);
					}
					JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', appendDelimiters: false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
					sb.Append("']");
				}
				else
				{
					if (sb.Length > 0)
					{
						sb.Append('.');
					}
					sb.Append(propertyName);
				}
				break;
			}
			case JsonContainerType.Array:
			case JsonContainerType.Constructor:
				sb.Append('[');
				sb.Append(Position);
				sb.Append(']');
				break;
			}
		}

		internal static bool TypeHasIndex(JsonContainerType type)
		{
			if (type != JsonContainerType.Array)
			{
				return type == JsonContainerType.Constructor;
			}
			return true;
		}

		internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition)
		{
			int num = 0;
			if (positions != null)
			{
				for (int i = 0; i < positions.Count; i++)
				{
					num += positions[i].CalculateLength();
				}
			}
			if (currentPosition.HasValue)
			{
				num += currentPosition.GetValueOrDefault().CalculateLength();
			}
			StringBuilder stringBuilder = new StringBuilder(num);
			StringWriter writer = null;
			char[] buffer = null;
			if (positions != null)
			{
				foreach (JsonPosition position in positions)
				{
					position.WriteTo(stringBuilder, ref writer, ref buffer);
				}
			}
			currentPosition?.WriteTo(stringBuilder, ref writer, ref buffer);
			return stringBuilder.ToString();
		}

		internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message)
		{
			if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
			{
				message = message.Trim();
				if (!message.EndsWith('.'))
				{
					message += ".";
				}
				message += " ";
			}
			message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
			}
			message += ".";
			return message;
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
	public sealed class JsonPropertyAttribute : Attribute
	{
		internal NullValueHandling? _nullValueHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal bool? _isReference;

		internal int? _order;

		internal Required? _required;

		internal bool? _itemIsReference;

		internal ReferenceLoopHandling? _itemReferenceLoopHandling;

		internal TypeNameHandling? _itemTypeNameHandling;

		public Type? ItemConverterType { get; set; }

		public object[]? ItemConverterParameters { get; set; }

		public Type? NamingStrategyType { get; set; }

		public object[]? NamingStrategyParameters { get; set; }

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public bool IsReference
		{
			get
			{
				return _isReference.GetValueOrDefault();
			}
			set
			{
				_isReference = value;
			}
		}

		public int Order
		{
			get
			{
				return _order.GetValueOrDefault();
			}
			set
			{
				_order = value;
			}
		}

		public Required Required
		{
			get
			{
				return _required.GetValueOrDefault();
			}
			set
			{
				_required = value;
			}
		}

		public string? PropertyName { get; set; }

		public ReferenceLoopHandling ItemReferenceLoopHandling
		{
			get
			{
				return _itemReferenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_itemReferenceLoopHandling = value;
			}
		}

		public TypeNameHandling ItemTypeNameHandling
		{
			get
			{
				return _itemTypeNameHandling.GetValueOrDefault();
			}
			set
			{
				_itemTypeNameHandling = value;
			}
		}

		public bool ItemIsReference
		{
			get
			{
				return _itemIsReference.GetValueOrDefault();
			}
			set
			{
				_itemIsReference = value;
			}
		}

		public JsonPropertyAttribute()
		{
		}

		public JsonPropertyAttribute(string propertyName)
		{
			PropertyName = propertyName;
		}
	}
	public abstract class JsonReader : IAsyncDisposable, IDisposable
	{
		protected internal enum State
		{
			Start,
			Complete,
			Property,
			ObjectStart,
			Object,
			ArrayStart,
			Array,
			Closed,
			PostValue,
			ConstructorStart,
			Constructor,
			Error,
			Finished
		}

		private JsonToken _tokenType;

		private object? _value;

		internal char _quoteChar;

		internal State _currentState;

		private JsonPosition _currentPosition;

		private CultureInfo? _culture;

		private DateTimeZoneHandling _dateTimeZoneHandling;

		private int? _maxDepth;

		private bool _hasExceededMaxDepth;

		internal DateParseHandling _dateParseHandling;

		internal FloatParseHandling _floatParseHandling;

		private string? _dateFormatString;

		private List<JsonPosition>? _stack;

		protected State CurrentState => _currentState;

		public bool CloseInput { get; set; }

		public bool SupportMultipleContent { get; set; }

		public virtual char QuoteChar
		{
			get
			{
				return _quoteChar;
			}
			protected internal set
			{
				_quoteChar = value;
			}
		}

		public DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling;
			}
			set
			{
				if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateTimeZoneHandling = value;
			}
		}

		public DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling;
			}
			set
			{
				if (value < DateParseHandling.None || value > DateParseHandling.DateTimeOffset)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_dateParseHandling = value;
			}
		}

		public FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling;
			}
			set
			{
				if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_floatParseHandling = value;
			}
		}

		public string? DateFormatString
		{
			get
			{
				return _dateFormatString;
			}
			set
			{
				_dateFormatString = value;
			}
		}

		public int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
			}
		}

		public virtual JsonToken TokenType => _tokenType;

		public virtual object? Value => _value;

		public virtual Type? ValueType => _value?.GetType();

		public virtual int Depth
		{
			get
			{
				int num = _stack?.Count ?? 0;
				if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
				{
					return num;
				}
				return num + 1;
			}
		}

		public virtual string Path
		{
			get
			{
				if (_currentPosition.Type == JsonContainerType.None)
				{
					return string.Empty;
				}
				JsonPosition? currentPosition = ((_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart) ? new JsonPosition?(_currentPosition) : null);
				return JsonPosition.BuildPath(_stack, currentPosition);
			}
		}

		public CultureInfo Culture
		{
			get
			{
				return _culture ?? CultureInfo.InvariantCulture;
			}
			set
			{
				_culture = value;
			}
		}

		ValueTask IAsyncDisposable.DisposeAsync()
		{
			try
			{
				Dispose(disposing: true);
				return default(ValueTask);
			}
			catch (Exception exception)
			{
				return ValueTask.FromException(exception);
			}
		}

		public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync();
		}

		public async Task SkipAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			if (TokenType == JsonToken.PropertyName)
			{
				await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) && depth < Depth)
				{
				}
			}
		}

		internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken)
		{
			if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
			{
				throw CreateUnexpectedEndException();
			}
		}

		public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean());
		}

		public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<byte[]>() ?? Task.FromResult(ReadAsBytes());
		}

		internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
		{
			List<byte> buffer = new List<byte>();
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(buffer));
			byte[] array = buffer.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime());
		}

		public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset());
		}

		public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal());
		}

		public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return Task.FromResult(ReadAsDouble());
		}

		public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32());
		}

		public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
		{
			return cancellationToken.CancelIfRequestedAsync<string>() ?? Task.FromResult(ReadAsString());
		}

		internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken)
		{
			bool flag = await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			if (flag)
			{
				flag = await MoveToContentAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}
			return flag;
		}

		internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType = TokenType;
			if (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				return MoveToContentFromNonContentAsync(cancellationToken);
			}
			return AsyncUtils.True;
		}

		private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken)
		{
			JsonToken tokenType;
			do
			{
				if (!(await ReadAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
				{
					return false;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment);
			return true;
		}

		internal JsonPosition GetPosition(int depth)
		{
			if (_stack != null && depth < _stack.Count)
			{
				return _stack[depth];
			}
			return _currentPosition;
		}

		protected JsonReader()
		{
			_currentState = State.Start;
			_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
			_dateParseHandling = DateParseHandling.DateTime;
			_floatParseHandling = FloatParseHandling.Double;
			_maxDepth = 64;
			CloseInput = true;
		}

		private void Push(JsonContainerType value)
		{
			UpdateScopeWithFinishedValue();
			if (_currentPosition.Type == JsonContainerType.None)
			{
				_currentPosition = new JsonPosition(value);
				return;
			}
			if (_stack == null)
			{
				_stack = new List<JsonPosition>();
			}
			_stack.Add(_currentPosition);
			_currentPosition = new JsonPosition(value);
			if (!_maxDepth.HasValue || !(Depth + 1 > _maxDepth) || _hasExceededMaxDepth)
			{
				return;
			}
			_hasExceededMaxDepth = true;
			throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
		}

		private JsonContainerType Pop()
		{
			JsonPosition currentPosition;
			if (_stack != null && _stack.Count > 0)
			{
				currentPosition = _currentPosition;
				_currentPosition = _stack[_stack.Count - 1];
				_stack.RemoveAt(_stack.Count - 1);
			}
			else
			{
				currentPosition = _currentPosition;
				_currentPosition = default(JsonPosition);
			}
			if (_maxDepth.HasValue && Depth <= _maxDepth)
			{
				_hasExceededMaxDepth = false;
			}
			return currentPosition.Type;
		}

		private JsonContainerType Peek()
		{
			return _currentPosition.Type;
		}

		public abstract bool Read();

		public virtual int? ReadAsInt32()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is int)
				{
					return (int)value;
				}
				int num;
				if (value is BigInteger bigInteger)
				{
					num = (int)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToInt32(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Integer, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadInt32String(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal int? ReadInt32String(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (int.TryParse(s, NumberStyles.Integer, Culture, out var result))
			{
				SetToken(JsonToken.Integer, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual string? ReadAsString()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.String:
				return (string)Value;
			default:
				if (JsonTokenUtils.IsPrimitiveToken(contentToken))
				{
					object value = Value;
					if (value != null)
					{
						string text = ((!(value is IFormattable formattable)) ? ((value is Uri uri) ? uri.OriginalString : value.ToString()) : formattable.ToString(null, Culture));
						SetToken(JsonToken.String, text, updateIndex: false);
						return text;
					}
				}
				throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		public virtual byte[]? ReadAsBytes()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.StartObject:
			{
				ReadIntoWrappedTypeObject();
				byte[] array2 = ReadAsBytes();
				ReaderReadAndAssert();
				if (TokenType != JsonToken.EndObject)
				{
					throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
				}
				SetToken(JsonToken.Bytes, array2, updateIndex: false);
				return array2;
			}
			case JsonToken.String:
			{
				string text = (string)Value;
				Guid g;
				byte[] array3 = ((text.Length == 0) ? CollectionUtils.ArrayEmpty<byte>() : ((!ConvertUtils.TryConvertGuid(text, out g)) ? Convert.FromBase64String(text) : g.ToByteArray()));
				SetToken(JsonToken.Bytes, array3, updateIndex: false);
				return array3;
			}
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Bytes:
				if (Value is Guid guid)
				{
					byte[] array = guid.ToByteArray();
					SetToken(JsonToken.Bytes, array, updateIndex: false);
					return array;
				}
				return (byte[])Value;
			case JsonToken.StartArray:
				return ReadArrayIntoByteArray();
			default:
				throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal byte[] ReadArrayIntoByteArray()
		{
			List<byte> list = new List<byte>();
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
				}
			}
			while (!ReadArrayElementIntoByteArrayReportDone(list));
			byte[] array = list.ToArray();
			SetToken(JsonToken.Bytes, array, updateIndex: false);
			return array;
		}

		private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
		{
			switch (TokenType)
			{
			case JsonToken.None:
				throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
			case JsonToken.Integer:
				buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
				return false;
			case JsonToken.EndArray:
				return true;
			case JsonToken.Comment:
				return false;
			default:
				throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		public virtual double? ReadAsDouble()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is double)
				{
					return (double)value;
				}
				double num = ((!(value is BigInteger bigInteger)) ? Convert.ToDouble(value, CultureInfo.InvariantCulture) : ((double)bigInteger));
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDoubleString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal double? ReadDoubleString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual bool? ReadAsBoolean()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				bool flag = ((!(Value is BigInteger bigInteger)) ? Convert.ToBoolean(Value, CultureInfo.InvariantCulture) : (bigInteger != 0L));
				SetToken(JsonToken.Boolean, flag, updateIndex: false);
				return flag;
			}
			case JsonToken.String:
				return ReadBooleanString((string)Value);
			case JsonToken.Boolean:
				return (bool)Value;
			default:
				throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal bool? ReadBooleanString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (bool.TryParse(s, out var result))
			{
				SetToken(JsonToken.Boolean, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual decimal? ReadAsDecimal()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Integer:
			case JsonToken.Float:
			{
				object value = Value;
				if (value is decimal)
				{
					return (decimal)value;
				}
				decimal num;
				if (value is BigInteger bigInteger)
				{
					num = (decimal)bigInteger;
				}
				else
				{
					try
					{
						num = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
					}
					catch (Exception ex)
					{
						throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, value), ex);
					}
				}
				SetToken(JsonToken.Float, num, updateIndex: false);
				return num;
			}
			case JsonToken.String:
				return ReadDecimalString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal decimal? ReadDecimalString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (decimal.TryParse(s, NumberStyles.Number, Culture, out var result))
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out result) == ParseResult.Success)
			{
				SetToken(JsonToken.Float, result, updateIndex: false);
				return result;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTime? ReadAsDateTime()
		{
			switch (GetContentToken())
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTimeOffset dateTimeOffset)
				{
					SetToken(JsonToken.Date, dateTimeOffset.DateTime, updateIndex: false);
				}
				return (DateTime)Value;
			case JsonToken.String:
				return ReadDateTimeString((string)Value);
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
			}
		}

		internal DateTime? ReadDateTimeString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out var dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		public virtual DateTimeOffset? ReadAsDateTimeOffset()
		{
			JsonToken contentToken = GetContentToken();
			switch (contentToken)
			{
			case JsonToken.None:
			case JsonToken.Null:
			case JsonToken.EndArray:
				return null;
			case JsonToken.Date:
				if (Value is DateTime dateTime)
				{
					SetToken(JsonToken.Date, new DateTimeOffset(dateTime), updateIndex: false);
				}
				return (DateTimeOffset)Value;
			case JsonToken.String:
			{
				string s = (string)Value;
				return ReadDateTimeOffsetString(s);
			}
			default:
				throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, contentToken));
			}
		}

		internal DateTimeOffset? ReadDateTimeOffsetString(string? s)
		{
			if (StringUtils.IsNullOrEmpty(s))
			{
				SetToken(JsonToken.Null, null, updateIndex: false);
				return null;
			}
			if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out var dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
			{
				SetToken(JsonToken.Date, dt, updateIndex: false);
				return dt;
			}
			SetToken(JsonToken.String, s, updateIndex: false);
			throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
		}

		internal void ReaderReadAndAssert()
		{
			if (!Read())
			{
				throw CreateUnexpectedEndException();
			}
		}

		internal JsonReaderException CreateUnexpectedEndException()
		{
			return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
		}

		internal void ReadIntoWrappedTypeObject()
		{
			ReaderReadAndAssert();
			if (Value != null && Value.ToString() == "$type")
			{
				ReaderReadAndAssert();
				if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
				{
					ReaderReadAndAssert();
					if (Value.ToString() == "$value")
					{
						return;
					}
				}
			}
			throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
		}

		public void Skip()
		{
			if (TokenType == JsonToken.PropertyName)
			{
				Read();
			}
			if (JsonTokenUtils.IsStartToken(TokenType))
			{
				int depth = Depth;
				while (Read() && depth < Depth)
				{
				}
			}
		}

		protected void SetToken(JsonToken newToken)
		{
			SetToken(newToken, null, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value)
		{
			SetToken(newToken, value, updateIndex: true);
		}

		protected void SetToken(JsonToken newToken, object? value, bool updateIndex)
		{
			_tokenType = newToken;
			_value = value;
			switch (newToken)
			{
			case JsonToken.StartObject:
				_currentState = State.ObjectStart;
				Push(JsonContainerType.Object);
				break;
			case JsonToken.StartArray:
				_currentState = State.ArrayStart;
				Push(JsonContainerType.Array);
				break;
			case JsonToken.StartConstructor:
				_currentState = State.ConstructorStart;
				Push(JsonContainerType.Constructor);
				break;
			case JsonToken.EndObject:
				ValidateEnd(JsonToken.EndObject);
				break;
			case JsonToken.EndArray:
				ValidateEnd(JsonToken.EndArray);
				break;
			case JsonToken.EndConstructor:
				ValidateEnd(JsonToken.EndConstructor);
				break;
			case JsonToken.PropertyName:
				_currentState = State.Property;
				_currentPosition.PropertyName = (string)value;
				break;
			case JsonToken.Raw:
			case JsonToken.Integer:
			case JsonToken.Float:
			case JsonToken.String:
			case JsonToken.Boolean:
			case JsonToken.Null:
			case JsonToken.Undefined:
			case JsonToken.Date:
			case JsonToken.Bytes:
				SetPostValueState(updateIndex);
				break;
			case JsonToken.Comment:
				break;
			}
		}

		internal void SetPostValueState(bool updateIndex)
		{
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
			if (updateIndex)
			{
				UpdateScopeWithFinishedValue();
			}
		}

		private void UpdateScopeWithFinishedValue()
		{
			if (_currentPosition.HasIndex)
			{
				_currentPosition.Position++;
			}
		}

		private void ValidateEnd(JsonToken endToken)
		{
			JsonContainerType jsonContainerType = Pop();
			if (GetTypeForCloseToken(endToken) != jsonContainerType)
			{
				throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, jsonContainerType));
			}
			if (Peek() != 0 || SupportMultipleContent)
			{
				_currentState = State.PostValue;
			}
			else
			{
				SetFinished();
			}
		}

		protected void SetStateBasedOnCurrent()
		{
			JsonContainerType jsonContainerType = Peek();
			switch (jsonContainerType)
			{
			case JsonContainerType.Object:
				_currentState = State.Object;
				break;
			case JsonContainerType.Array:
				_currentState = State.Array;
				break;
			case JsonContainerType.Constructor:
				_currentState = State.Constructor;
				break;
			case JsonContainerType.None:
				SetFinished();
				break;
			default:
				throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, jsonContainerType));
			}
		}

		private void SetFinished()
		{
			_currentState = ((!SupportMultipleContent) ? State.Finished : State.Start);
		}

		private JsonContainerType GetTypeForCloseToken(JsonToken token)
		{
			return token switch
			{
				JsonToken.EndObject => JsonContainerType.Object, 
				JsonToken.EndArray => JsonContainerType.Array, 
				JsonToken.EndConstructor => JsonContainerType.Constructor, 
				_ => throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)), 
			};
		}

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

		protected virtual void Dispose(bool disposing)
		{
			if (_currentState != State.Closed && disposing)
			{
				Close();
			}
		}

		public virtual void Close()
		{
			_currentState = State.Closed;
			_tokenType = JsonToken.None;
			_value = null;
		}

		internal void ReadAndAssert()
		{
			if (!Read())
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal void ReadForTypeAndAssert(JsonContract? contract, bool hasConverter)
		{
			if (!ReadForType(contract, hasConverter))
			{
				throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
			}
		}

		internal bool ReadForType(JsonContract? contract, bool hasConverter)
		{
			if (hasConverter)
			{
				return Read();
			}
			switch (contract?.InternalReadType ?? ReadType.Read)
			{
			case ReadType.Read:
				return ReadAndMoveToContent();
			case ReadType.ReadAsInt32:
				ReadAsInt32();
				break;
			case ReadType.ReadAsInt64:
			{
				bool result = ReadAndMoveToContent();
				if (TokenType == JsonToken.Undefined)
				{
					throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
				}
				return result;
			}
			case ReadType.ReadAsDecimal:
				ReadAsDecimal();
				break;
			case ReadType.ReadAsDouble:
				ReadAsDouble();
				break;
			case ReadType.ReadAsBytes:
				ReadAsBytes();
				break;
			case ReadType.ReadAsBoolean:
				ReadAsBoolean();
				break;
			case ReadType.ReadAsString:
				ReadAsString();
				break;
			case ReadType.ReadAsDateTime:
				ReadAsDateTime();
				break;
			case ReadType.ReadAsDateTimeOffset:
				ReadAsDateTimeOffset();
				break;
			default:
				throw new ArgumentOutOfRangeException();
			}
			return TokenType != JsonToken.None;
		}

		internal bool ReadAndMoveToContent()
		{
			if (Read())
			{
				return MoveToContent();
			}
			return false;
		}

		internal bool MoveToContent()
		{
			JsonToken tokenType = TokenType;
			while (tokenType == JsonToken.None || tokenType == JsonToken.Comment)
			{
				if (!Read())
				{
					return false;
				}
				tokenType = TokenType;
			}
			return true;
		}

		private JsonToken GetContentToken()
		{
			JsonToken tokenType;
			do
			{
				if (!Read())
				{
					SetToken(JsonToken.None);
					return JsonToken.None;
				}
				tokenType = TokenType;
			}
			while (tokenType == JsonToken.Comment);
			return tokenType;
		}
	}
	[Serializable]
	public class JsonReaderException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonReaderException()
		{
		}

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

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

		public JsonReaderException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonReaderException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonReaderException(message, path, lineNumber, linePosition, ex);
		}
	}
	[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
	public sealed class JsonRequiredAttribute : Attribute
	{
	}
	[Serializable]
	public class JsonSerializationException : JsonException
	{
		public int LineNumber { get; }

		public int LinePosition { get; }

		public string? Path { get; }

		public JsonSerializationException()
		{
		}

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

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

		public JsonSerializationException(SerializationInfo info, StreamingContext context)
			: base(info, context)
		{
		}

		public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
			: base(message, innerException)
		{
			Path = path;
			LineNumber = lineNumber;
			LinePosition = linePosition;
		}

		internal static JsonSerializationException Create(JsonReader reader, string message)
		{
			return Create(reader, message, null);
		}

		internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex)
		{
			return Create(reader as IJsonLineInfo, reader.Path, message, ex);
		}

		internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
		{
			message = JsonPosition.FormatMessage(lineInfo, path, message);
			int lineNumber;
			int linePosition;
			if (lineInfo != null && lineInfo.HasLineInfo())
			{
				lineNumber = lineInfo.LineNumber;
				linePosition = lineInfo.LinePosition;
			}
			else
			{
				lineNumber = 0;
				linePosition = 0;
			}
			return new JsonSerializationException(message, path, lineNumber, linePosition, ex);
		}
	}
	public class JsonSerializer
	{
		internal TypeNameHandling _typeNameHandling;

		internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling;

		internal PreserveReferencesHandling _preserveReferencesHandling;

		internal ReferenceLoopHandling _referenceLoopHandling;

		internal MissingMemberHandling _missingMemberHandling;

		internal ObjectCreationHandling _objectCreationHandling;

		internal NullValueHandling _nullValueHandling;

		internal DefaultValueHandling _defaultValueHandling;

		internal ConstructorHandling _constructorHandling;

		internal MetadataPropertyHandling _metadataPropertyHandling;

		internal JsonConverterCollection? _converters;

		internal IContractResolver _contractResolver;

		internal ITraceWriter? _traceWriter;

		internal IEqualityComparer? _equalityComparer;

		internal ISerializationBinder _serializationBinder;

		internal StreamingContext _context;

		private IReferenceResolver? _referenceResolver;

		private Formatting? _formatting;

		private DateFormatHandling? _dateFormatHandling;

		private DateTimeZoneHandling? _dateTimeZoneHandling;

		private DateParseHandling? _dateParseHandling;

		private FloatFormatHandling? _floatFormatHandling;

		private FloatParseHandling? _floatParseHandling;

		private StringEscapeHandling? _stringEscapeHandling;

		private CultureInfo _culture;

		private int? _maxDepth;

		private bool _maxDepthSet;

		private bool? _checkAdditionalContent;

		private string? _dateFormatString;

		private bool _dateFormatStringSet;

		public virtual IReferenceResolver? ReferenceResolver
		{
			get
			{
				return GetReferenceResolver();
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Reference resolver cannot be null.");
				}
				_referenceResolver = value;
			}
		}

		[Obsolete("Binder is obsolete. Use SerializationBinder instead.")]
		public virtual SerializationBinder Binder
		{
			get
			{
				if (_serializationBinder is SerializationBinder result)
				{
					return result;
				}
				if (_serializationBinder is SerializationBinderAdapter serializationBinderAdapter)
				{
					return serializationBinderAdapter.SerializationBinder;
				}
				throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set.");
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = (value as ISerializationBinder) ?? new SerializationBinderAdapter(value);
			}
		}

		public virtual ISerializationBinder SerializationBinder
		{
			get
			{
				return _serializationBinder;
			}
			set
			{
				if (value == null)
				{
					throw new ArgumentNullException("value", "Serialization binder cannot be null.");
				}
				_serializationBinder = value;
			}
		}

		public virtual ITraceWriter? TraceWriter
		{
			get
			{
				return _traceWriter;
			}
			set
			{
				_traceWriter = value;
			}
		}

		public virtual IEqualityComparer? EqualityComparer
		{
			get
			{
				return _equalityComparer;
			}
			set
			{
				_equalityComparer = value;
			}
		}

		public virtual TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling;
			}
			set
			{
				if (value < TypeNameHandling.None || value > TypeNameHandling.Auto)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameHandling = value;
			}
		}

		[Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
		public virtual FormatterAssemblyStyle TypeNameAssemblyFormat
		{
			get
			{
				return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
			}
		}

		public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
		{
			get
			{
				return _typeNameAssemblyFormatHandling;
			}
			set
			{
				if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_typeNameAssemblyFormatHandling = value;
			}
		}

		public virtual PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling;
			}
			set
			{
				if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_preserveReferencesHandling = value;
			}
		}

		public virtual ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling;
			}
			set
			{
				if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_referenceLoopHandling = value;
			}
		}

		public virtual MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling;
			}
			set
			{
				if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_missingMemberHandling = value;
			}
		}

		public virtual NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling;
			}
			set
			{
				if (value < NullValueHandling.Include || value > NullValueHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_nullValueHandling = value;
			}
		}

		public virtual DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling;
			}
			set
			{
				if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_defaultValueHandling = value;
			}
		}

		public virtual ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling;
			}
			set
			{
				if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_objectCreationHandling = value;
			}
		}

		public virtual ConstructorHandling ConstructorHandling
		{
			get
			{
				return _constructorHandling;
			}
			set
			{
				if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_constructorHandling = value;
			}
		}

		public virtual MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling;
			}
			set
			{
				if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore)
				{
					throw new ArgumentOutOfRangeException("value");
				}
				_metadataPropertyHandling = value;
			}
		}

		public virtual JsonConverterCollection Converters
		{
			get
			{
				if (_converters == null)
				{
					_converters = new JsonConverterCollection();
				}
				return _converters;
			}
		}

		public virtual IContractResolver ContractResolver
		{
			get
			{
				return _contractResolver;
			}
			set
			{
				_contractResolver = value ?? DefaultContractResolver.Instance;
			}
		}

		public virtual StreamingContext Context
		{
			get
			{
				return _context;
			}
			set
			{
				_context = value;
			}
		}

		public virtual Formatting Formatting
		{
			get
			{
				return _formatting.GetValueOrDefault();
			}
			set
			{
				_formatting = value;
			}
		}

		public virtual DateFormatHandling DateFormatHandling
		{
			get
			{
				return _dateFormatHandling.GetValueOrDefault();
			}
			set
			{
				_dateFormatHandling = value;
			}
		}

		public virtual DateTimeZoneHandling DateTimeZoneHandling
		{
			get
			{
				return _dateTimeZoneHandling ?? DateTimeZoneHandling.RoundtripKind;
			}
			set
			{
				_dateTimeZoneHandling = value;
			}
		}

		public virtual DateParseHandling DateParseHandling
		{
			get
			{
				return _dateParseHandling ?? DateParseHandling.DateTime;
			}
			set
			{
				_dateParseHandling = value;
			}
		}

		public virtual FloatParseHandling FloatParseHandling
		{
			get
			{
				return _floatParseHandling.GetValueOrDefault();
			}
			set
			{
				_floatParseHandling = value;
			}
		}

		public virtual FloatFormatHandling FloatFormatHandling
		{
			get
			{
				return _floatFormatHandling.GetValueOrDefault();
			}
			set
			{
				_floatFormatHandling = value;
			}
		}

		public virtual StringEscapeHandling StringEscapeHandling
		{
			get
			{
				return _stringEscapeHandling.GetValueOrDefault();
			}
			set
			{
				_stringEscapeHandling = value;
			}
		}

		public virtual string DateFormatString
		{
			get
			{
				return _dateFormatString ?? "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
			}
			set
			{
				_dateFormatString = value;
				_dateFormatStringSet = true;
			}
		}

		public virtual CultureInfo Culture
		{
			get
			{
				return _culture ?? JsonSerializerSettings.DefaultCulture;
			}
			set
			{
				_culture = value;
			}
		}

		public virtual int? MaxDepth
		{
			get
			{
				return _maxDepth;
			}
			set
			{
				if (value <= 0)
				{
					throw new ArgumentException("Value must be positive.", "value");
				}
				_maxDepth = value;
				_maxDepthSet = true;
			}
		}

		public virtual bool CheckAdditionalContent
		{
			get
			{
				return _checkAdditionalContent.GetValueOrDefault();
			}
			set
			{
				_checkAdditionalContent = value;
			}
		}

		public virtual event EventHandler<ErrorEventArgs>? Error;

		internal bool IsCheckAdditionalContentSet()
		{
			return _checkAdditionalContent.HasValue;
		}

		public JsonSerializer()
		{
			_referenceLoopHandling = ReferenceLoopHandling.Error;
			_missingMemberHandling = MissingMemberHandling.Ignore;
			_nullValueHandling = NullValueHandling.Include;
			_defaultValueHandling = DefaultValueHandling.Include;
			_objectCreationHandling = ObjectCreationHandling.Auto;
			_preserveReferencesHandling = PreserveReferencesHandling.None;
			_constructorHandling = ConstructorHandling.Default;
			_typeNameHandling = TypeNameHandling.None;
			_metadataPropertyHandling = MetadataPropertyHandling.Default;
			_context = JsonSerializerSettings.DefaultContext;
			_serializationBinder = DefaultSerializationBinder.Instance;
			_culture = JsonSerializerSettings.DefaultCulture;
			_contractResolver = DefaultContractResolver.Instance;
		}

		public static JsonSerializer Create()
		{
			return new JsonSerializer();
		}

		public static JsonSerializer Create(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = Create();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		public static JsonSerializer CreateDefault()
		{
			return Create(JsonConvert.DefaultSettings?.Invoke());
		}

		public static JsonSerializer CreateDefault(JsonSerializerSettings? settings)
		{
			JsonSerializer jsonSerializer = CreateDefault();
			if (settings != null)
			{
				ApplySerializerSettings(jsonSerializer, settings);
			}
			return jsonSerializer;
		}

		private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings)
		{
			if (!CollectionUtils.IsNullOrEmpty(settings.Converters))
			{
				for (int i = 0; i < settings.Converters.Count; i++)
				{
					serializer.Converters.Insert(i, settings.Converters[i]);
				}
			}
			if (settings._typeNameHandling.HasValue)
			{
				serializer.TypeNameHandling = settings.TypeNameHandling;
			}
			if (settings._metadataPropertyHandling.HasValue)
			{
				serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling;
			}
			if (settings._typeNameAssemblyFormatHandling.HasValue)
			{
				serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling;
			}
			if (settings._preserveReferencesHandling.HasValue)
			{
				serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling;
			}
			if (settings._referenceLoopHandling.HasValue)
			{
				serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling;
			}
			if (settings._missingMemberHandling.HasValue)
			{
				serializer.MissingMemberHandling = settings.MissingMemberHandling;
			}
			if (settings._objectCreationHandling.HasValue)
			{
				serializer.ObjectCreationHandling = settings.ObjectCreationHandling;
			}
			if (settings._nullValueHandling.HasValue)
			{
				serializer.NullValueHandling = settings.NullValueHandling;
			}
			if (settings._defaultValueHandling.HasValue)
			{
				serializer.DefaultValueHandling = settings.DefaultValueHandling;
			}
			if (settings._constructorHandling.HasValue)
			{
				serializer.ConstructorHandling = settings.ConstructorHandling;
			}
			if (settings._context.HasValue)
			{
				serializer.Context = settings.Context;
			}
			if (settings._checkAdditionalContent.HasValue)
			{
				serializer._checkAdditionalContent = settings._checkAdditionalContent;
			}
			if (settings.Error != null)
			{
				serializer.Error += settings.Error;
			}
			if (settings.ContractResolver != null)
			{
				serializer.ContractResolver = settings.ContractResolver;
			}
			if (settings.ReferenceResolverProvider != null)
			{
				serializer.ReferenceResolver = settings.ReferenceResolverProvider();
			}
			if (settings.TraceWriter != null)
			{
				serializer.TraceWriter = settings.TraceWriter;
			}
			if (settings.EqualityComparer != null)
			{
				serializer.EqualityComparer = settings.EqualityComparer;
			}
			if (settings.SerializationBinder != null)
			{
				serializer.SerializationBinder = settings.SerializationBinder;
			}
			if (settings._formatting.HasValue)
			{
				serializer._formatting = settings._formatting;
			}
			if (settings._dateFormatHandling.HasValue)
			{
				serializer._dateFormatHandling = settings._dateFormatHandling;
			}
			if (settings._dateTimeZoneHandling.HasValue)
			{
				serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling;
			}
			if (settings._dateParseHandling.HasValue)
			{
				serializer._dateParseHandling = settings._dateParseHandling;
			}
			if (settings._dateFormatStringSet)
			{
				serializer._dateFormatString = settings._dateFormatString;
				serializer._dateFormatStringSet = settings._dateFormatStringSet;
			}
			if (settings._floatFormatHandling.HasValue)
			{
				serializer._floatFormatHandling = settings._floatFormatHandling;
			}
			if (settings._floatParseHandling.HasValue)
			{
				serializer._floatParseHandling = settings._floatParseHandling;
			}
			if (settings._stringEscapeHandling.HasValue)
			{
				serializer._stringEscapeHandling = settings._stringEscapeHandling;
			}
			if (settings._culture != null)
			{
				serializer._culture = settings._culture;
			}
			if (settings._maxDepthSet)
			{
				serializer._maxDepth = settings._maxDepth;
				serializer._maxDepthSet = settings._maxDepthSet;
			}
		}

		[DebuggerStepThrough]
		public void Populate(TextReader reader, object target)
		{
			Populate(new JsonTextReader(reader), target);
		}

		[DebuggerStepThrough]
		public void Populate(JsonReader reader, object target)
		{
			PopulateInternal(reader, target);
		}

		internal virtual void PopulateInternal(JsonReader reader, object target)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			ValidationUtils.ArgumentNotNull(target, "target");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			new JsonSerializerInternalReader(this).Populate(traceJsonReader ?? reader, target);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader)
		{
			return Deserialize(reader, null);
		}

		[DebuggerStepThrough]
		public object? Deserialize(TextReader reader, Type objectType)
		{
			return Deserialize(new JsonTextReader(reader), objectType);
		}

		[DebuggerStepThrough]
		public T? Deserialize<T>(JsonReader reader)
		{
			return (T)Deserialize(reader, typeof(T));
		}

		[DebuggerStepThrough]
		public object? Deserialize(JsonReader reader, Type? objectType)
		{
			return DeserializeInternal(reader, objectType);
		}

		internal virtual object? DeserializeInternal(JsonReader reader, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(reader, "reader");
			SetupReader(reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString);
			TraceJsonReader traceJsonReader = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? CreateTraceJsonReader(reader) : null);
			object? result = new JsonSerializerInternalReader(this).Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent);
			if (traceJsonReader != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null);
			}
			ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString);
			return result;
		}

		internal void SetupReader(JsonReader reader, out CultureInfo? previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string? previousDateFormatString)
		{
			if (_culture != null && !_culture.Equals(reader.Culture))
			{
				previousCulture = reader.Culture;
				reader.Culture = _culture;
			}
			else
			{
				previousCulture = null;
			}
			if (_dateTimeZoneHandling.HasValue && reader.DateTimeZoneHandling != _dateTimeZoneHandling)
			{
				previousDateTimeZoneHandling = reader.DateTimeZoneHandling;
				reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
			}
			else
			{
				previousDateTimeZoneHandling = null;
			}
			if (_dateParseHandling.HasValue && reader.DateParseHandling != _dateParseHandling)
			{
				previousDateParseHandling = reader.DateParseHandling;
				reader.DateParseHandling = _dateParseHandling.GetValueOrDefault();
			}
			else
			{
				previousDateParseHandling = null;
			}
			if (_floatParseHandling.HasValue && reader.FloatParseHandling != _floatParseHandling)
			{
				previousFloatParseHandling = reader.FloatParseHandling;
				reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault();
			}
			else
			{
				previousFloatParseHandling = null;
			}
			if (_maxDepthSet && reader.MaxDepth != _maxDepth)
			{
				previousMaxDepth = reader.MaxDepth;
				reader.MaxDepth = _maxDepth;
			}
			else
			{
				previousMaxDepth = null;
			}
			if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString)
			{
				previousDateFormatString = reader.DateFormatString;
				reader.DateFormatString = _dateFormatString;
			}
			else
			{
				previousDateFormatString = null;
			}
			if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable == null && _contractResolver is DefaultContractResolver defaultContractResolver)
			{
				jsonTextReader.PropertyNameTable = defaultContractResolver.GetNameTable();
			}
		}

		private void ResetReader(JsonReader reader, CultureInfo? previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string? previousDateFormatString)
		{
			if (previousCulture != null)
			{
				reader.Culture = previousCulture;
			}
			if (previousDateTimeZoneHandling.HasValue)
			{
				reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault();
			}
			if (previousDateParseHandling.HasValue)
			{
				reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault();
			}
			if (previousFloatParseHandling.HasValue)
			{
				reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault();
			}
			if (_maxDepthSet)
			{
				reader.MaxDepth = previousMaxDepth;
			}
			if (_dateFormatStringSet)
			{
				reader.DateFormatString = previousDateFormatString;
			}
			if (reader is JsonTextReader jsonTextReader && jsonTextReader.PropertyNameTable != null && _contractResolver is DefaultContractResolver defaultContractResolver && jsonTextReader.PropertyNameTable == defaultContractResolver.GetNameTable())
			{
				jsonTextReader.PropertyNameTable = null;
			}
		}

		public void Serialize(TextWriter textWriter, object? value)
		{
			Serialize(new JsonTextWriter(textWriter), value);
		}

		public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType)
		{
			SerializeInternal(jsonWriter, value, objectType);
		}

		public void Serialize(TextWriter textWriter, object? value, Type objectType)
		{
			Serialize(new JsonTextWriter(textWriter), value, objectType);
		}

		public void Serialize(JsonWriter jsonWriter, object? value)
		{
			SerializeInternal(jsonWriter, value, null);
		}

		private TraceJsonReader CreateTraceJsonReader(JsonReader reader)
		{
			TraceJsonReader traceJsonReader = new TraceJsonReader(reader);
			if (reader.TokenType != 0)
			{
				traceJsonReader.WriteCurrentToken();
			}
			return traceJsonReader;
		}

		internal virtual void SerializeInternal(JsonWriter jsonWriter, object? value, Type? objectType)
		{
			ValidationUtils.ArgumentNotNull(jsonWriter, "jsonWriter");
			Formatting? formatting = null;
			if (_formatting.HasValue && jsonWriter.Formatting != _formatting)
			{
				formatting = jsonWriter.Formatting;
				jsonWriter.Formatting = _formatting.GetValueOrDefault();
			}
			DateFormatHandling? dateFormatHandling = null;
			if (_dateFormatHandling.HasValue && jsonWriter.DateFormatHandling != _dateFormatHandling)
			{
				dateFormatHandling = jsonWriter.DateFormatHandling;
				jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault();
			}
			DateTimeZoneHandling? dateTimeZoneHandling = null;
			if (_dateTimeZoneHandling.HasValue && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling)
			{
				dateTimeZoneHandling = jsonWriter.DateTimeZoneHandling;
				jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault();
			}
			FloatFormatHandling? floatFormatHandling = null;
			if (_floatFormatHandling.HasValue && jsonWriter.FloatFormatHandling != _floatFormatHandling)
			{
				floatFormatHandling = jsonWriter.FloatFormatHandling;
				jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault();
			}
			StringEscapeHandling? stringEscapeHandling = null;
			if (_stringEscapeHandling.HasValue && jsonWriter.StringEscapeHandling != _stringEscapeHandling)
			{
				stringEscapeHandling = jsonWriter.StringEscapeHandling;
				jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault();
			}
			CultureInfo cultureInfo = null;
			if (_culture != null && !_culture.Equals(jsonWriter.Culture))
			{
				cultureInfo = jsonWriter.Culture;
				jsonWriter.Culture = _culture;
			}
			string dateFormatString = null;
			if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString)
			{
				dateFormatString = jsonWriter.DateFormatString;
				jsonWriter.DateFormatString = _dateFormatString;
			}
			TraceJsonWriter traceJsonWriter = ((TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null);
			new JsonSerializerInternalWriter(this).Serialize(traceJsonWriter ?? jsonWriter, value, objectType);
			if (traceJsonWriter != null)
			{
				TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null);
			}
			if (formatting.HasValue)
			{
				jsonWriter.Formatting = formatting.GetValueOrDefault();
			}
			if (dateFormatHandling.HasValue)
			{
				jsonWriter.DateFormatHandling = dateFormatHandling.GetValueOrDefault();
			}
			if (dateTimeZoneHandling.HasValue)
			{
				jsonWriter.DateTimeZoneHandling = dateTimeZoneHandling.GetValueOrDefault();
			}
			if (floatFormatHandling.HasValue)
			{
				jsonWriter.FloatFormatHandling = floatFormatHandling.GetValueOrDefault();
			}
			if (stringEscapeHandling.HasValue)
			{
				jsonWriter.StringEscapeHandling = stringEscapeHandling.GetValueOrDefault();
			}
			if (_dateFormatStringSet)
			{
				jsonWriter.DateFormatString = dateFormatString;
			}
			if (cultureInfo != null)
			{
				jsonWriter.Culture = cultureInfo;
			}
		}

		internal IReferenceResolver GetReferenceResolver()
		{
			if (_referenceResolver == null)
			{
				_referenceResolver = new DefaultReferenceResolver();
			}
			return _referenceResolver;
		}

		internal JsonConverter? GetMatchingConverter(Type type)
		{
			return GetMatchingConverter(_converters, type);
		}

		internal static JsonConverter? GetMatchingConverter(IList<JsonConverter>? converters, Type objectType)
		{
			if (converters != null)
			{
				for (int i = 0; i < converters.Count; i++)
				{
					JsonConverter jsonConverter = converters[i];
					if (jsonConverter.CanConvert(objectType))
					{
						return jsonConverter;
					}
				}
			}
			return null;
		}

		internal void OnError(ErrorEventArgs e)
		{
			this.Error?.Invoke(this, e);
		}
	}
	public class JsonSerializerSettings
	{
		internal const ReferenceLoopHandling DefaultReferenceLoopHandling = ReferenceLoopHandling.Error;

		internal const MissingMemberHandling DefaultMissingMemberHandling = MissingMemberHandling.Ignore;

		internal const NullValueHandling DefaultNullValueHandling = NullValueHandling.Include;

		internal const DefaultValueHandling DefaultDefaultValueHandling = DefaultValueHandling.Include;

		internal const ObjectCreationHandling DefaultObjectCreationHandling = ObjectCreationHandling.Auto;

		internal const PreserveReferencesHandling DefaultPreserveReferencesHandling = PreserveReferencesHandling.None;

		internal const ConstructorHandling DefaultConstructorHandling = ConstructorHandling.Default;

		internal const TypeNameHandling DefaultTypeNameHandling = TypeNameHandling.None;

		internal const MetadataPropertyHandling DefaultMetadataPropertyHandling = MetadataPropertyHandling.Default;

		internal static readonly StreamingContext DefaultContext;

		internal const Formatting DefaultFormatting = Formatting.None;

		internal const DateFormatHandling DefaultDateFormatHandling = DateFormatHandling.IsoDateFormat;

		internal const DateTimeZoneHandling DefaultDateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;

		internal const DateParseHandling DefaultDateParseHandling = DateParseHandling.DateTime;

		internal const FloatParseHandling DefaultFloatParseHandling = FloatParseHandling.Double;

		internal const FloatFormatHandling DefaultFloatFormatHandling = FloatFormatHandling.String;

		internal const StringEscapeHandling DefaultStringEscapeHandling = StringEscapeHandling.Default;

		internal const TypeNameAssemblyFormatHandling DefaultTypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple;

		internal static readonly CultureInfo DefaultCulture;

		internal const bool DefaultCheckAdditionalContent = false;

		internal const string DefaultDateFormatString = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";

		internal const int DefaultMaxDepth = 64;

		internal Formatting? _formatting;

		internal DateFormatHandling? _dateFormatHandling;

		internal DateTimeZoneHandling? _dateTimeZoneHandling;

		internal DateParseHandling? _dateParseHandling;

		internal FloatFormatHandling? _floatFormatHandling;

		internal FloatParseHandling? _floatParseHandling;

		internal StringEscapeHandling? _stringEscapeHandling;

		internal CultureInfo? _culture;

		internal bool? _checkAdditionalContent;

		internal int? _maxDepth;

		internal bool _maxDepthSet;

		internal string? _dateFormatString;

		internal bool _dateFormatStringSet;

		internal TypeNameAssemblyFormatHandling? _typeNameAssemblyFormatHandling;

		internal DefaultValueHandling? _defaultValueHandling;

		internal PreserveReferencesHandling? _preserveReferencesHandling;

		internal NullValueHandling? _nullValueHandling;

		internal ObjectCreationHandling? _objectCreationHandling;

		internal MissingMemberHandling? _missingMemberHandling;

		internal ReferenceLoopHandling? _referenceLoopHandling;

		internal StreamingContext? _context;

		internal ConstructorHandling? _constructorHandling;

		internal TypeNameHandling? _typeNameHandling;

		internal MetadataPropertyHandling? _metadataPropertyHandling;

		public ReferenceLoopHandling ReferenceLoopHandling
		{
			get
			{
				return _referenceLoopHandling.GetValueOrDefault();
			}
			set
			{
				_referenceLoopHandling = value;
			}
		}

		public MissingMemberHandling MissingMemberHandling
		{
			get
			{
				return _missingMemberHandling.GetValueOrDefault();
			}
			set
			{
				_missingMemberHandling = value;
			}
		}

		public ObjectCreationHandling ObjectCreationHandling
		{
			get
			{
				return _objectCreationHandling.GetValueOrDefault();
			}
			set
			{
				_objectCreationHandling = value;
			}
		}

		public NullValueHandling NullValueHandling
		{
			get
			{
				return _nullValueHandling.GetValueOrDefault();
			}
			set
			{
				_nullValueHandling = value;
			}
		}

		public DefaultValueHandling DefaultValueHandling
		{
			get
			{
				return _defaultValueHandling.GetValueOrDefault();
			}
			set
			{
				_defaultValueHandling = value;
			}
		}

		public IList<JsonConverter> Converters { get; set; }

		public PreserveReferencesHandling PreserveReferencesHandling
		{
			get
			{
				return _preserveReferencesHandling.GetValueOrDefault();
			}
			set
			{
				_preserveReferencesHandling = value;
			}
		}

		public TypeNameHandling TypeNameHandling
		{
			get
			{
				return _typeNameHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameHandling = value;
			}
		}

		public MetadataPropertyHandling MetadataPropertyHandling
		{
			get
			{
				return _metadataPropertyHandling.GetValueOrDefault();
			}
			set
			{
				_metadataPropertyHandling = value;
			}
		}

		[Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
		public FormatterAssemblyStyle TypeNameAssemblyFormat
		{
			get
			{
				return (FormatterAssemblyStyle)TypeNameAssemblyFormatHandling;
			}
			set
			{
				TypeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value;
			}
		}

		public TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling
		{
			get
			{
				return _typeNameAssemblyFormatHandling.GetValueOrDefault();
			}
			set
			{
				_typeNameAssemblyFormatHandling = value;
			}
		}

		public ConstructorHandling ConstructorHandling
		{
			get
			{
				return _constructorHandling.GetValueOrDefault();
			}
			set
			{
				_constructorHandling = value;
			}
		}

		public IContractResolver? ContractResolver { get; set; }

		public IEqualityComparer? EqualityComparer { get; set; }

		[Obsolete("Refer

plugins/OnlineShenanigans/System.Interactive.Async.dll

Decompiled 2 years ago
using System;
using System.CodeDom.Compiler;
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 Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("6.0.1.35981")]
[assembly: AssemblyInformationalVersion("6.0.1+8d8c10ceb7")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyMetadata("CommitHash", "8d8c10ceb7cc0bdb1e49b362efe5826e577dfeff")]
[assembly: AssemblyCompany(".NET Foundation and Contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) .NET Foundation and Contributors.")]
[assembly: AssemblyDescription("Interactive Extensions Async Library used to express queries over asynchronous enumerable sequences.")]
[assembly: AssemblyProduct("System.Interactive.Async (net6.0)")]
[assembly: AssemblyTitle("Interactive Extensions - Async Library")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/reactive")]
[assembly: AssemblyVersion("6.0.0.0")]
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;
		}
	}
}
[GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.4.255.64262")]
[ExcludeFromCodeCoverage]
internal static class ThisAssembly
{
	internal const string AssemblyConfiguration = "Release";

	internal const string AssemblyFileVersion = "6.0.1.35981";

	internal const string AssemblyInformationalVersion = "6.0.1+8d8c10ceb7";

	internal const string AssemblyName = "System.Interactive.Async";

	internal const string AssemblyTitle = "Interactive Extensions - Async Library";

	internal const string AssemblyVersion = "6.0.0.0";

	internal static readonly DateTime GitCommitDate = new DateTime(637793259160000000L, DateTimeKind.Utc);

	internal const string GitCommitId = "8d8c10ceb7cc0bdb1e49b362efe5826e577dfeff";

	internal const bool IsPrerelease = false;

	internal const bool IsPublicRelease = true;

	internal const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001008f5cff058631087031f8350f30a36fa078027e5df2316b564352dc9eb7af7ce856016d3c5e9d058036fe73bb5c83987bd3fc0793fbe25d633cc4f37c2bd5f1d717cd2a81661bec08f0971dc6078e17bde372b89005e7738a0ebd501b896ca3e8315270ff64df7809dd912c372df61785a5085b3553b7872e39b1b1cc0ff5a6bc";

	internal const string PublicKeyToken = "94bc3704cddfc263";

	internal const string RootNamespace = "System.Interactive.Async";
}
namespace System
{
	internal static class Error
	{
		public static Exception ArgumentNull(string paramName)
		{
			return new ArgumentNullException(paramName);
		}

		public static Exception ArgumentOutOfRange(string paramName)
		{
			return new ArgumentOutOfRangeException(paramName);
		}

		public static Exception NoElements()
		{
			return new InvalidOperationException(Strings.NO_ELEMENTS);
		}

		public static Exception MoreThanOneElement()
		{
			return new InvalidOperationException(Strings.MORE_THAN_ONE_ELEMENT);
		}

		public static Exception NotSupported()
		{
			return new NotSupportedException(Strings.NOT_SUPPORTED);
		}
	}
	internal static class Strings
	{
		public static string NO_ELEMENTS = "Source sequence doesn't contain any elements.";

		public static string MORE_THAN_ONE_ELEMENT = "Source sequence contains more than one element.";

		public static string NOT_SUPPORTED = "Specified method is not supported.";
	}
}
namespace System.Threading.Tasks
{
	internal static class TaskExt
	{
		public static readonly Task<bool> Never = new TaskCompletionSource<bool>().Task;
	}
	internal static class AsyncEnumerableExt
	{
		public static ConfiguredCancelableAsyncEnumerable<T>.Enumerator GetConfiguredAsyncEnumerator<T>(this IAsyncEnumerable<T> enumerable, CancellationToken cancellationToken, bool continueOnCapturedContext)
		{
			return enumerable.ConfigureAwait(continueOnCapturedContext).WithCancellation(cancellationToken).GetAsyncEnumerator();
		}
	}
}
namespace System.Linq
{
	public static class AsyncEnumerableEx
	{
		private sealed class DistinctAsyncIterator<TSource, TKey> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>, IAsyncEnumerable<TSource>
		{
			private readonly IEqualityComparer<TKey>? _comparer;

			private readonly Func<TSource, TKey> _keySelector;

			private readonly IAsyncEnumerable<TSource> _source;

			private IAsyncEnumerator<TSource>? _enumerator;

			private Set<TKey>? _set;

			public DistinctAsyncIterator(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source;
				_keySelector = keySelector;
				_comparer = comparer;
			}

			public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return (await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
			}

			public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				return await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return -1;
				}
				int count = 0;
				Set<TKey> s = new Set<TKey>(_comparer);
				IAsyncEnumerator<TSource> enu = _source.GetAsyncEnumerator(cancellationToken);
				try
				{
					while (await enu.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						TSource current = enu.Current;
						if (s.Add(_keySelector(current)))
						{
							count++;
						}
					}
				}
				finally
				{
					await enu.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
				return count;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new DistinctAsyncIterator<TSource, TKey>(_source, _keySelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
					_set = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				TSource current;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state == AsyncIteratorState.Iterating)
					{
						while (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
						{
							current = _enumerator.Current;
							if (_set.Add(_keySelector(current)))
							{
								_current = current;
								return true;
							}
						}
					}
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
				_enumerator = _source.GetAsyncEnumerator(_cancellationToken);
				if (!(await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false)))
				{
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
				current = _enumerator.Current;
				_set = new Set<TKey>(_comparer);
				_set.Add(_keySelector(current));
				_current = current;
				_state = AsyncIteratorState.Iterating;
				return true;
			}

			private async Task<List<TSource>> FillSetAsync(CancellationToken cancellationToken)
			{
				Set<TKey> s = new Set<TKey>(_comparer);
				List<TSource> r = new List<TSource>();
				IAsyncEnumerator<TSource> enu = _source.GetAsyncEnumerator(cancellationToken);
				try
				{
					while (await enu.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						TSource current = enu.Current;
						if (s.Add(_keySelector(current)))
						{
							r.Add(current);
						}
					}
				}
				finally
				{
					await enu.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
				return r;
			}
		}

		private sealed class DistinctAsyncIteratorWithTask<TSource, TKey> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>, IAsyncEnumerable<TSource>
		{
			private readonly IEqualityComparer<TKey>? _comparer;

			private readonly Func<TSource, ValueTask<TKey>> _keySelector;

			private readonly IAsyncEnumerable<TSource> _source;

			private IAsyncEnumerator<TSource>? _enumerator;

			private Set<TKey>? _set;

			public DistinctAsyncIteratorWithTask(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source;
				_keySelector = keySelector;
				_comparer = comparer;
			}

			public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return (await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
			}

			public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				return await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return -1;
				}
				int count = 0;
				Set<TKey> s = new Set<TKey>(_comparer);
				IAsyncEnumerator<TSource> enu = _source.GetAsyncEnumerator(cancellationToken);
				try
				{
					while (await enu.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						TSource current = enu.Current;
						Set<TKey> set = s;
						if (set.Add(await _keySelector(current).ConfigureAwait(continueOnCapturedContext: false)))
						{
							count++;
						}
					}
				}
				finally
				{
					await enu.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
				return count;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new DistinctAsyncIteratorWithTask<TSource, TKey>(_source, _keySelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
					_set = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				TSource element;
				Set<TKey> set;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state == AsyncIteratorState.Iterating)
					{
						while (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
						{
							element = _enumerator.Current;
							set = _set;
							if (set.Add(await _keySelector(element).ConfigureAwait(continueOnCapturedContext: false)))
							{
								_current = element;
								return true;
							}
						}
					}
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
				_enumerator = _source.GetAsyncEnumerator(_cancellationToken);
				if (!(await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false)))
				{
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
				element = _enumerator.Current;
				_set = new Set<TKey>(_comparer);
				set = _set;
				set.Add(await _keySelector(element).ConfigureAwait(continueOnCapturedContext: false));
				_current = element;
				_state = AsyncIteratorState.Iterating;
				return true;
			}

			private async ValueTask<List<TSource>> FillSetAsync(CancellationToken cancellationToken)
			{
				Set<TKey> s = new Set<TKey>(_comparer);
				List<TSource> r = new List<TSource>();
				IAsyncEnumerator<TSource> enu = _source.GetAsyncEnumerator(cancellationToken);
				try
				{
					while (await enu.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						TSource item = enu.Current;
						Set<TKey> set = s;
						if (set.Add(await _keySelector(item).ConfigureAwait(continueOnCapturedContext: false)))
						{
							r.Add(item);
						}
					}
				}
				finally
				{
					await enu.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
				return r;
			}
		}

		private sealed class DistinctAsyncIteratorWithTaskAndCancellation<TSource, TKey> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>, IAsyncEnumerable<TSource>
		{
			private readonly IEqualityComparer<TKey>? _comparer;

			private readonly Func<TSource, CancellationToken, ValueTask<TKey>> _keySelector;

			private readonly IAsyncEnumerable<TSource> _source;

			private IAsyncEnumerator<TSource>? _enumerator;

			private Set<TKey>? _set;

			public DistinctAsyncIteratorWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source;
				_keySelector = keySelector;
				_comparer = comparer;
			}

			public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return (await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
			}

			public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				return await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return -1;
				}
				int count = 0;
				Set<TKey> s = new Set<TKey>(_comparer);
				IAsyncEnumerator<TSource> enu = _source.GetAsyncEnumerator(cancellationToken);
				try
				{
					while (await enu.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						TSource current = enu.Current;
						Set<TKey> set = s;
						if (set.Add(await _keySelector(current, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
						{
							count++;
						}
					}
				}
				finally
				{
					await enu.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
				return count;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new DistinctAsyncIteratorWithTaskAndCancellation<TSource, TKey>(_source, _keySelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
					_set = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				TSource element;
				Set<TKey> set;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state == AsyncIteratorState.Iterating)
					{
						while (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
						{
							element = _enumerator.Current;
							set = _set;
							if (set.Add(await _keySelector(element, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
							{
								_current = element;
								return true;
							}
						}
					}
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
				_enumerator = _source.GetAsyncEnumerator(_cancellationToken);
				if (!(await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false)))
				{
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
				element = _enumerator.Current;
				_set = new Set<TKey>(_comparer);
				set = _set;
				set.Add(await _keySelector(element, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
				_current = element;
				_state = AsyncIteratorState.Iterating;
				return true;
			}

			private async ValueTask<List<TSource>> FillSetAsync(CancellationToken cancellationToken)
			{
				Set<TKey> s = new Set<TKey>(_comparer);
				List<TSource> r = new List<TSource>();
				IAsyncEnumerator<TSource> enu = _source.GetAsyncEnumerator(cancellationToken);
				try
				{
					while (await enu.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						TSource item = enu.Current;
						Set<TKey> set = s;
						if (set.Add(await _keySelector(item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)))
						{
							r.Add(item);
						}
					}
				}
				finally
				{
					await enu.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
				return r;
			}
		}

		private sealed class NeverAsyncEnumerable<TValue> : IAsyncEnumerable<TValue>
		{
			private sealed class NeverAsyncEnumerator : IAsyncEnumerator<TValue>, IAsyncDisposable
			{
				private readonly CancellationToken _token;

				private CancellationTokenRegistration _registration;

				private bool _once;

				public TValue Current
				{
					get
					{
						throw new InvalidOperationException();
					}
				}

				public NeverAsyncEnumerator(CancellationToken token)
				{
					_token = token;
				}

				public ValueTask DisposeAsync()
				{
					_registration.Dispose();
					return default(ValueTask);
				}

				public ValueTask<bool> MoveNextAsync()
				{
					if (_once)
					{
						return new ValueTask<bool>(result: false);
					}
					_once = true;
					TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
					_registration = _token.Register(delegate(object? state)
					{
						((TaskCompletionSource<bool>)state).TrySetCanceled(_token);
					}, taskCompletionSource);
					return new ValueTask<bool>(taskCompletionSource.Task);
				}
			}

			internal static readonly NeverAsyncEnumerable<TValue> Instance = new NeverAsyncEnumerable<TValue>();

			public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				return new NeverAsyncEnumerator(cancellationToken);
			}
		}

		private sealed class OnErrorResumeNextAsyncIterator<TSource> : AsyncIterator<TSource>
		{
			private readonly IEnumerable<IAsyncEnumerable<TSource>> _sources;

			private IAsyncEnumerator<TSource>? _enumerator;

			private IEnumerator<IAsyncEnumerable<TSource>>? _sourcesEnumerator;

			public OnErrorResumeNextAsyncIterator(IEnumerable<IAsyncEnumerable<TSource>> sources)
			{
				_sources = sources;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new OnErrorResumeNextAsyncIterator<TSource>(_sources);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_sourcesEnumerator != null)
				{
					_sourcesEnumerator.Dispose();
					_sourcesEnumerator = null;
				}
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0191;
					}
				}
				else
				{
					_sourcesEnumerator = _sources.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				while (true)
				{
					if (_enumerator == null)
					{
						if (!_sourcesEnumerator.MoveNext())
						{
							break;
						}
						_enumerator = _sourcesEnumerator.Current.GetAsyncEnumerator(_cancellationToken);
					}
					try
					{
						if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
						{
							_current = _enumerator.Current;
							return true;
						}
					}
					catch
					{
					}
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				goto IL_0191;
				IL_0191:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}
		}

		private sealed class ReturnEnumerable<TValue> : IAsyncEnumerable<TValue>, IAsyncIListProvider<TValue>
		{
			private sealed class ReturnEnumerator : IAsyncEnumerator<TValue>, IAsyncDisposable
			{
				private bool _once;

				public TValue Current { get; private set; }

				public ReturnEnumerator(TValue current)
				{
					Current = current;
				}

				public ValueTask DisposeAsync()
				{
					Current = default(TValue);
					return default(ValueTask);
				}

				public ValueTask<bool> MoveNextAsync()
				{
					if (_once)
					{
						return new ValueTask<bool>(result: false);
					}
					_once = true;
					return new ValueTask<bool>(result: true);
				}
			}

			private readonly TValue _value;

			public ReturnEnumerable(TValue value)
			{
				_value = value;
			}

			public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				return new ReturnEnumerator(_value);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				return new ValueTask<int>(1);
			}

			public ValueTask<TValue[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return new ValueTask<TValue[]>(new TValue[1] { _value });
			}

			public ValueTask<List<TValue>> ToListAsync(CancellationToken cancellationToken)
			{
				return new ValueTask<List<TValue>>(new List<TValue>(1) { _value });
			}
		}

		private sealed class ThrowEnumerable<TValue> : IAsyncEnumerable<TValue>
		{
			private sealed class ThrowEnumerator : IAsyncEnumerator<TValue>, IAsyncDisposable
			{
				private ValueTask<bool> _moveNextThrows;

				public TValue Current => default(TValue);

				public ThrowEnumerator(ValueTask<bool> moveNextThrows)
				{
					_moveNextThrows = moveNextThrows;
				}

				public ValueTask DisposeAsync()
				{
					_moveNextThrows = new ValueTask<bool>(result: false);
					return default(ValueTask);
				}

				public ValueTask<bool> MoveNextAsync()
				{
					ValueTask<bool> moveNextThrows = _moveNextThrows;
					_moveNextThrows = new ValueTask<bool>(result: false);
					return moveNextThrows;
				}
			}

			private readonly ValueTask<bool> _moveNextThrows;

			public ThrowEnumerable(ValueTask<bool> moveNextThrows)
			{
				_moveNextThrows = moveNextThrows;
			}

			public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				return new ThrowEnumerator(_moveNextThrows);
			}
		}

		private sealed class TimeoutAsyncIterator<TSource> : AsyncIterator<TSource>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly TimeSpan _timeout;

			private IAsyncEnumerator<TSource>? _enumerator;

			private Task? _loserTask;

			private CancellationTokenSource? _sourceCTS;

			public TimeoutAsyncIterator(IAsyncEnumerable<TSource> source, TimeSpan timeout)
			{
				_source = source;
				_timeout = timeout;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new TimeoutAsyncIterator<TSource>(_source, _timeout);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_loserTask != null)
				{
					await _loserTask.ConfigureAwait(continueOnCapturedContext: false);
					_loserTask = null;
					_enumerator = null;
				}
				else if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				if (_sourceCTS != null)
				{
					_sourceCTS.Dispose();
					_sourceCTS = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state2 = _state;
				if (state2 != AsyncIteratorState.Allocated)
				{
					if (state2 != AsyncIteratorState.Iterating)
					{
						goto IL_0249;
					}
				}
				else
				{
					_sourceCTS = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken);
					_enumerator = _source.GetAsyncEnumerator(_sourceCTS.Token);
					_state = AsyncIteratorState.Iterating;
				}
				ValueTask<bool> moveNext = _enumerator.MoveNextAsync();
				if (!moveNext.IsCompleted)
				{
					using CancellationTokenSource delayCts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationToken);
					Task delay = Task.Delay(_timeout, delayCts.Token);
					Task<bool> next = moveNext.AsTask();
					if (await Task.WhenAny(next, delay).ConfigureAwait(continueOnCapturedContext: false) == delay)
					{
						_loserTask = next.ContinueWith((Task<bool> _, object? state) => ((IAsyncDisposable)state).DisposeAsync().AsTask(), _enumerator);
						_sourceCTS.Cancel();
						throw new TimeoutException();
					}
					delayCts.Cancel();
				}
				if (await moveNext.ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = _enumerator.Current;
					return true;
				}
				goto IL_0249;
				IL_0249:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}
		}

		public static IAsyncEnumerable<TSource> Amb<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
		{
			if (first == null)
			{
				throw Error.ArgumentNull("first");
			}
			if (second == null)
			{
				throw Error.ArgumentNull("second");
			}
			return Core(first, second);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				IAsyncEnumerator<TSource> firstEnumerator = null;
				IAsyncEnumerator<TSource> secondEnumerator = null;
				Task<bool> firstMoveNext = null;
				Task<bool> secondMoveNext = null;
				CancellationTokenSource firstCancelToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
				CancellationTokenSource secondCancelToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
				try
				{
					firstEnumerator = first.GetAsyncEnumerator(firstCancelToken.Token);
					firstMoveNext = firstEnumerator.MoveNextAsync().AsTask();
					secondEnumerator = second.GetAsyncEnumerator(secondCancelToken.Token);
					secondMoveNext = secondEnumerator.MoveNextAsync().AsTask();
				}
				catch
				{
					secondCancelToken.Cancel();
					firstCancelToken.Cancel();
					await Task.WhenAll(AwaitMoveNextAsyncAndDispose(secondMoveNext, secondEnumerator), AwaitMoveNextAsyncAndDispose(firstMoveNext, firstEnumerator)).ConfigureAwait(continueOnCapturedContext: false);
					throw;
				}
				Task<bool> task = await Task.WhenAny(firstMoveNext, secondMoveNext).ConfigureAwait(continueOnCapturedContext: false);
				IAsyncEnumerator<TSource> winner;
				Task disposeLoser;
				if (task == firstMoveNext)
				{
					winner = firstEnumerator;
					secondCancelToken.Cancel();
					disposeLoser = AwaitMoveNextAsyncAndDispose(secondMoveNext, secondEnumerator);
				}
				else
				{
					winner = secondEnumerator;
					firstCancelToken.Cancel();
					disposeLoser = AwaitMoveNextAsyncAndDispose(firstMoveNext, firstEnumerator);
				}
				try
				{
					ConfiguredAsyncDisposable configuredAsyncDisposable = winner.ConfigureAwait(continueOnCapturedContext: false);
					try
					{
						if (await task.ConfigureAwait(continueOnCapturedContext: false))
						{
							yield return winner.Current;
							while (await winner.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
							{
								yield return winner.Current;
							}
						}
					}
					finally
					{
						IAsyncDisposable asyncDisposable = configuredAsyncDisposable as IAsyncDisposable;
						if (asyncDisposable != null)
						{
							await asyncDisposable.DisposeAsync();
						}
					}
				}
				finally
				{
					await disposeLoser.ConfigureAwait(continueOnCapturedContext: false);
				}
			}
		}

		public static IAsyncEnumerable<TSource> Amb<TSource>(params IAsyncEnumerable<TSource>[] sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return Core(sources);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource>[] sources, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				int i = sources.Length;
				IAsyncEnumerator<TSource>[] enumerators = new IAsyncEnumerator<TSource>[i];
				Task<bool>[] moveNexts = new Task<bool>[i];
				CancellationTokenSource[] individualTokenSources = new CancellationTokenSource[i];
				for (int j = 0; j < i; j++)
				{
					individualTokenSources[j] = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
				}
				try
				{
					for (int k = 0; k < i; k++)
					{
						moveNexts[k] = (enumerators[k] = sources[k].GetAsyncEnumerator(individualTokenSources[k].Token)).MoveNextAsync().AsTask();
					}
				}
				catch
				{
					Task[] array = new Task[i];
					for (int num = i - 1; num >= 0; num--)
					{
						individualTokenSources[num].Cancel();
						array[num] = AwaitMoveNextAsyncAndDispose(moveNexts[num], enumerators[num]);
					}
					await Task.WhenAll(array).ConfigureAwait(continueOnCapturedContext: false);
					throw;
				}
				Task<bool> task = await Task.WhenAny(moveNexts).ConfigureAwait(continueOnCapturedContext: false);
				int num2 = Array.IndexOf(moveNexts, task);
				IAsyncEnumerator<TSource> winner = enumerators[num2];
				List<Task> list = new List<Task>(i - 1);
				for (int num3 = i - 1; num3 >= 0; num3--)
				{
					if (num3 != num2)
					{
						individualTokenSources[num3].Cancel();
						Task item = AwaitMoveNextAsyncAndDispose(moveNexts[num3], enumerators[num3]);
						list.Add(item);
					}
				}
				Task cleanupLosers = Task.WhenAll(list);
				try
				{
					ConfiguredAsyncDisposable configuredAsyncDisposable = winner.ConfigureAwait(continueOnCapturedContext: false);
					try
					{
						if (await task.ConfigureAwait(continueOnCapturedContext: false))
						{
							yield return winner.Current;
							while (await winner.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
							{
								yield return winner.Current;
							}
						}
					}
					finally
					{
						IAsyncDisposable asyncDisposable = configuredAsyncDisposable as IAsyncDisposable;
						if (asyncDisposable != null)
						{
							await asyncDisposable.DisposeAsync();
						}
					}
				}
				finally
				{
					await cleanupLosers.ConfigureAwait(continueOnCapturedContext: false);
				}
			}
		}

		public static IAsyncEnumerable<TSource> Amb<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return Amb(sources.ToArray());
		}

		private static async Task AwaitMoveNextAsyncAndDispose<T>(Task<bool>? moveNextAsync, IAsyncEnumerator<T>? enumerator)
		{
			if (enumerator == null)
			{
				return;
			}
			ConfiguredAsyncDisposable configuredAsyncDisposable = enumerator.ConfigureAwait(continueOnCapturedContext: false);
			try
			{
				if (moveNextAsync != null)
				{
					try
					{
						await moveNextAsync.ConfigureAwait(continueOnCapturedContext: false);
					}
					catch (TaskCanceledException)
					{
					}
				}
			}
			finally
			{
				IAsyncDisposable asyncDisposable = configuredAsyncDisposable as IAsyncDisposable;
				if (asyncDisposable != null)
				{
					await asyncDisposable.DisposeAsync();
				}
			}
		}

		public static IAsyncEnumerable<IList<TSource>> Buffer<TSource>(this IAsyncEnumerable<TSource> source, int count)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (count <= 0)
			{
				throw Error.ArgumentOutOfRange("count");
			}
			return Core(source, count);
			static async IAsyncEnumerable<IList<TSource>> Core(IAsyncEnumerable<TSource> source, int count, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				List<TSource> buffer = new List<TSource>(count);
				await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					buffer.Add(item);
					if (buffer.Count == count)
					{
						yield return buffer;
						buffer = new List<TSource>(count);
					}
				}
				if (buffer.Count > 0)
				{
					yield return buffer;
				}
			}
		}

		public static IAsyncEnumerable<IList<TSource>> Buffer<TSource>(this IAsyncEnumerable<TSource> source, int count, int skip)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (count <= 0)
			{
				throw Error.ArgumentOutOfRange("count");
			}
			if (skip <= 0)
			{
				throw Error.ArgumentOutOfRange("skip");
			}
			return Core(source, count, skip);
			static async IAsyncEnumerable<IList<TSource>> Core(IAsyncEnumerable<TSource> source, int count, int skip, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				Queue<IList<TSource>> buffers = new Queue<IList<TSource>>();
				int index = 0;
				await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					if (index++ % skip == 0)
					{
						buffers.Enqueue(new List<TSource>(count));
					}
					foreach (IList<TSource> item2 in buffers)
					{
						item2.Add(item);
					}
					if (buffers.Count > 0 && buffers.Peek().Count == count)
					{
						yield return buffers.Dequeue();
					}
				}
				while (buffers.Count > 0)
				{
					yield return buffers.Dequeue();
				}
			}
		}

		public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler) where TException : Exception
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (handler == null)
			{
				throw Error.ArgumentNull("handler");
			}
			return Core(source, handler);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, IAsyncEnumerable<TSource>> handler, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				IAsyncEnumerable<TSource> err = null;
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					while (true)
					{
						TSource current;
						try
						{
							if (await e.MoveNextAsync())
							{
								current = e.Current;
								goto IL_011b;
							}
						}
						catch (TException arg)
						{
							err = handler(arg);
						}
						break;
						IL_011b:
						yield return current;
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
				if (err != null)
				{
					await foreach (TSource item in err.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler) where TException : Exception
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (handler == null)
			{
				throw Error.ArgumentNull("handler");
			}
			return Core(source, handler);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, ValueTask<IAsyncEnumerable<TSource>>> handler, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				IAsyncEnumerable<TSource> err = null;
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					TSource c = default(TSource);
					object obj = default(object);
					while (true)
					{
						int num = 0;
						try
						{
							if (await e.MoveNextAsync())
							{
								c = e.Current;
								goto IL_0136;
							}
						}
						catch (TException val)
						{
							obj = val;
							num = 1;
							goto IL_0136;
						}
						break;
						IL_0136:
						if (num == 1)
						{
							TException arg = (TException)obj;
							err = await handler(arg).ConfigureAwait(continueOnCapturedContext: false);
							break;
						}
						obj = null;
						yield return c;
						c = default(TSource);
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
				if (err != null)
				{
					await foreach (TSource item in err.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Catch<TSource, TException>(this IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler) where TException : Exception
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (handler == null)
			{
				throw Error.ArgumentNull("handler");
			}
			return Core(source, handler);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TException, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> handler, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				IAsyncEnumerable<TSource> err = null;
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					TSource c = default(TSource);
					object obj = default(object);
					while (true)
					{
						int num = 0;
						try
						{
							if (await e.MoveNextAsync())
							{
								c = e.Current;
								goto IL_0136;
							}
						}
						catch (TException val)
						{
							obj = val;
							num = 1;
							goto IL_0136;
						}
						break;
						IL_0136:
						if (num == 1)
						{
							TException arg = (TException)obj;
							err = await handler(arg, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
							break;
						}
						obj = null;
						yield return c;
						c = default(TSource);
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
				if (err != null)
				{
					await foreach (TSource item in err.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Catch<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return CatchCore(sources);
		}

		public static IAsyncEnumerable<TSource> Catch<TSource>(params IAsyncEnumerable<TSource>[] sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return CatchCore(sources);
		}

		public static IAsyncEnumerable<TSource> Catch<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
		{
			if (first == null)
			{
				throw Error.ArgumentNull("first");
			}
			if (second == null)
			{
				throw Error.ArgumentNull("second");
			}
			return CatchCore(new IAsyncEnumerable<TSource>[2] { first, second });
		}

		private static async IAsyncEnumerable<TSource> CatchCore<TSource>(IEnumerable<IAsyncEnumerable<TSource>> sources, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			ExceptionDispatchInfo error = null;
			foreach (IAsyncEnumerable<TSource> source2 in sources)
			{
				{
					ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source2.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
					try
					{
						error = null;
						while (true)
						{
							TSource current2;
							try
							{
								if (!(await e.MoveNextAsync()))
								{
									break;
								}
								current2 = e.Current;
								goto IL_013a;
							}
							catch (Exception source)
							{
								error = ExceptionDispatchInfo.Capture(source);
							}
							break;
							IL_013a:
							yield return current2;
						}
						if (error != null)
						{
							continue;
						}
						break;
					}
					finally
					{
						IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
						if (asyncDisposable != null)
						{
							await asyncDisposable.DisposeAsync();
						}
					}
				}
			}
			error?.Throw();
		}

		public static IAsyncEnumerable<TSource> Concat<TSource>(this IAsyncEnumerable<IAsyncEnumerable<TSource>> sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return Core(sources);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<IAsyncEnumerable<TSource>> sources, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				await foreach (IAsyncEnumerable<TSource> item in sources.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					await foreach (TSource item2 in item.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item2;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Concat<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return Core(sources);
			static async IAsyncEnumerable<TSource> Core(IEnumerable<IAsyncEnumerable<TSource>> sources, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				foreach (IAsyncEnumerable<TSource> source in sources)
				{
					await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Concat<TSource>(params IAsyncEnumerable<TSource>[] sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return Core(sources);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource>[] sources, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				foreach (IAsyncEnumerable<TSource> source in sources)
				{
					await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Defer<TSource>(Func<IAsyncEnumerable<TSource>> factory)
		{
			if (factory == null)
			{
				throw Error.ArgumentNull("factory");
			}
			return Core(factory);
			static async IAsyncEnumerable<TSource> Core(Func<IAsyncEnumerable<TSource>> factory, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				await foreach (TSource item in factory().WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					yield return item;
				}
			}
		}

		public static IAsyncEnumerable<TSource> Defer<TSource>(Func<Task<IAsyncEnumerable<TSource>>> factory)
		{
			if (factory == null)
			{
				throw Error.ArgumentNull("factory");
			}
			return Core(factory);
			static async IAsyncEnumerable<TSource> Core(Func<Task<IAsyncEnumerable<TSource>>> factory, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				await foreach (TSource item in (await factory().ConfigureAwait(continueOnCapturedContext: false)).WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					yield return item;
				}
			}
		}

		public static IAsyncEnumerable<TSource> Defer<TSource>(Func<CancellationToken, Task<IAsyncEnumerable<TSource>>> factory)
		{
			if (factory == null)
			{
				throw Error.ArgumentNull("factory");
			}
			return Core(factory);
			static async IAsyncEnumerable<TSource> Core(Func<CancellationToken, Task<IAsyncEnumerable<TSource>>> factory, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				await foreach (TSource item in (await factory(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					yield return item;
				}
			}
		}

		public static IAsyncEnumerable<TSource> Distinct<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctCore(source, keySelector, null);
		}

		public static IAsyncEnumerable<TSource> Distinct<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctCore(source, keySelector, comparer);
		}

		public static IAsyncEnumerable<TSource> Distinct<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctCore(source, keySelector, (IEqualityComparer<TKey>?)null);
		}

		public static IAsyncEnumerable<TSource> Distinct<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctCore(source, keySelector, null);
		}

		public static IAsyncEnumerable<TSource> Distinct<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctCore(source, keySelector, comparer);
		}

		public static IAsyncEnumerable<TSource> Distinct<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctCore(source, keySelector, comparer);
		}

		private static IAsyncEnumerable<TSource> DistinctCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer)
		{
			return new DistinctAsyncIterator<TSource, TKey>(source, keySelector, comparer);
		}

		private static IAsyncEnumerable<TSource> DistinctCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
		{
			return new DistinctAsyncIteratorWithTask<TSource, TKey>(source, keySelector, comparer);
		}

		private static IAsyncEnumerable<TSource> DistinctCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
		{
			return new DistinctAsyncIteratorWithTaskAndCancellation<TSource, TKey>(source, keySelector, comparer);
		}

		public static IAsyncEnumerable<TSource> DistinctUntilChanged<TSource>(this IAsyncEnumerable<TSource> source)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			return DistinctUntilChangedCore(source, null);
		}

		public static IAsyncEnumerable<TSource> DistinctUntilChanged<TSource>(this IAsyncEnumerable<TSource> source, IEqualityComparer<TSource>? comparer)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			return DistinctUntilChangedCore(source, comparer);
		}

		public static IAsyncEnumerable<TSource> DistinctUntilChanged<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctUntilChangedCore(source, keySelector, null);
		}

		public static IAsyncEnumerable<TSource> DistinctUntilChanged<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctUntilChangedCore(source, keySelector, comparer);
		}

		public static IAsyncEnumerable<TSource> DistinctUntilChanged<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctUntilChangedCore(source, keySelector, (IEqualityComparer<TKey>?)null);
		}

		public static IAsyncEnumerable<TSource> DistinctUntilChanged<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctUntilChangedCore(source, keySelector, null);
		}

		public static IAsyncEnumerable<TSource> DistinctUntilChanged<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctUntilChangedCore(source, keySelector, comparer);
		}

		public static IAsyncEnumerable<TSource> DistinctUntilChanged<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IEqualityComparer<TKey> comparer)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return DistinctUntilChangedCore(source, keySelector, comparer);
		}

		private static IAsyncEnumerable<TSource> DistinctUntilChangedCore<TSource>(IAsyncEnumerable<TSource> source, IEqualityComparer<TSource>? comparer)
		{
			if (comparer == null)
			{
				comparer = EqualityComparer<TSource>.Default;
			}
			return Core(source, comparer);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, IEqualityComparer<TSource> comparer, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					if (await e.MoveNextAsync())
					{
						TSource latest = e.Current;
						yield return latest;
						while (await e.MoveNextAsync())
						{
							TSource current = e.Current;
							if (!comparer.Equals(latest, current))
							{
								latest = current;
								yield return latest;
							}
						}
						yield break;
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
			}
		}

		private static IAsyncEnumerable<TSource> DistinctUntilChangedCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer)
		{
			if (comparer == null)
			{
				comparer = EqualityComparer<TKey>.Default;
			}
			return Core(source, keySelector, comparer);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					if (await e.MoveNextAsync())
					{
						TSource current = e.Current;
						TKey latestKey = keySelector(current);
						yield return current;
						while (await e.MoveNextAsync())
						{
							current = e.Current;
							TKey val = keySelector(current);
							if (!comparer.Equals(latestKey, val))
							{
								latestKey = val;
								yield return current;
							}
						}
						yield break;
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
			}
		}

		private static IAsyncEnumerable<TSource> DistinctUntilChangedCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
		{
			if (comparer == null)
			{
				comparer = EqualityComparer<TKey>.Default;
			}
			return Core(source, keySelector, comparer);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					if (await e.MoveNextAsync())
					{
						TSource item = e.Current;
						TKey latestKey = await keySelector(item).ConfigureAwait(continueOnCapturedContext: false);
						yield return item;
						while (await e.MoveNextAsync())
						{
							item = e.Current;
							TKey val = await keySelector(item).ConfigureAwait(continueOnCapturedContext: false);
							if (!comparer.Equals(latestKey, val))
							{
								latestKey = val;
								yield return item;
							}
						}
						yield break;
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
			}
		}

		private static IAsyncEnumerable<TSource> DistinctUntilChangedCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
		{
			if (comparer == null)
			{
				comparer = EqualityComparer<TKey>.Default;
			}
			return Core(source, keySelector, comparer);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					if (await e.MoveNextAsync())
					{
						TSource item = e.Current;
						TKey latestKey = await keySelector(item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						yield return item;
						while (await e.MoveNextAsync())
						{
							item = e.Current;
							TKey val = await keySelector(item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
							if (!comparer.Equals(latestKey, val))
							{
								latestKey = val;
								yield return item;
							}
						}
						yield break;
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Action<TSource> onNext)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			return DoCore(source, onNext, null, null);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Action<TSource> onNext, Action onCompleted)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onCompleted == null)
			{
				throw Error.ArgumentNull("onCompleted");
			}
			return DoCore(source, onNext, null, onCompleted);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Action<TSource> onNext, Action<Exception> onError)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onError == null)
			{
				throw Error.ArgumentNull("onError");
			}
			return DoCore(source, onNext, onError, null);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Action<TSource> onNext, Action<Exception> onError, Action onCompleted)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onError == null)
			{
				throw Error.ArgumentNull("onError");
			}
			if (onCompleted == null)
			{
				throw Error.ArgumentNull("onCompleted");
			}
			return DoCore(source, onNext, onError, onCompleted);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, Task> onNext)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			return DoCore(source, onNext, null, null);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, Task> onNext, Func<Task> onCompleted)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onCompleted == null)
			{
				throw Error.ArgumentNull("onCompleted");
			}
			return DoCore(source, onNext, null, onCompleted);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, Task> onNext, Func<Exception, Task> onError)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onError == null)
			{
				throw Error.ArgumentNull("onError");
			}
			return DoCore(source, onNext, onError, null);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, Task> onNext, Func<Exception, Task> onError, Func<Task> onCompleted)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onError == null)
			{
				throw Error.ArgumentNull("onError");
			}
			if (onCompleted == null)
			{
				throw Error.ArgumentNull("onCompleted");
			}
			return DoCore(source, onNext, onError, onCompleted);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, Task> onNext)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			return DoCore(source, onNext, null, null);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, Task> onNext, Func<CancellationToken, Task> onCompleted)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onCompleted == null)
			{
				throw Error.ArgumentNull("onCompleted");
			}
			return DoCore(source, onNext, null, onCompleted);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, Task> onNext, Func<Exception, CancellationToken, Task> onError)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onError == null)
			{
				throw Error.ArgumentNull("onError");
			}
			return DoCore(source, onNext, onError, null);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, Task> onNext, Func<Exception, CancellationToken, Task> onError, Func<CancellationToken, Task> onCompleted)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (onNext == null)
			{
				throw Error.ArgumentNull("onNext");
			}
			if (onError == null)
			{
				throw Error.ArgumentNull("onError");
			}
			if (onCompleted == null)
			{
				throw Error.ArgumentNull("onCompleted");
			}
			return DoCore(source, onNext, onError, onCompleted);
		}

		public static IAsyncEnumerable<TSource> Do<TSource>(this IAsyncEnumerable<TSource> source, IObserver<TSource> observer)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (observer == null)
			{
				throw Error.ArgumentNull("observer");
			}
			return DoCore(source, (Action<TSource>)observer.OnNext, (Action<Exception>?)observer.OnError, (Action?)observer.OnCompleted, default(CancellationToken));
		}

		private static async IAsyncEnumerable<TSource> DoCore<TSource>(IAsyncEnumerable<TSource> source, Action<TSource> onNext, Action<Exception>? onError, Action? onCompleted, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
			try
			{
				while (true)
				{
					TSource current;
					try
					{
						if (!(await e.MoveNextAsync()))
						{
							break;
						}
						current = e.Current;
						onNext(current);
						goto IL_0127;
					}
					catch (OperationCanceledException)
					{
						throw;
					}
					catch (Exception obj) when (onError != null)
					{
						onError(obj);
						throw;
					}
					IL_0127:
					yield return current;
				}
				onCompleted?.Invoke();
			}
			finally
			{
				IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
				if (asyncDisposable != null)
				{
					await asyncDisposable.DisposeAsync();
				}
			}
		}

		private static async IAsyncEnumerable<TSource> DoCore<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, Task> onNext, Func<Exception, Task>? onError, Func<Task>? onCompleted, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
			try
			{
				while (true)
				{
					TSource item;
					try
					{
						if (!(await e.MoveNextAsync()))
						{
							break;
						}
						item = e.Current;
						await onNext(item).ConfigureAwait(continueOnCapturedContext: false);
						goto IL_0289;
					}
					catch (OperationCanceledException)
					{
						throw;
					}
					catch (Exception arg) when (onError != null)
					{
						await onError(arg).ConfigureAwait(continueOnCapturedContext: false);
						throw;
					}
					IL_0289:
					yield return item;
				}
				if (onCompleted != null)
				{
					await onCompleted().ConfigureAwait(continueOnCapturedContext: false);
				}
			}
			finally
			{
				IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
				if (asyncDisposable != null)
				{
					await asyncDisposable.DisposeAsync();
				}
			}
		}

		private static async IAsyncEnumerable<TSource> DoCore<TSource>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, Task> onNext, Func<Exception, CancellationToken, Task>? onError, Func<CancellationToken, Task>? onCompleted, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
		{
			ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
			try
			{
				while (true)
				{
					TSource item;
					try
					{
						if (!(await e.MoveNextAsync()))
						{
							break;
						}
						item = e.Current;
						await onNext(item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						goto IL_0295;
					}
					catch (OperationCanceledException)
					{
						throw;
					}
					catch (Exception arg) when (onError != null)
					{
						await onError(arg, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						throw;
					}
					IL_0295:
					yield return item;
				}
				if (onCompleted != null)
				{
					await onCompleted(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				}
			}
			finally
			{
				IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
				if (asyncDisposable != null)
				{
					await asyncDisposable.DisposeAsync();
				}
			}
		}

		public static IAsyncEnumerable<TSource> Expand<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, IAsyncEnumerable<TSource>> selector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (selector == null)
			{
				throw Error.ArgumentNull("selector");
			}
			return Core(source, selector);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, IAsyncEnumerable<TSource>> selector, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				Queue<IAsyncEnumerable<TSource>> queue = new Queue<IAsyncEnumerable<TSource>>();
				queue.Enqueue(source);
				while (queue.Count > 0)
				{
					await foreach (TSource item in queue.Dequeue().WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						queue.Enqueue(selector(item));
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Expand<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<IAsyncEnumerable<TSource>>> selector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (selector == null)
			{
				throw Error.ArgumentNull("selector");
			}
			return Core(source, selector);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<IAsyncEnumerable<TSource>>> selector, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				Queue<IAsyncEnumerable<TSource>> queue = new Queue<IAsyncEnumerable<TSource>>();
				queue.Enqueue(source);
				while (queue.Count > 0)
				{
					await foreach (TSource item in queue.Dequeue().WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						Queue<IAsyncEnumerable<TSource>> queue2 = queue;
						queue2.Enqueue(await selector(item).ConfigureAwait(continueOnCapturedContext: false));
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Expand<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> selector)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (selector == null)
			{
				throw Error.ArgumentNull("selector");
			}
			return Core(source, selector);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<IAsyncEnumerable<TSource>>> selector, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				Queue<IAsyncEnumerable<TSource>> queue = new Queue<IAsyncEnumerable<TSource>>();
				queue.Enqueue(source);
				while (queue.Count > 0)
				{
					await foreach (TSource item in queue.Dequeue().WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						Queue<IAsyncEnumerable<TSource>> queue2 = queue;
						queue2.Enqueue(await selector(item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Finally<TSource>(this IAsyncEnumerable<TSource> source, Action finallyAction)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (finallyAction == null)
			{
				throw Error.ArgumentNull("finallyAction");
			}
			return Core(source, finallyAction);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Action finallyAction, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				try
				{
					await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
				finally
				{
					finallyAction();
				}
			}
		}

		public static IAsyncEnumerable<TSource> Finally<TSource>(this IAsyncEnumerable<TSource> source, Func<Task> finallyAction)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (finallyAction == null)
			{
				throw Error.ArgumentNull("finallyAction");
			}
			return Core(source, finallyAction);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<Task> finallyAction, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				try
				{
					await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
				finally
				{
					await finallyAction().ConfigureAwait(continueOnCapturedContext: false);
				}
			}
		}

		public static IAsyncEnumerable<TResult> Generate<TState, TResult>(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector)
		{
			if (condition == null)
			{
				throw Error.ArgumentNull("condition");
			}
			if (iterate == null)
			{
				throw Error.ArgumentNull("iterate");
			}
			if (resultSelector == null)
			{
				throw Error.ArgumentNull("resultSelector");
			}
			return Core(initialState, condition, iterate, resultSelector);
			static async IAsyncEnumerable<TResult> Core(TState initialState, Func<TState, bool> condition, Func<TState, TState> iterate, Func<TState, TResult> resultSelector, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				TState state = initialState;
				while (condition(state))
				{
					yield return resultSelector(state);
					state = iterate(state);
				}
			}
		}

		public static IAsyncEnumerable<TSource> IgnoreElements<TSource>(this IAsyncEnumerable<TSource> source)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			return Core(source);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					_ = item;
				}
				yield break;
			}
		}

		public static ValueTask<bool> IsEmptyAsync<TSource>(this IAsyncEnumerable<TSource> source, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			return Core(source, cancellationToken);
			static async ValueTask<bool> Core(IAsyncEnumerable<TSource> source, CancellationToken cancellationToken)
			{
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				bool result;
				try
				{
					result = !(await e.MoveNextAsync());
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
				return result;
			}
		}

		public static ValueTask<TSource> MaxAsync<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			return Core(source, comparer, cancellationToken);
			static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken)
			{
				if (comparer == null)
				{
					comparer = Comparer<TSource>.Default;
				}
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				TSource result;
				try
				{
					if (!(await e.MoveNextAsync()))
					{
						throw Error.NoElements();
					}
					TSource max = e.Current;
					while (await e.MoveNextAsync())
					{
						TSource current = e.Current;
						if (comparer.Compare(current, max) > 0)
						{
							max = current;
						}
					}
					result = max;
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
				return result;
			}
		}

		public static ValueTask<IList<TSource>> MaxByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MaxByCore(source, keySelector, null, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MaxByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MaxByCore(source, keySelector, comparer, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MaxByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MaxByCore(source, keySelector, (IComparer<TKey>?)null, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MaxByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MaxByCore(source, keySelector, null, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MaxByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MaxByCore(source, keySelector, comparer, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MaxByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MaxByCore(source, keySelector, comparer, cancellationToken);
		}

		private static ValueTask<IList<TSource>> MaxByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
		{
			IComparer<TKey> comparer2 = comparer;
			if (comparer2 == null)
			{
				comparer2 = Comparer<TKey>.Default;
			}
			return ExtremaBy(source, keySelector, (TKey key, TKey minValue) => comparer2.Compare(key, minValue), cancellationToken);
		}

		private static ValueTask<IList<TSource>> MaxByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
		{
			IComparer<TKey> comparer2 = comparer;
			if (comparer2 == null)
			{
				comparer2 = Comparer<TKey>.Default;
			}
			return ExtremaBy(source, keySelector, (TKey key, TKey minValue) => comparer2.Compare(key, minValue), cancellationToken);
		}

		private static ValueTask<IList<TSource>> MaxByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
		{
			IComparer<TKey> comparer2 = comparer;
			if (comparer2 == null)
			{
				comparer2 = Comparer<TKey>.Default;
			}
			return ExtremaBy(source, keySelector, (TKey key, TKey minValue) => comparer2.Compare(key, minValue), cancellationToken);
		}

		public static IAsyncEnumerable<TSource> Merge<TSource>(params IAsyncEnumerable<TSource>[] sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return Core(sources);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource>[] sources, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				int count = sources.Length;
				IAsyncEnumerator<TSource>?[] enumerators = new IAsyncEnumerator<TSource>[count];
				Task<bool>[] moveNextTasks = new Task<bool>[count];
				try
				{
					for (int i = 0; i < count; i++)
					{
						moveNextTasks[i] = (enumerators[i] = sources[i].GetAsyncEnumerator(cancellationToken)).MoveNextAsync().AsTask();
					}
					int active2 = count;
					while (active2 > 0)
					{
						Task<bool> task = await Task.WhenAny(moveNextTasks).ConfigureAwait(continueOnCapturedContext: false);
						int index = Array.IndexOf(moveNextTasks, task);
						IAsyncEnumerator<TSource> enumerator2 = enumerators[index];
						if (!(await task.ConfigureAwait(continueOnCapturedContext: false)))
						{
							moveNextTasks[index] = TaskExt.Never;
							enumerators[index] = null;
							await enumerator2.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
							active2--;
						}
						else
						{
							TSource current = enumerator2.Current;
							moveNextTasks[index] = enumerator2.MoveNextAsync().AsTask();
							yield return current;
						}
					}
				}
				finally
				{
					List<Exception> errors = null;
					for (int active2 = count - 1; active2 >= 0; active2--)
					{
						Task<bool> task2 = moveNextTasks[active2];
						IAsyncEnumerator<TSource> enumerator2 = enumerators[active2];
						try
						{
							try
							{
								if (task2 != null && task2 != TaskExt.Never)
								{
									await task2.ConfigureAwait(continueOnCapturedContext: false);
								}
							}
							finally
							{
								if (enumerator2 != null)
								{
									await enumerator2.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
								}
							}
						}
						catch (Exception item)
						{
							if (errors == null)
							{
								errors = new List<Exception>();
							}
							errors.Add(item);
						}
					}
					if (errors != null)
					{
						throw new AggregateException(errors);
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Merge<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return AsyncEnumerable.SelectMany<IAsyncEnumerable<TSource>, TSource>(AsyncEnumerable.ToAsyncEnumerable<IAsyncEnumerable<TSource>>(sources), (Func<IAsyncEnumerable<TSource>, IAsyncEnumerable<TSource>>)((IAsyncEnumerable<TSource> source) => source));
		}

		public static IAsyncEnumerable<TSource> Merge<TSource>(this IAsyncEnumerable<IAsyncEnumerable<TSource>> sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return AsyncEnumerable.SelectMany<IAsyncEnumerable<TSource>, TSource>(sources, (Func<IAsyncEnumerable<TSource>, IAsyncEnumerable<TSource>>)((IAsyncEnumerable<TSource> source) => source));
		}

		public static ValueTask<TSource> MinAsync<TSource>(this IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			return Core(source, comparer, cancellationToken);
			static async ValueTask<TSource> Core(IAsyncEnumerable<TSource> source, IComparer<TSource>? comparer, CancellationToken cancellationToken)
			{
				if (comparer == null)
				{
					comparer = Comparer<TSource>.Default;
				}
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				TSource result;
				try
				{
					if (!(await e.MoveNextAsync()))
					{
						throw Error.NoElements();
					}
					TSource min = e.Current;
					while (await e.MoveNextAsync())
					{
						TSource current = e.Current;
						if (comparer.Compare(current, min) < 0)
						{
							min = current;
						}
					}
					result = min;
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
				return result;
			}
		}

		public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MinByCore(source, keySelector, null, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MinByCore(source, keySelector, comparer, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MinByCore(source, keySelector, (IComparer<TKey>?)null, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MinByCore(source, keySelector, null, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MinByCore(source, keySelector, comparer, cancellationToken);
		}

		public static ValueTask<IList<TSource>> MinByAsync<TSource, TKey>(this IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey> comparer, CancellationToken cancellationToken = default(CancellationToken))
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (keySelector == null)
			{
				throw Error.ArgumentNull("keySelector");
			}
			return MinByCore(source, keySelector, comparer, cancellationToken);
		}

		private static ValueTask<IList<TSource>> MinByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
		{
			IComparer<TKey> comparer2 = comparer;
			if (comparer2 == null)
			{
				comparer2 = Comparer<TKey>.Default;
			}
			return ExtremaBy(source, keySelector, (TKey key, TKey minValue) => -comparer2.Compare(key, minValue), cancellationToken);
		}

		private static ValueTask<IList<TSource>> MinByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
		{
			IComparer<TKey> comparer2 = comparer;
			if (comparer2 == null)
			{
				comparer2 = Comparer<TKey>.Default;
			}
			return ExtremaBy(source, keySelector, (TKey key, TKey minValue) => -comparer2.Compare(key, minValue), cancellationToken);
		}

		private static ValueTask<IList<TSource>> MinByCore<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IComparer<TKey>? comparer, CancellationToken cancellationToken)
		{
			IComparer<TKey> comparer2 = comparer;
			if (comparer2 == null)
			{
				comparer2 = Comparer<TKey>.Default;
			}
			return ExtremaBy(source, keySelector, (TKey key, TKey minValue) => -comparer2.Compare(key, minValue), cancellationToken);
		}

		private static async ValueTask<IList<TSource>> ExtremaBy<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, TKey, int> compare, CancellationToken cancellationToken)
		{
			List<TSource> result = new List<TSource>();
			ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
			try
			{
				if (!(await e.MoveNextAsync()))
				{
					throw Error.NoElements();
				}
				TSource current = e.Current;
				TKey resKey = keySelector(current);
				result.Add(current);
				while (await e.MoveNextAsync())
				{
					TSource current2 = e.Current;
					TKey val = keySelector(current2);
					int num = compare(val, resKey);
					if (num == 0)
					{
						result.Add(current2);
					}
					else if (num > 0)
					{
						result = new List<TSource> { current2 };
						resKey = val;
					}
				}
			}
			finally
			{
				IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
				if (asyncDisposable != null)
				{
					await asyncDisposable.DisposeAsync();
				}
			}
			return result;
		}

		private static async ValueTask<IList<TSource>> ExtremaBy<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, Func<TKey, TKey, int> compare, CancellationToken cancellationToken)
		{
			List<TSource> result = new List<TSource>();
			ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
			try
			{
				if (!(await e.MoveNextAsync()))
				{
					throw Error.NoElements();
				}
				TSource current = e.Current;
				TKey resKey = await keySelector(current).ConfigureAwait(continueOnCapturedContext: false);
				result.Add(current);
				while (await e.MoveNextAsync())
				{
					TSource cur = e.Current;
					TKey val = await keySelector(cur).ConfigureAwait(continueOnCapturedContext: false);
					int num = compare(val, resKey);
					if (num == 0)
					{
						result.Add(cur);
					}
					else if (num > 0)
					{
						result = new List<TSource> { cur };
						resKey = val;
					}
				}
			}
			finally
			{
				IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
				if (asyncDisposable != null)
				{
					await asyncDisposable.DisposeAsync();
				}
			}
			return result;
		}

		private static async ValueTask<IList<TSource>> ExtremaBy<TSource, TKey>(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, Func<TKey, TKey, int> compare, CancellationToken cancellationToken)
		{
			List<TSource> result = new List<TSource>();
			ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
			try
			{
				if (!(await e.MoveNextAsync()))
				{
					throw Error.NoElements();
				}
				TSource current = e.Current;
				TKey resKey = await keySelector(current, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				result.Add(current);
				while (await e.MoveNextAsync())
				{
					TSource cur = e.Current;
					TKey val = await keySelector(cur, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					int num = compare(val, resKey);
					if (num == 0)
					{
						result.Add(cur);
					}
					else if (num > 0)
					{
						result = new List<TSource> { cur };
						resKey = val;
					}
				}
			}
			finally
			{
				IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
				if (asyncDisposable != null)
				{
					await asyncDisposable.DisposeAsync();
				}
			}
			return result;
		}

		public static IAsyncEnumerable<TValue> Never<TValue>()
		{
			return NeverAsyncEnumerable<TValue>.Instance;
		}

		public static IAsyncEnumerable<TSource> OnErrorResumeNext<TSource>(this IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
		{
			if (first == null)
			{
				throw Error.ArgumentNull("first");
			}
			if (second == null)
			{
				throw Error.ArgumentNull("second");
			}
			return OnErrorResumeNextCore(new IAsyncEnumerable<TSource>[2] { first, second });
		}

		public static IAsyncEnumerable<TSource> OnErrorResumeNext<TSource>(params IAsyncEnumerable<TSource>[] sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return OnErrorResumeNextCore(sources);
		}

		public static IAsyncEnumerable<TSource> OnErrorResumeNext<TSource>(this IEnumerable<IAsyncEnumerable<TSource>> sources)
		{
			if (sources == null)
			{
				throw Error.ArgumentNull("sources");
			}
			return OnErrorResumeNextCore(sources);
		}

		private static IAsyncEnumerable<TSource> OnErrorResumeNextCore<TSource>(IEnumerable<IAsyncEnumerable<TSource>> sources)
		{
			return new OnErrorResumeNextAsyncIterator<TSource>(sources);
		}

		public static IAsyncEnumerable<TResult> Repeat<TResult>(TResult element)
		{
			return Core(element);
			static async IAsyncEnumerable<TResult> Core(TResult element, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				while (true)
				{
					cancellationToken.ThrowIfCancellationRequested();
					yield return element;
				}
			}
		}

		public static IAsyncEnumerable<TSource> Repeat<TSource>(this IAsyncEnumerable<TSource> source)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			return Core(source);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				while (true)
				{
					await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Repeat<TSource>(this IAsyncEnumerable<TSource> source, int count)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (count < 0)
			{
				throw Error.ArgumentOutOfRange("count");
			}
			return Core(source, count);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, int count, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				for (int i = 0; i < count; i++)
				{
					await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						yield return item;
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Retry<TSource>(this IAsyncEnumerable<TSource> source)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			return ((IEnumerable<IAsyncEnumerable<TSource>>)new IAsyncEnumerable<TSource>[1] { source }).Repeat().Catch();
		}

		public static IAsyncEnumerable<TSource> Retry<TSource>(this IAsyncEnumerable<TSource> source, int retryCount)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (retryCount < 0)
			{
				throw Error.ArgumentOutOfRange("retryCount");
			}
			return new IAsyncEnumerable<TSource>[1] { source }.Repeat(retryCount).Catch();
		}

		private static IEnumerable<TSource> Repeat<TSource>(this IEnumerable<TSource> source)
		{
			while (true)
			{
				foreach (TSource item in source)
				{
					yield return item;
				}
			}
		}

		private static IEnumerable<TSource> Repeat<TSource>(this IEnumerable<TSource> source, int count)
		{
			for (int i = 0; i < count; i++)
			{
				foreach (TSource item in source)
				{
					yield return item;
				}
			}
		}

		public static IAsyncEnumerable<TValue> Return<TValue>(TValue value)
		{
			return new ReturnEnumerable<TValue>(value);
		}

		public static IAsyncEnumerable<TSource> Scan<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, TSource, TSource> accumulator)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (accumulator == null)
			{
				throw Error.ArgumentNull("accumulator");
			}
			return Core(source, accumulator);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, TSource, TSource> accumulator, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					if (await e.MoveNextAsync())
					{
						TSource res = e.Current;
						while (await e.MoveNextAsync())
						{
							res = accumulator(res, e.Current);
							yield return res;
						}
						yield break;
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
			}
		}

		public static IAsyncEnumerable<TAccumulate> Scan<TSource, TAccumulate>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (accumulator == null)
			{
				throw Error.ArgumentNull("accumulator");
			}
			return Core(source, seed, accumulator);
			static async IAsyncEnumerable<TAccumulate> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, TAccumulate> accumulator, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				TAccumulate res = seed;
				await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					res = accumulator(res, item);
					yield return res;
				}
			}
		}

		public static IAsyncEnumerable<TSource> Scan<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, TSource, ValueTask<TSource>> accumulator)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (accumulator == null)
			{
				throw Error.ArgumentNull("accumulator");
			}
			return Core(source, accumulator);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, TSource, ValueTask<TSource>> accumulator, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					if (await e.MoveNextAsync())
					{
						TSource res = e.Current;
						while (await e.MoveNextAsync())
						{
							res = await accumulator(res, e.Current).ConfigureAwait(continueOnCapturedContext: false);
							yield return res;
						}
						yield break;
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
			}
		}

		public static IAsyncEnumerable<TSource> Scan<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, TSource, CancellationToken, ValueTask<TSource>> accumulator)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (accumulator == null)
			{
				throw Error.ArgumentNull("accumulator");
			}
			return Core(source, accumulator);
			static async IAsyncEnumerable<TSource> Core(IAsyncEnumerable<TSource> source, Func<TSource, TSource, CancellationToken, ValueTask<TSource>> accumulator, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				ConfiguredCancelableAsyncEnumerable<TSource>.Enumerator e = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
				try
				{
					if (await e.MoveNextAsync())
					{
						TSource res = e.Current;
						while (await e.MoveNextAsync())
						{
							res = await accumulator(res, e.Current, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
							yield return res;
						}
						yield break;
					}
				}
				finally
				{
					IAsyncDisposable asyncDisposable = e as IAsyncDisposable;
					if (asyncDisposable != null)
					{
						await asyncDisposable.DisposeAsync();
					}
				}
			}
		}

		public static IAsyncEnumerable<TAccumulate> Scan<TSource, TAccumulate>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, ValueTask<TAccumulate>> accumulator)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (accumulator == null)
			{
				throw Error.ArgumentNull("accumulator");
			}
			return Core(source, seed, accumulator);
			static async IAsyncEnumerable<TAccumulate> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, ValueTask<TAccumulate>> accumulator, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				TAccumulate res = seed;
				await foreach (TSource item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					res = await accumulator(res, item).ConfigureAwait(continueOnCapturedContext: false);
					yield return res;
				}
			}
		}

		public static IAsyncEnumerable<TAccumulate> Scan<TSource, TAccumulate>(this IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, CancellationToken, ValueTask<TAccumulate>> accumulator)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (accumulator == null)
			{
				throw Error.ArgumentNull("accumulator");
			}
			return Core(source, seed, accumulator);
			static async IAsyncEnumerable<TAccumulate> Core(IAsyncEnumerable<TSource> source, TAccumulate seed, Func<TAccumulate, TSource, CancellationToken, ValueTask<TAccumulate>> accumulator, [EnumeratorCancellation] CancellationToken cancellationToken = default(CancellationToken))
			{
				TAccumulate res = seed;
				await foreach (TSource item in source.WithCance

plugins/OnlineShenanigans/System.Linq.Async.dll

Decompiled 2 years ago
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Internal;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("6.0.1.35981")]
[assembly: AssemblyInformationalVersion("6.0.1+8d8c10ceb7")]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")]
[assembly: AssemblyMetadata("CommitHash", "8d8c10ceb7cc0bdb1e49b362efe5826e577dfeff")]
[assembly: AssemblyCompany(".NET Foundation and Contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) .NET Foundation and Contributors.")]
[assembly: AssemblyDescription("Provides support for Language-Integrated Query (LINQ) over IAsyncEnumerable<T> sequences.")]
[assembly: AssemblyProduct("System.Linq.Async (net6.0)")]
[assembly: AssemblyTitle("System.Linq.Async")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/reactive")]
[assembly: AssemblyVersion("6.0.0.0")]
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;
		}
	}
}
[GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.4.255.64262")]
[ExcludeFromCodeCoverage]
internal static class ThisAssembly
{
	internal const string AssemblyConfiguration = "Release";

	internal const string AssemblyFileVersion = "6.0.1.35981";

	internal const string AssemblyInformationalVersion = "6.0.1+8d8c10ceb7";

	internal const string AssemblyName = "System.Linq.Async";

	internal const string AssemblyTitle = "System.Linq.Async";

	internal const string AssemblyVersion = "6.0.0.0";

	internal static readonly DateTime GitCommitDate = new DateTime(637793259160000000L, DateTimeKind.Utc);

	internal const string GitCommitId = "8d8c10ceb7cc0bdb1e49b362efe5826e577dfeff";

	internal const bool IsPrerelease = false;

	internal const bool IsPublicRelease = true;

	internal const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001008f5cff058631087031f8350f30a36fa078027e5df2316b564352dc9eb7af7ce856016d3c5e9d058036fe73bb5c83987bd3fc0793fbe25d633cc4f37c2bd5f1d717cd2a81661bec08f0971dc6078e17bde372b89005e7738a0ebd501b896ca3e8315270ff64df7809dd912c372df61785a5085b3553b7872e39b1b1cc0ff5a6bc";

	internal const string PublicKeyToken = "94bc3704cddfc263";

	internal const string RootNamespace = "System.Linq.Async";
}
namespace System
{
	internal static class Error
	{
		public static Exception ArgumentNull(string paramName)
		{
			return new ArgumentNullException(paramName);
		}

		public static Exception ArgumentOutOfRange(string paramName)
		{
			return new ArgumentOutOfRangeException(paramName);
		}

		public static Exception NoElements()
		{
			return new InvalidOperationException(Strings.NO_ELEMENTS);
		}

		public static Exception MoreThanOneElement()
		{
			return new InvalidOperationException(Strings.MORE_THAN_ONE_ELEMENT);
		}

		public static Exception NotSupported()
		{
			return new NotSupportedException(Strings.NOT_SUPPORTED);
		}
	}
	internal static class Strings
	{
		public static string NO_ELEMENTS = "Source sequence doesn't contain any elements.";

		public static string MORE_THAN_ONE_ELEMENT = "Source sequence contains more than one element.";

		public static string NOT_SUPPORTED = "Specified method is not supported.";
	}
}
namespace System.Threading.Tasks
{
	internal static class AsyncEnumerableExt
	{
		public static ConfiguredCancelableAsyncEnumerable<T>.Enumerator GetConfiguredAsyncEnumerator<T>(this IAsyncEnumerable<T> enumerable, CancellationToken cancellationToken, bool continueOnCapturedContext)
		{
			return enumerable.ConfigureAwait(continueOnCapturedContext).WithCancellation(cancellationToken).GetAsyncEnumerator();
		}
	}
	internal static class TaskExt
	{
		public static readonly TaskCompletionSource<bool> True;

		static TaskExt()
		{
			True = new TaskCompletionSource<bool>();
			True.SetResult(result: true);
		}
	}
}
namespace System.Collections.Generic
{
	internal static class AsyncEnumerableHelpers
	{
		internal struct ArrayWithLength<T>
		{
			public T[] Array;

			public int Length;
		}

		internal static async ValueTask<T[]> ToArray<T>(IAsyncEnumerable<T> source, CancellationToken cancellationToken)
		{
			ArrayWithLength<T> arrayWithLength = await ToArrayWithLength(source, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			Array.Resize(ref arrayWithLength.Array, arrayWithLength.Length);
			return arrayWithLength.Array;
		}

		internal static async ValueTask<ArrayWithLength<T>> ToArrayWithLength<T>(IAsyncEnumerable<T> source, CancellationToken cancellationToken)
		{
			cancellationToken.ThrowIfCancellationRequested();
			ArrayWithLength<T> result = default(ArrayWithLength<T>);
			if (source is ICollection<T> collection)
			{
				int count2 = collection.Count;
				if (count2 != 0)
				{
					result.Array = new T[count2];
					collection.CopyTo(result.Array, 0);
					result.Length = count2;
					return result;
				}
			}
			else
			{
				{
					ConfiguredCancelableAsyncEnumerable<T>.Enumerator en = source.GetConfiguredAsyncEnumerator(cancellationToken, continueOnCapturedContext: false);
					try
					{
						if (await en.MoveNextAsync())
						{
							T[] arr = new T[4]
							{
								en.Current,
								default(T),
								default(T),
								default(T)
							};
							int count = 1;
							while (await en.MoveNextAsync())
							{
								if (count == arr.Length)
								{
									int num = count << 1;
									if ((uint)num > 2146435071u)
									{
										num = ((2146435071 <= count) ? (count + 1) : 2146435071);
									}
									Array.Resize(ref arr, num);
								}
								arr[count++] = en.Current;
							}
							result.Length = count;
							result.Array = arr;
							return result;
						}
					}
					finally
					{
						IAsyncDisposable asyncDisposable = en as IAsyncDisposable;
						if (asyncDisposable != null)
						{
							await asyncDisposable.DisposeAsync();
						}
					}
				}
			}
			result.Length = 0;
			result.Array = Array.Empty<T>();
			return result;
		}

		internal static async Task<Set<T>> ToSet<T>(IAsyncEnumerable<T> source, IEqualityComparer<T>? comparer, CancellationToken cancellationToken)
		{
			Set<T> set = new Set<T>(comparer);
			await foreach (T item in source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
			{
				set.Add(item);
			}
			return set;
		}
	}
	public static class AsyncEnumerator
	{
		private sealed class AnonymousAsyncIterator<T> : AsyncIterator<T>
		{
			private readonly Func<T> _currentFunc;

			private readonly Func<ValueTask<bool>> _moveNext;

			private Func<ValueTask>? _dispose;

			public AnonymousAsyncIterator(Func<ValueTask<bool>> moveNext, Func<T> currentFunc, Func<ValueTask> dispose)
			{
				_moveNext = moveNext;
				_currentFunc = currentFunc;
				_dispose = dispose;
				GetAsyncEnumerator(default(CancellationToken));
			}

			public override AsyncIteratorBase<T> Clone()
			{
				throw new NotSupportedException("AnonymousAsyncIterator cannot be cloned. It is only intended for use as an iterator.");
			}

			public override async ValueTask DisposeAsync()
			{
				Func<ValueTask> func = Interlocked.Exchange(ref _dispose, null);
				if (func != null)
				{
					await func().ConfigureAwait(continueOnCapturedContext: false);
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0127;
					}
				}
				else
				{
					_state = AsyncIteratorState.Iterating;
				}
				if (await _moveNext().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = _currentFunc();
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_0127;
				IL_0127:
				return false;
			}
		}

		private sealed class WithCancellationAsyncEnumerator<T> : IAsyncEnumerator<T>, IAsyncDisposable
		{
			private readonly IAsyncEnumerator<T> _source;

			private readonly CancellationToken _cancellationToken;

			public T Current => _source.Current;

			public WithCancellationAsyncEnumerator(IAsyncEnumerator<T> source, CancellationToken cancellationToken)
			{
				_source = source;
				_cancellationToken = cancellationToken;
			}

			public ValueTask DisposeAsync()
			{
				return _source.DisposeAsync();
			}

			public ValueTask<bool> MoveNextAsync()
			{
				_cancellationToken.ThrowIfCancellationRequested();
				return _source.MoveNextAsync();
			}
		}

		public static IAsyncEnumerator<T> Create<T>(Func<ValueTask<bool>> moveNextAsync, Func<T> getCurrent, Func<ValueTask> disposeAsync)
		{
			if (moveNextAsync == null)
			{
				throw Error.ArgumentNull("moveNextAsync");
			}
			return new AnonymousAsyncIterator<T>(moveNextAsync, getCurrent, disposeAsync);
		}

		public static ValueTask<bool> MoveNextAsync<T>(this IAsyncEnumerator<T> source, CancellationToken cancellationToken)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			cancellationToken.ThrowIfCancellationRequested();
			return source.MoveNextAsync();
		}

		public static IAsyncEnumerator<T> WithCancellation<T>(this IAsyncEnumerator<T> source, CancellationToken cancellationToken)
		{
			if (source == null)
			{
				throw Error.ArgumentNull("source");
			}
			if (cancellationToken == default(CancellationToken))
			{
				return source;
			}
			return new WithCancellationAsyncEnumerator<T>(source, cancellationToken);
		}
	}
}
namespace System.Linq
{
	public static class AsyncEnumerable
	{
		private sealed class AnonymousAsyncEnumerable<T> : IAsyncEnumerable<T>
		{
			private readonly Func<CancellationToken, IAsyncEnumerator<T>> _getEnumerator;

			public AnonymousAsyncEnumerable(Func<CancellationToken, IAsyncEnumerator<T>> getEnumerator)
			{
				_getEnumerator = getEnumerator;
			}

			public IAsyncEnumerator<T> GetAsyncEnumerator(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				return _getEnumerator(cancellationToken);
			}
		}

		private abstract class AppendPrependAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>, IAsyncEnumerable<TSource>
		{
			protected readonly IAsyncEnumerable<TSource> _source;

			protected IAsyncEnumerator<TSource>? _enumerator;

			protected AppendPrependAsyncIterator(IAsyncEnumerable<TSource> source)
			{
				_source = source;
			}

			protected void GetSourceEnumerator(CancellationToken cancellationToken)
			{
				_enumerator = _source.GetAsyncEnumerator(cancellationToken);
			}

			public abstract AppendPrependAsyncIterator<TSource> Append(TSource item);

			public abstract AppendPrependAsyncIterator<TSource> Prepend(TSource item);

			protected async Task<bool> LoadFromEnumeratorAsync()
			{
				if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = _enumerator.Current;
					return true;
				}
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				return false;
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			public abstract ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken);

			public abstract ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken);

			public abstract ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken);
		}

		private sealed class AppendPrepend1AsyncIterator<TSource> : AppendPrependAsyncIterator<TSource>
		{
			private readonly TSource _item;

			private readonly bool _appending;

			private bool _hasEnumerator;

			public AppendPrepend1AsyncIterator(IAsyncEnumerable<TSource> source, TSource item, bool appending)
				: base(source)
			{
				_item = item;
				_appending = appending;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new AppendPrepend1AsyncIterator<TSource>(_source, _item, _appending);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_010a;
					}
				}
				else
				{
					_hasEnumerator = false;
					_state = AsyncIteratorState.Iterating;
					if (!_appending)
					{
						_current = _item;
						return true;
					}
				}
				if (!_hasEnumerator)
				{
					GetSourceEnumerator(_cancellationToken);
					_hasEnumerator = true;
				}
				if (_enumerator != null)
				{
					if (await LoadFromEnumeratorAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						return true;
					}
					if (_appending)
					{
						_current = _item;
						return true;
					}
				}
				goto IL_010a;
				IL_010a:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}

			public override AppendPrependAsyncIterator<TSource> Append(TSource element)
			{
				if (_appending)
				{
					return new AppendPrependNAsyncIterator<TSource>(_source, null, new System.Linq.SingleLinkedNode<TSource>(_item).Add(element), 0, 2);
				}
				return new AppendPrependNAsyncIterator<TSource>(_source, new System.Linq.SingleLinkedNode<TSource>(_item), new System.Linq.SingleLinkedNode<TSource>(element), 1, 1);
			}

			public override AppendPrependAsyncIterator<TSource> Prepend(TSource element)
			{
				if (_appending)
				{
					return new AppendPrependNAsyncIterator<TSource>(_source, new System.Linq.SingleLinkedNode<TSource>(element), new System.Linq.SingleLinkedNode<TSource>(_item), 1, 1);
				}
				return new AppendPrependNAsyncIterator<TSource>(_source, new System.Linq.SingleLinkedNode<TSource>(_item).Add(element), null, 2, 0);
			}

			public override async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				int num = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				if (num == -1)
				{
					return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				}
				cancellationToken.ThrowIfCancellationRequested();
				TSource[] array = new TSource[num];
				int index;
				if (_appending)
				{
					index = 0;
				}
				else
				{
					array[0] = _item;
					index = 1;
				}
				if (_source is ICollection<TSource> collection)
				{
					collection.CopyTo(array, index);
				}
				else
				{
					await foreach (TSource item in _source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						array[index] = item;
						int num2 = index + 1;
						index = num2;
					}
				}
				if (_appending)
				{
					array[^1] = _item;
				}
				return array;
			}

			public override async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				int num = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				cancellationToken.ThrowIfCancellationRequested();
				List<TSource> list = ((num == -1) ? new List<TSource>() : new List<TSource>(num));
				if (!_appending)
				{
					list.Add(_item);
				}
				await foreach (TSource item in _source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					list.Add(item);
				}
				if (_appending)
				{
					list.Add(_item);
				}
				return list;
			}

			public override async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (_source is IAsyncIListProvider<TSource> asyncIListProvider)
				{
					int num = await asyncIListProvider.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					return (num == -1) ? (-1) : (num + 1);
				}
				return (onlyIfCheap && !(_source is ICollection<TSource>) && !(_source is ICollection)) ? (-1) : (await _source.CountAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) + 1);
			}
		}

		private sealed class AppendPrependNAsyncIterator<TSource> : AppendPrependAsyncIterator<TSource>
		{
			private readonly System.Linq.SingleLinkedNode<TSource>? _prepended;

			private readonly System.Linq.SingleLinkedNode<TSource>? _appended;

			private readonly int _prependCount;

			private readonly int _appendCount;

			private System.Linq.SingleLinkedNode<TSource>? _node;

			private int _mode;

			private IEnumerator<TSource>? _appendedEnumerator;

			public AppendPrependNAsyncIterator(IAsyncEnumerable<TSource> source, System.Linq.SingleLinkedNode<TSource>? prepended, System.Linq.SingleLinkedNode<TSource>? appended, int prependCount, int appendCount)
				: base(source)
			{
				_prepended = prepended;
				_appended = appended;
				_prependCount = prependCount;
				_appendCount = appendCount;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new AppendPrependNAsyncIterator<TSource>(_source, _prepended, _appended, _prependCount, _appendCount);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_appendedEnumerator != null)
				{
					_appendedEnumerator.Dispose();
					_appendedEnumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0176;
					}
				}
				else
				{
					_mode = 1;
					_state = AsyncIteratorState.Iterating;
				}
				switch (_mode)
				{
				case 1:
					_node = _prepended;
					_mode = 2;
					goto case 2;
				case 2:
					if (_node != null)
					{
						_current = _node.Item;
						_node = _node.Linked;
						return true;
					}
					GetSourceEnumerator(_cancellationToken);
					_mode = 3;
					goto case 3;
				case 3:
					if (await LoadFromEnumeratorAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						return true;
					}
					if (_appended == null)
					{
						break;
					}
					_appendedEnumerator = _appended.GetEnumerator(_appendCount);
					_mode = 4;
					goto case 4;
				case 4:
					if (_appendedEnumerator.MoveNext())
					{
						_current = _appendedEnumerator.Current;
						return true;
					}
					break;
				}
				goto IL_0176;
				IL_0176:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}

			public override AppendPrependAsyncIterator<TSource> Append(TSource item)
			{
				System.Linq.SingleLinkedNode<TSource> appended = ((_appended != null) ? _appended.Add(item) : new System.Linq.SingleLinkedNode<TSource>(item));
				return new AppendPrependNAsyncIterator<TSource>(_source, _prepended, appended, _prependCount, _appendCount + 1);
			}

			public override AppendPrependAsyncIterator<TSource> Prepend(TSource item)
			{
				System.Linq.SingleLinkedNode<TSource> prepended = ((_prepended != null) ? _prepended.Add(item) : new System.Linq.SingleLinkedNode<TSource>(item));
				return new AppendPrependNAsyncIterator<TSource>(_source, prepended, _appended, _prependCount + 1, _appendCount);
			}

			public override async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				int num = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				if (num == -1)
				{
					return await AsyncEnumerableHelpers.ToArray(this, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				}
				TSource[] array = new TSource[num];
				int index2 = 0;
				for (System.Linq.SingleLinkedNode<TSource> singleLinkedNode = _prepended; singleLinkedNode != null; singleLinkedNode = singleLinkedNode.Linked)
				{
					array[index2] = singleLinkedNode.Item;
					int num2 = index2 + 1;
					index2 = num2;
				}
				if (_source is ICollection<TSource> collection)
				{
					collection.CopyTo(array, index2);
				}
				else
				{
					await foreach (TSource item in _source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						array[index2] = item;
						int num2 = index2 + 1;
						index2 = num2;
					}
				}
				index2 = array.Length;
				for (System.Linq.SingleLinkedNode<TSource> singleLinkedNode2 = _appended; singleLinkedNode2 != null; singleLinkedNode2 = singleLinkedNode2.Linked)
				{
					int num2 = index2 - 1;
					index2 = num2;
					array[index2] = singleLinkedNode2.Item;
				}
				return array;
			}

			public override async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				int num = await GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				List<TSource> list = ((num == -1) ? new List<TSource>() : new List<TSource>(num));
				for (System.Linq.SingleLinkedNode<TSource> singleLinkedNode = _prepended; singleLinkedNode != null; singleLinkedNode = singleLinkedNode.Linked)
				{
					list.Add(singleLinkedNode.Item);
				}
				await foreach (TSource item in _source.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
				{
					list.Add(item);
				}
				if (_appended != null)
				{
					using IEnumerator<TSource> enumerator2 = _appended.GetEnumerator(_appendCount);
					while (enumerator2.MoveNext())
					{
						list.Add(enumerator2.Current);
					}
				}
				return list;
			}

			public override async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (_source is IAsyncIListProvider<TSource> asyncIListProvider)
				{
					int num = await asyncIListProvider.GetCountAsync(onlyIfCheap, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					return (num == -1) ? (-1) : (num + _appendCount + _prependCount);
				}
				return (onlyIfCheap && !(_source is ICollection<TSource>) && !(_source is ICollection)) ? (-1) : (await _source.CountAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false) + _appendCount + _prependCount);
			}
		}

		private sealed class Concat2AsyncIterator<TSource> : ConcatAsyncIterator<TSource>
		{
			private readonly IAsyncEnumerable<TSource> _first;

			private readonly IAsyncEnumerable<TSource> _second;

			internal Concat2AsyncIterator(IAsyncEnumerable<TSource> first, IAsyncEnumerable<TSource> second)
			{
				_first = first;
				_second = second;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new Concat2AsyncIterator<TSource>(_first, _second);
			}

			internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
			{
				return new ConcatNAsyncIterator<TSource>(this, next, 2);
			}

			internal override IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index)
			{
				return index switch
				{
					0 => _first, 
					1 => _second, 
					_ => null, 
				};
			}
		}

		private abstract class ConcatAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>, IAsyncEnumerable<TSource>
		{
			private int _counter;

			private IAsyncEnumerator<TSource>? _enumerator;

			public ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return AsyncEnumerableHelpers.ToArray(this, cancellationToken);
			}

			public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				List<TSource> list = new List<TSource>();
				int i = 0;
				while (true)
				{
					IAsyncEnumerable<TSource> asyncEnumerable = GetAsyncEnumerable(i);
					if (asyncEnumerable == null)
					{
						break;
					}
					await foreach (TSource item in asyncEnumerable.WithCancellation(cancellationToken).ConfigureAwait(continueOnCapturedContext: false))
					{
						list.Add(item);
					}
					i++;
				}
				return list;
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					cancellationToken.ThrowIfCancellationRequested();
					int num = 0;
					int i = 0;
					while (true)
					{
						IAsyncEnumerable<TSource> asyncEnumerable = GetAsyncEnumerable(i);
						if (asyncEnumerable == null)
						{
							break;
						}
						int num2 = num;
						num = checked(num2 + await asyncEnumerable.CountAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
						i++;
					}
					return num;
				}
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				if (_state == AsyncIteratorState.Allocated)
				{
					_enumerator = GetAsyncEnumerable(0).GetAsyncEnumerator(_cancellationToken);
					_state = AsyncIteratorState.Iterating;
					_counter = 2;
				}
				if (_state == AsyncIteratorState.Iterating)
				{
					while (true)
					{
						if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
						{
							_current = _enumerator.Current;
							return true;
						}
						IAsyncEnumerable<TSource> next = GetAsyncEnumerable(_counter++ - 1);
						if (next == null)
						{
							break;
						}
						await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
						_enumerator = next.GetAsyncEnumerator(_cancellationToken);
					}
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				}
				return false;
			}

			internal abstract ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next);

			internal abstract IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index);
		}

		private sealed class ConcatNAsyncIterator<TSource> : ConcatAsyncIterator<TSource>
		{
			private readonly IAsyncEnumerable<TSource> _next;

			private readonly int _nextIndex;

			private readonly ConcatAsyncIterator<TSource> _previousConcat;

			internal ConcatNAsyncIterator(ConcatAsyncIterator<TSource> previousConcat, IAsyncEnumerable<TSource> next, int nextIndex)
			{
				_previousConcat = previousConcat;
				_next = next;
				_nextIndex = nextIndex;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new ConcatNAsyncIterator<TSource>(_previousConcat, _next, _nextIndex);
			}

			internal override ConcatAsyncIterator<TSource> Concat(IAsyncEnumerable<TSource> next)
			{
				if (_nextIndex == 2147483645)
				{
					return new Concat2AsyncIterator<TSource>(this, next);
				}
				return new ConcatNAsyncIterator<TSource>(this, next, _nextIndex + 1);
			}

			internal override IAsyncEnumerable<TSource>? GetAsyncEnumerable(int index)
			{
				if (index > _nextIndex)
				{
					return null;
				}
				ConcatNAsyncIterator<TSource> concatNAsyncIterator = this;
				while (true)
				{
					if (index == concatNAsyncIterator._nextIndex)
					{
						return concatNAsyncIterator._next;
					}
					if (!(concatNAsyncIterator._previousConcat is ConcatNAsyncIterator<TSource> concatNAsyncIterator2))
					{
						break;
					}
					concatNAsyncIterator = concatNAsyncIterator2;
				}
				return concatNAsyncIterator._previousConcat.GetAsyncEnumerable(index);
			}
		}

		private sealed class DefaultIfEmptyAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>, IAsyncEnumerable<TSource>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly TSource _defaultValue;

			private IAsyncEnumerator<TSource>? _enumerator;

			public DefaultIfEmptyAsyncIterator(IAsyncEnumerable<TSource> source, TSource defaultValue)
			{
				_source = source;
				_defaultValue = defaultValue;
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new DefaultIfEmptyAsyncIterator<TSource>(_source, _defaultValue);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				switch (_state)
				{
				case AsyncIteratorState.Allocated:
					_enumerator = _source.GetAsyncEnumerator(_cancellationToken);
					if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						_current = _enumerator.Current;
						_state = AsyncIteratorState.Iterating;
					}
					else
					{
						_current = _defaultValue;
						await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
						_enumerator = null;
						_state = AsyncIteratorState.Disposed;
					}
					return true;
				case AsyncIteratorState.Iterating:
					if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
					{
						_current = _enumerator.Current;
						return true;
					}
					break;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}

			public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				TSource[] array = await _source.ToArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				return (array.Length != 0) ? array : new TSource[1] { _defaultValue };
			}

			public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				List<TSource> list = await _source.ToListAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				if (list.Count == 0)
				{
					list.Add(_defaultValue);
				}
				return list;
			}

			public async ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				int num = ((onlyIfCheap && !(_source is ICollection<TSource>) && !(_source is ICollection)) ? ((!(_source is IAsyncIListProvider<TSource> asyncIListProvider)) ? (-1) : (await asyncIListProvider.GetCountAsync(onlyIfCheap: true, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))) : (await _source.CountAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)));
				return (num == 0) ? 1 : num;
			}
		}

		private sealed class DistinctAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>, IAsyncEnumerable<TSource>
		{
			private readonly IEqualityComparer<TSource>? _comparer;

			private readonly IAsyncEnumerable<TSource> _source;

			private IAsyncEnumerator<TSource>? _enumerator;

			private Set<TSource>? _set;

			public DistinctAsyncIterator(IAsyncEnumerable<TSource> source, IEqualityComparer<TSource>? comparer)
			{
				_source = source;
				_comparer = comparer;
			}

			public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return (await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray();
			}

			public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				return (await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToList();
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await FillSetAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new DistinctAsyncIterator<TSource>(_source, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
					_set = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				TSource current;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state == AsyncIteratorState.Iterating)
					{
						while (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
						{
							current = _enumerator.Current;
							if (_set.Add(current))
							{
								_current = current;
								return true;
							}
						}
					}
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
				_enumerator = _source.GetAsyncEnumerator(_cancellationToken);
				if (!(await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false)))
				{
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
				current = _enumerator.Current;
				_set = new Set<TSource>(_comparer);
				_set.Add(current);
				_current = current;
				_state = AsyncIteratorState.Iterating;
				return true;
			}

			private Task<Set<TSource>> FillSetAsync(CancellationToken cancellationToken)
			{
				return AsyncEnumerableHelpers.ToSet(_source, _comparer, cancellationToken);
			}
		}

		internal sealed class EmptyAsyncIterator<TValue> : IAsyncPartition<TValue>, IAsyncIListProvider<TValue>, IAsyncEnumerable<TValue>, IAsyncEnumerator<TValue>, IAsyncDisposable
		{
			public static readonly EmptyAsyncIterator<TValue> Instance = new EmptyAsyncIterator<TValue>();

			public TValue Current => default(TValue);

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				return new ValueTask<int>(0);
			}

			public IAsyncPartition<TValue> Skip(int count)
			{
				return this;
			}

			public IAsyncPartition<TValue> Take(int count)
			{
				return this;
			}

			public ValueTask<TValue[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return new ValueTask<TValue[]>(Array.Empty<TValue>());
			}

			public ValueTask<List<TValue>> ToListAsync(CancellationToken cancellationToken)
			{
				return new ValueTask<List<TValue>>(new List<TValue>());
			}

			public ValueTask<Maybe<TValue>> TryGetElementAtAsync(int index, CancellationToken cancellationToken)
			{
				return new ValueTask<Maybe<TValue>>(default(Maybe<TValue>));
			}

			public ValueTask<Maybe<TValue>> TryGetFirstAsync(CancellationToken cancellationToken)
			{
				return new ValueTask<Maybe<TValue>>(default(Maybe<TValue>));
			}

			public ValueTask<Maybe<TValue>> TryGetLastAsync(CancellationToken cancellationToken)
			{
				return new ValueTask<Maybe<TValue>>(default(Maybe<TValue>));
			}

			public ValueTask<bool> MoveNextAsync()
			{
				return new ValueTask<bool>(result: false);
			}

			public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				return this;
			}

			public ValueTask DisposeAsync()
			{
				return default(ValueTask);
			}
		}

		private sealed class GroupedResultAsyncEnumerable<TSource, TKey, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, TKey> _keySelector;

			private readonly Func<TKey, IAsyncEnumerable<TSource>, TResult> _resultSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private System.Linq.Internal.Lookup<TKey, TSource>? _lookup;

			private IEnumerator<TResult>? _enumerator;

			public GroupedResultAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TKey, IAsyncEnumerable<TSource>, TResult> resultSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_resultSelector = resultSelector ?? throw Error.ArgumentNull("resultSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new GroupedResultAsyncEnumerable<TSource, TKey, TResult>(_source, _keySelector, _resultSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0169;
					}
				}
				else
				{
					_lookup = await System.Linq.Internal.Lookup<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.ApplyResultSelector(_resultSelector).GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = _enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_0169;
				IL_0169:
				return false;
			}

			public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return (await System.Linq.Internal.Lookup<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray(_resultSelector);
			}

			public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				return (await System.Linq.Internal.Lookup<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToList(_resultSelector);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await System.Linq.Internal.Lookup<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedResultAsyncEnumerableWithTask<TSource, TKey, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, ValueTask<TKey>> _keySelector;

			private readonly Func<TKey, IAsyncEnumerable<TSource>, ValueTask<TResult>> _resultSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private LookupWithTask<TKey, TSource>? _lookup;

			private IAsyncEnumerator<TResult>? _enumerator;

			public GroupedResultAsyncEnumerableWithTask(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, Func<TKey, IAsyncEnumerable<TSource>, ValueTask<TResult>> resultSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_resultSelector = resultSelector ?? throw Error.ArgumentNull("resultSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new GroupedResultAsyncEnumerableWithTask<TSource, TKey, TResult>(_source, _keySelector, _resultSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_01e3;
					}
				}
				else
				{
					_lookup = await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.SelectAwaitCore<IAsyncGrouping<TKey, TSource>, TResult>(async (IAsyncGrouping<TKey, TSource> g) => await _resultSelector(g.Key, g).ConfigureAwait(continueOnCapturedContext: false)).GetAsyncEnumerator(_cancellationToken);
					_state = AsyncIteratorState.Iterating;
				}
				if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = _enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_01e3;
				IL_01e3:
				return false;
			}

			public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await (await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray(_resultSelector).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				return await (await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToList(_resultSelector).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedResultAsyncEnumerableWithTaskAndCancellation<TSource, TKey, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, CancellationToken, ValueTask<TKey>> _keySelector;

			private readonly Func<TKey, IAsyncEnumerable<TSource>, CancellationToken, ValueTask<TResult>> _resultSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private LookupWithTask<TKey, TSource>? _lookup;

			private IAsyncEnumerator<TResult>? _enumerator;

			public GroupedResultAsyncEnumerableWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, Func<TKey, IAsyncEnumerable<TSource>, CancellationToken, ValueTask<TResult>> resultSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_resultSelector = resultSelector ?? throw Error.ArgumentNull("resultSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new GroupedResultAsyncEnumerableWithTaskAndCancellation<TSource, TKey, TResult>(_source, _keySelector, _resultSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_01e3;
					}
				}
				else
				{
					_lookup = await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.SelectAwaitCore<IAsyncGrouping<TKey, TSource>, TResult>(async (IAsyncGrouping<TKey, TSource> g) => await _resultSelector(g.Key, g, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetAsyncEnumerator(_cancellationToken);
					_state = AsyncIteratorState.Iterating;
				}
				if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = _enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_01e3;
				IL_01e3:
				return false;
			}

			public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await (await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray(_resultSelector, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				return await (await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToList(_resultSelector, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedResultAsyncEnumerable<TSource, TKey, TElement, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, TKey> _keySelector;

			private readonly Func<TSource, TElement> _elementSelector;

			private readonly Func<TKey, IAsyncEnumerable<TElement>, TResult> _resultSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private System.Linq.Internal.Lookup<TKey, TElement>? _lookup;

			private IEnumerator<TResult>? _enumerator;

			public GroupedResultAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, Func<TKey, IAsyncEnumerable<TElement>, TResult> resultSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_elementSelector = elementSelector ?? throw Error.ArgumentNull("elementSelector");
				_resultSelector = resultSelector ?? throw Error.ArgumentNull("resultSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new GroupedResultAsyncEnumerable<TSource, TKey, TElement, TResult>(_source, _keySelector, _elementSelector, _resultSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_016f;
					}
				}
				else
				{
					_lookup = await System.Linq.Internal.Lookup<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.ApplyResultSelector(_resultSelector).GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = _enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_016f;
				IL_016f:
				return false;
			}

			public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return (await System.Linq.Internal.Lookup<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray(_resultSelector);
			}

			public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				return (await System.Linq.Internal.Lookup<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToList(_resultSelector);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await System.Linq.Internal.Lookup<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedResultAsyncEnumerableWithTask<TSource, TKey, TElement, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, ValueTask<TKey>> _keySelector;

			private readonly Func<TSource, ValueTask<TElement>> _elementSelector;

			private readonly Func<TKey, IAsyncEnumerable<TElement>, ValueTask<TResult>> _resultSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private LookupWithTask<TKey, TElement>? _lookup;

			private IAsyncEnumerator<TResult>? _enumerator;

			public GroupedResultAsyncEnumerableWithTask(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, Func<TSource, ValueTask<TElement>> elementSelector, Func<TKey, IAsyncEnumerable<TElement>, ValueTask<TResult>> resultSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_elementSelector = elementSelector ?? throw Error.ArgumentNull("elementSelector");
				_resultSelector = resultSelector ?? throw Error.ArgumentNull("resultSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new GroupedResultAsyncEnumerableWithTask<TSource, TKey, TElement, TResult>(_source, _keySelector, _elementSelector, _resultSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_01e9;
					}
				}
				else
				{
					_lookup = await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.SelectAwaitCore<IAsyncGrouping<TKey, TElement>, TResult>(async (IAsyncGrouping<TKey, TElement> g) => await _resultSelector(g.Key, g).ConfigureAwait(continueOnCapturedContext: false)).GetAsyncEnumerator(_cancellationToken);
					_state = AsyncIteratorState.Iterating;
				}
				if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = _enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_01e9;
				IL_01e9:
				return false;
			}

			public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await (await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray(_resultSelector).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				return await (await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToList(_resultSelector).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedResultAsyncEnumerableWithTaskAndCancellation<TSource, TKey, TElement, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, CancellationToken, ValueTask<TKey>> _keySelector;

			private readonly Func<TSource, CancellationToken, ValueTask<TElement>> _elementSelector;

			private readonly Func<TKey, IAsyncEnumerable<TElement>, CancellationToken, ValueTask<TResult>> _resultSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private LookupWithTask<TKey, TElement>? _lookup;

			private IAsyncEnumerator<TResult>? _enumerator;

			public GroupedResultAsyncEnumerableWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, Func<TSource, CancellationToken, ValueTask<TElement>> elementSelector, Func<TKey, IAsyncEnumerable<TElement>, CancellationToken, ValueTask<TResult>> resultSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_elementSelector = elementSelector ?? throw Error.ArgumentNull("elementSelector");
				_resultSelector = resultSelector ?? throw Error.ArgumentNull("resultSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new GroupedResultAsyncEnumerableWithTaskAndCancellation<TSource, TKey, TElement, TResult>(_source, _keySelector, _elementSelector, _resultSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_01e9;
					}
				}
				else
				{
					_lookup = await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.SelectAwaitCore<IAsyncGrouping<TKey, TElement>, TResult>(async (IAsyncGrouping<TKey, TElement> g) => await _resultSelector(g.Key, g, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).GetAsyncEnumerator(_cancellationToken);
					_state = AsyncIteratorState.Iterating;
				}
				if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = _enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_01e9;
				IL_01e9:
				return false;
			}

			public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await (await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToArray(_resultSelector, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				return await (await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).ToList(_resultSelector, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedAsyncEnumerable<TSource, TKey, TElement> : AsyncIterator<IAsyncGrouping<TKey, TElement>>, IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>, IAsyncEnumerable<IAsyncGrouping<TKey, TElement>>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, TKey> _keySelector;

			private readonly Func<TSource, TElement> _elementSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private System.Linq.Internal.Lookup<TKey, TElement>? _lookup;

			private IEnumerator<IGrouping<TKey, TElement>>? _enumerator;

			public GroupedAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_elementSelector = elementSelector ?? throw Error.ArgumentNull("elementSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<IAsyncGrouping<TKey, TElement>> Clone()
			{
				return new GroupedAsyncEnumerable<TSource, TKey, TElement>(_source, _keySelector, _elementSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0169;
					}
				}
				else
				{
					_lookup = await System.Linq.Internal.Lookup<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = (IAsyncGrouping<TKey, TElement>)_enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_0169;
				IL_0169:
				return false;
			}

			public async ValueTask<IAsyncGrouping<TKey, TElement>[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>)(await System.Linq.Internal.Lookup<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<IAsyncGrouping<TKey, TElement>>> ToListAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>)(await System.Linq.Internal.Lookup<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToListAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await System.Linq.Internal.Lookup<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedAsyncEnumerableWithTask<TSource, TKey, TElement> : AsyncIterator<IAsyncGrouping<TKey, TElement>>, IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>, IAsyncEnumerable<IAsyncGrouping<TKey, TElement>>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, ValueTask<TKey>> _keySelector;

			private readonly Func<TSource, ValueTask<TElement>> _elementSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private LookupWithTask<TKey, TElement>? _lookup;

			private IEnumerator<IGrouping<TKey, TElement>>? _enumerator;

			public GroupedAsyncEnumerableWithTask(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, Func<TSource, ValueTask<TElement>> elementSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_elementSelector = elementSelector ?? throw Error.ArgumentNull("elementSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<IAsyncGrouping<TKey, TElement>> Clone()
			{
				return new GroupedAsyncEnumerableWithTask<TSource, TKey, TElement>(_source, _keySelector, _elementSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0169;
					}
				}
				else
				{
					_lookup = await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = (IAsyncGrouping<TKey, TElement>)_enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_0169;
				IL_0169:
				return false;
			}

			public async ValueTask<IAsyncGrouping<TKey, TElement>[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>)(await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<IAsyncGrouping<TKey, TElement>>> ToListAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>)(await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToListAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedAsyncEnumerableWithTaskAndCancellation<TSource, TKey, TElement> : AsyncIterator<IAsyncGrouping<TKey, TElement>>, IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>, IAsyncEnumerable<IAsyncGrouping<TKey, TElement>>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, CancellationToken, ValueTask<TKey>> _keySelector;

			private readonly Func<TSource, CancellationToken, ValueTask<TElement>> _elementSelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private LookupWithTask<TKey, TElement>? _lookup;

			private IEnumerator<IGrouping<TKey, TElement>>? _enumerator;

			public GroupedAsyncEnumerableWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, Func<TSource, CancellationToken, ValueTask<TElement>> elementSelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_elementSelector = elementSelector ?? throw Error.ArgumentNull("elementSelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<IAsyncGrouping<TKey, TElement>> Clone()
			{
				return new GroupedAsyncEnumerableWithTaskAndCancellation<TSource, TKey, TElement>(_source, _keySelector, _elementSelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0169;
					}
				}
				else
				{
					_lookup = await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = (IAsyncGrouping<TKey, TElement>)_enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_0169;
				IL_0169:
				return false;
			}

			public async ValueTask<IAsyncGrouping<TKey, TElement>[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>)(await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<IAsyncGrouping<TKey, TElement>>> ToListAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TElement>>)(await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToListAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await LookupWithTask<TKey, TElement>.CreateAsync(_source, _keySelector, _elementSelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedAsyncEnumerable<TSource, TKey> : AsyncIterator<IAsyncGrouping<TKey, TSource>>, IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>, IAsyncEnumerable<IAsyncGrouping<TKey, TSource>>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, TKey> _keySelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private System.Linq.Internal.Lookup<TKey, TSource>? _lookup;

			private IEnumerator<IGrouping<TKey, TSource>>? _enumerator;

			public GroupedAsyncEnumerable(IAsyncEnumerable<TSource> source, Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<IAsyncGrouping<TKey, TSource>> Clone()
			{
				return new GroupedAsyncEnumerable<TSource, TKey>(_source, _keySelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0163;
					}
				}
				else
				{
					_lookup = await System.Linq.Internal.Lookup<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = (IAsyncGrouping<TKey, TSource>)_enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_0163;
				IL_0163:
				return false;
			}

			public async ValueTask<IAsyncGrouping<TKey, TSource>[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>)(await System.Linq.Internal.Lookup<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<IAsyncGrouping<TKey, TSource>>> ToListAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>)(await System.Linq.Internal.Lookup<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToListAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await System.Linq.Internal.Lookup<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedAsyncEnumerableWithTask<TSource, TKey> : AsyncIterator<IAsyncGrouping<TKey, TSource>>, IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>, IAsyncEnumerable<IAsyncGrouping<TKey, TSource>>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, ValueTask<TKey>> _keySelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private LookupWithTask<TKey, TSource>? _lookup;

			private IEnumerator<IGrouping<TKey, TSource>>? _enumerator;

			public GroupedAsyncEnumerableWithTask(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<IAsyncGrouping<TKey, TSource>> Clone()
			{
				return new GroupedAsyncEnumerableWithTask<TSource, TKey>(_source, _keySelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0163;
					}
				}
				else
				{
					_lookup = await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = (IAsyncGrouping<TKey, TSource>)_enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_0163;
				IL_0163:
				return false;
			}

			public async ValueTask<IAsyncGrouping<TKey, TSource>[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>)(await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<IAsyncGrouping<TKey, TSource>>> ToListAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>)(await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToListAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class GroupedAsyncEnumerableWithTaskAndCancellation<TSource, TKey> : AsyncIterator<IAsyncGrouping<TKey, TSource>>, IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>, IAsyncEnumerable<IAsyncGrouping<TKey, TSource>>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private readonly Func<TSource, CancellationToken, ValueTask<TKey>> _keySelector;

			private readonly IEqualityComparer<TKey>? _comparer;

			private LookupWithTask<TKey, TSource>? _lookup;

			private IEnumerator<IGrouping<TKey, TSource>>? _enumerator;

			public GroupedAsyncEnumerableWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TKey>> keySelector, IEqualityComparer<TKey>? comparer)
			{
				_source = source ?? throw Error.ArgumentNull("source");
				_keySelector = keySelector ?? throw Error.ArgumentNull("keySelector");
				_comparer = comparer;
			}

			public override AsyncIteratorBase<IAsyncGrouping<TKey, TSource>> Clone()
			{
				return new GroupedAsyncEnumerableWithTaskAndCancellation<TSource, TKey>(_source, _keySelector, _comparer);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
					_lookup = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0163;
					}
				}
				else
				{
					_lookup = await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = _lookup.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = (IAsyncGrouping<TKey, TSource>)_enumerator.Current;
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_0163;
				IL_0163:
				return false;
			}

			public async ValueTask<IAsyncGrouping<TKey, TSource>[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>)(await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public async ValueTask<List<IAsyncGrouping<TKey, TSource>>> ToListAsync(CancellationToken cancellationToken)
			{
				return await ((IAsyncIListProvider<IAsyncGrouping<TKey, TSource>>)(await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false))).ToListAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					return (await LookupWithTask<TKey, TSource>.CreateAsync(_source, _keySelector, _comparer, cancellationToken).ConfigureAwait(continueOnCapturedContext: false)).Count;
				}
			}
		}

		private sealed class RangeAsyncIterator : AsyncIterator<int>, IAsyncPartition<int>, IAsyncIListProvider<int>, IAsyncEnumerable<int>
		{
			private readonly int _start;

			private readonly int _end;

			public RangeAsyncIterator(int start, int count)
			{
				_start = start;
				_end = start + count;
			}

			public override AsyncIteratorBase<int> Clone()
			{
				return new RangeAsyncIterator(_start, _end - _start);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				return new ValueTask<int>(_end - _start);
			}

			public IAsyncPartition<int> Skip(int count)
			{
				int num = _end - _start;
				if (count >= num)
				{
					return EmptyAsyncIterator<int>.Instance;
				}
				return new RangeAsyncIterator(_start + count, num - count);
			}

			public IAsyncPartition<int> Take(int count)
			{
				int num = _end - _start;
				if (count >= num)
				{
					return this;
				}
				return new RangeAsyncIterator(_start, count);
			}

			public ValueTask<int[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				int[] array = new int[_end - _start];
				int start = _start;
				for (int i = 0; i < array.Length; i++)
				{
					array[i] = start++;
				}
				return new ValueTask<int[]>(array);
			}

			public ValueTask<List<int>> ToListAsync(CancellationToken cancellationToken)
			{
				List<int> list = new List<int>(_end - _start);
				for (int i = _start; i < _end; i++)
				{
					list.Add(i);
				}
				return new ValueTask<List<int>>(list);
			}

			public ValueTask<Maybe<int>> TryGetElementAtAsync(int index, CancellationToken cancellationToken)
			{
				if ((uint)index < (uint)(_end - _start))
				{
					return new ValueTask<Maybe<int>>(new Maybe<int>(_start + index));
				}
				return new ValueTask<Maybe<int>>(default(Maybe<int>));
			}

			public ValueTask<Maybe<int>> TryGetFirstAsync(CancellationToken cancellationToken)
			{
				return new ValueTask<Maybe<int>>(new Maybe<int>(_start));
			}

			public ValueTask<Maybe<int>> TryGetLastAsync(CancellationToken cancellationToken)
			{
				return new ValueTask<Maybe<int>>(new Maybe<int>(_end - 1));
			}

			protected override ValueTask<bool> MoveNextCore()
			{
				switch (_state)
				{
				case AsyncIteratorState.Allocated:
					_current = _start;
					_state = AsyncIteratorState.Iterating;
					return new ValueTask<bool>(result: true);
				case AsyncIteratorState.Iterating:
					_current++;
					if (_current != _end)
					{
						return new ValueTask<bool>(result: true);
					}
					break;
				}
				return Core();
				async ValueTask<bool> Core()
				{
					await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					return false;
				}
			}
		}

		private sealed class RepeatAsyncIterator<TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly TResult _element;

			private readonly int _count;

			private int _remaining;

			public RepeatAsyncIterator(TResult element, int count)
			{
				_element = element;
				_count = count;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new RepeatAsyncIterator<TResult>(_element, _count);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				return new ValueTask<int>(_count);
			}

			public ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				TResult[] array = new TResult[_count];
				for (int i = 0; i < _count; i++)
				{
					array[i] = _element;
				}
				return new ValueTask<TResult[]>(array);
			}

			public ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				List<TResult> list = new List<TResult>(_count);
				for (int i = 0; i < _count; i++)
				{
					list.Add(_element);
				}
				return new ValueTask<List<TResult>>(list);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_006a;
					}
				}
				else
				{
					_remaining = _count;
					if (_remaining > 0)
					{
						_current = _element;
					}
					_state = AsyncIteratorState.Iterating;
				}
				if (_remaining-- != 0)
				{
					return true;
				}
				goto IL_006a;
				IL_006a:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}
		}

		private sealed class ReverseAsyncIterator<TSource> : AsyncIterator<TSource>, IAsyncIListProvider<TSource>, IAsyncEnumerable<TSource>
		{
			private readonly IAsyncEnumerable<TSource> _source;

			private int _index;

			private TSource[]? _items;

			public ReverseAsyncIterator(IAsyncEnumerable<TSource> source)
			{
				_source = source;
			}

			public async ValueTask<TSource[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				TSource[] array = await _source.ToArrayAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				int num = 0;
				int num2 = array.Length - 1;
				while (num < num2)
				{
					TSource val = array[num];
					array[num] = array[num2];
					array[num2] = val;
					num++;
					num2--;
				}
				return array;
			}

			public async ValueTask<List<TSource>> ToListAsync(CancellationToken cancellationToken)
			{
				List<TSource> obj = await _source.ToListAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				obj.Reverse();
				return obj;
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					if (_source is IAsyncIListProvider<TSource> asyncIListProvider)
					{
						return asyncIListProvider.GetCountAsync(onlyIfCheap: true, cancellationToken);
					}
					if (!(_source is ICollection<TSource>) && !(_source is ICollection))
					{
						return new ValueTask<int>(-1);
					}
				}
				return _source.CountAsync(cancellationToken);
			}

			public override AsyncIteratorBase<TSource> Clone()
			{
				return new ReverseAsyncIterator<TSource>(_source);
			}

			public override async ValueTask DisposeAsync()
			{
				_items = null;
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_00fc;
					}
				}
				else
				{
					_items = await _source.ToArrayAsync(_cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					_index = _items.Length - 1;
					_state = AsyncIteratorState.Iterating;
				}
				if (_index != -1)
				{
					_current = _items[_index];
					_index--;
					return true;
				}
				goto IL_00fc;
				IL_00fc:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}
		}

		internal sealed class SelectEnumerableAsyncIterator<TSource, TResult> : AsyncIterator<TResult>
		{
			private readonly Func<TSource, TResult> _selector;

			private readonly IAsyncEnumerable<TSource> _source;

			private IAsyncEnumerator<TSource>? _enumerator;

			public SelectEnumerableAsyncIterator(IAsyncEnumerable<TSource> source, Func<TSource, TResult> selector)
			{
				_source = source;
				_selector = selector;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new SelectEnumerableAsyncIterator<TSource, TResult>(_source, _selector);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, TResult1> selector)
			{
				return new SelectEnumerableAsyncIterator<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_00e3;
					}
				}
				else
				{
					_enumerator = _source.GetAsyncEnumerator(_cancellationToken);
					_state = AsyncIteratorState.Iterating;
				}
				if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = _selector(_enumerator.Current);
					return true;
				}
				goto IL_00e3;
				IL_00e3:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}
		}

		internal sealed class SelectIListIterator<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly Func<TSource, TResult> _selector;

			private readonly IList<TSource> _source;

			private IEnumerator<TSource>? _enumerator;

			public SelectIListIterator(IList<TSource> source, Func<TSource, TResult> selector)
			{
				_source = source;
				_selector = selector;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new SelectIListIterator<TSource, TResult>(_source, _selector);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				cancellationToken.ThrowIfCancellationRequested();
				int num = 0;
				foreach (TSource item in _source)
				{
					_selector(item);
					num = checked(num + 1);
				}
				return new ValueTask<int>(num);
			}

			public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, TResult1> selector)
			{
				return new SelectIListIterator<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
			}

			public ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				int count = _source.Count;
				TResult[] array = new TResult[count];
				for (int i = 0; i < count; i++)
				{
					array[i] = _selector(_source[i]);
				}
				return new ValueTask<TResult[]>(array);
			}

			public ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				int count = _source.Count;
				List<TResult> list = new List<TResult>(count);
				for (int i = 0; i < count; i++)
				{
					list.Add(_selector(_source[i]));
				}
				return new ValueTask<List<TResult>>(list);
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_00d9;
					}
				}
				else
				{
					_enumerator = _source.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = _selector(_enumerator.Current);
					return true;
				}
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				goto IL_00d9;
				IL_00d9:
				return false;
			}
		}

		internal sealed class SelectEnumerableAsyncIteratorWithTask<TSource, TResult> : AsyncIterator<TResult>
		{
			private readonly Func<TSource, ValueTask<TResult>> _selector;

			private readonly IAsyncEnumerable<TSource> _source;

			private IAsyncEnumerator<TSource>? _enumerator;

			public SelectEnumerableAsyncIteratorWithTask(IAsyncEnumerable<TSource> source, Func<TSource, ValueTask<TResult>> selector)
			{
				_source = source;
				_selector = selector;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new SelectEnumerableAsyncIteratorWithTask<TSource, TResult>(_source, _selector);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, ValueTask<TResult1>> selector)
			{
				return new SelectEnumerableAsyncIteratorWithTask<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_0155;
					}
				}
				else
				{
					_enumerator = _source.GetAsyncEnumerator(_cancellationToken);
					_state = AsyncIteratorState.Iterating;
				}
				if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = await _selector(_enumerator.Current).ConfigureAwait(continueOnCapturedContext: false);
					return true;
				}
				goto IL_0155;
				IL_0155:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}
		}

		internal sealed class SelectEnumerableAsyncIteratorWithTaskAndCancellation<TSource, TResult> : AsyncIterator<TResult>
		{
			private readonly Func<TSource, CancellationToken, ValueTask<TResult>> _selector;

			private readonly IAsyncEnumerable<TSource> _source;

			private IAsyncEnumerator<TSource>? _enumerator;

			public SelectEnumerableAsyncIteratorWithTaskAndCancellation(IAsyncEnumerable<TSource> source, Func<TSource, CancellationToken, ValueTask<TResult>> selector)
			{
				_source = source;
				_selector = selector;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new SelectEnumerableAsyncIteratorWithTaskAndCancellation<TSource, TResult>(_source, _selector);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					await _enumerator.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, CancellationToken, ValueTask<TResult1>> selector)
			{
				return new SelectEnumerableAsyncIteratorWithTaskAndCancellation<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_015b;
					}
				}
				else
				{
					_enumerator = _source.GetAsyncEnumerator(_cancellationToken);
					_state = AsyncIteratorState.Iterating;
				}
				if (await _enumerator.MoveNextAsync().ConfigureAwait(continueOnCapturedContext: false))
				{
					_current = await _selector(_enumerator.Current, _cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
					return true;
				}
				goto IL_015b;
				IL_015b:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}
		}

		private sealed class SelectIListIteratorWithTask<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly Func<TSource, ValueTask<TResult>> _selector;

			private readonly IList<TSource> _source;

			private IEnumerator<TSource>? _enumerator;

			public SelectIListIteratorWithTask(IList<TSource> source, Func<TSource, ValueTask<TResult>> selector)
			{
				_source = source;
				_selector = selector;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new SelectIListIteratorWithTask<TSource, TResult>(_source, _selector);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					cancellationToken.ThrowIfCancellationRequested();
					int count = 0;
					foreach (TSource item in _source)
					{
						await _selector(item).ConfigureAwait(continueOnCapturedContext: false);
						count = checked(count + 1);
					}
					return count;
				}
			}

			public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, ValueTask<TResult1>> selector)
			{
				return new SelectIListIteratorWithTask<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
			}

			public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				int j = _source.Count;
				TResult[] res = new TResult[j];
				for (int i = 0; i < j; i++)
				{
					TResult[] array = res;
					int num = i;
					array[num] = await _selector(_source[i]).ConfigureAwait(continueOnCapturedContext: false);
				}
				return res;
			}

			public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				int j = _source.Count;
				List<TResult> res = new List<TResult>(j);
				for (int i = 0; i < j; i++)
				{
					List<TResult> list = res;
					list.Add(await _selector(_source[i]).ConfigureAwait(continueOnCapturedContext: false));
				}
				return res;
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_00e4;
					}
				}
				else
				{
					_enumerator = _source.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNext())
				{
					_current = await _selector(_enumerator.Current).ConfigureAwait(continueOnCapturedContext: false);
					return true;
				}
				goto IL_00e4;
				IL_00e4:
				await DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
				return false;
			}
		}

		private sealed class SelectIListIteratorWithTaskAndCancellation<TSource, TResult> : AsyncIterator<TResult>, IAsyncIListProvider<TResult>, IAsyncEnumerable<TResult>
		{
			private readonly Func<TSource, CancellationToken, ValueTask<TResult>> _selector;

			private readonly IList<TSource> _source;

			private IEnumerator<TSource>? _enumerator;

			public SelectIListIteratorWithTaskAndCancellation(IList<TSource> source, Func<TSource, CancellationToken, ValueTask<TResult>> selector)
			{
				_source = source;
				_selector = selector;
			}

			public override AsyncIteratorBase<TResult> Clone()
			{
				return new SelectIListIteratorWithTaskAndCancellation<TSource, TResult>(_source, _selector);
			}

			public override async ValueTask DisposeAsync()
			{
				if (_enumerator != null)
				{
					_enumerator.Dispose();
					_enumerator = null;
				}
				await base.DisposeAsync().ConfigureAwait(continueOnCapturedContext: false);
			}

			public ValueTask<int> GetCountAsync(bool onlyIfCheap, CancellationToken cancellationToken)
			{
				if (onlyIfCheap)
				{
					return new ValueTask<int>(-1);
				}
				return Core();
				async ValueTask<int> Core()
				{
					cancellationToken.ThrowIfCancellationRequested();
					int count = 0;
					foreach (TSource item in _source)
					{
						await _selector(item, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
						count = checked(count + 1);
					}
					return count;
				}
			}

			public override IAsyncEnumerable<TResult1> Select<TResult1>(Func<TResult, CancellationToken, ValueTask<TResult1>> selector)
			{
				return new SelectIListIteratorWithTaskAndCancellation<TSource, TResult1>(_source, CombineSelectors(_selector, selector));
			}

			public async ValueTask<TResult[]> ToArrayAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				int j = _source.Count;
				TResult[] res = new TResult[j];
				for (int i = 0; i < j; i++)
				{
					TResult[] array = res;
					int num = i;
					array[num] = await _selector(_source[i], cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
				}
				return res;
			}

			public async ValueTask<List<TResult>> ToListAsync(CancellationToken cancellationToken)
			{
				cancellationToken.ThrowIfCancellationRequested();
				int j = _source.Count;
				List<TResult> res = new List<TResult>(j);
				for (int i = 0; i < j; i++)
				{
					List<TResult> list = res;
					list.Add(await _selector(_source[i], cancellationToken).ConfigureAwait(continueOnCapturedContext: false));
				}
				return res;
			}

			protected override async ValueTask<bool> MoveNextCore()
			{
				AsyncIteratorState state = _state;
				if (state != AsyncIteratorState.Allocated)
				{
					if (state != AsyncIteratorState.Iterating)
					{
						goto IL_00ea;
					}
				}
				else
				{
					_enumerator = _source.GetEnumerator();
					_state = AsyncIteratorState.Iterating;
				}
				if (_enumerator.MoveNex

plugins/OnlineShenanigans/System.Reactive.dll

Decompiled 2 years ago
#define TRACE
using System;
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.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Joins;
using System.Reactive.Linq;
using System.Reactive.Linq.ObservableImpl;
using System.Reactive.PlatformServices;
using System.Reactive.Subjects;
using System.Reactive.Threading.Tasks;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyFileVersion("6.0.0.1")]
[assembly: AssemblyInformationalVersion("6.0.0.1+e29c7a50db")]
[assembly: InternalsVisibleTo("Tests.System.Reactive, PublicKey=00240000048000009400000006020000002400005253413100040000010001008f5cff058631087031f8350f30a36fa078027e5df2316b564352dc9eb7af7ce856016d3c5e9d058036fe73bb5c83987bd3fc0793fbe25d633cc4f37c2bd5f1d717cd2a81661bec08f0971dc6078e17bde372b89005e7738a0ebd501b896ca3e8315270ff64df7809dd912c372df61785a5085b3553b7872e39b1b1cc0ff5a6bc")]
[assembly: InternalsVisibleTo("Tests.System.Reactive.Uwp.DeviceRunner, PublicKey=00240000048000009400000006020000002400005253413100040000010001008f5cff058631087031f8350f30a36fa078027e5df2316b564352dc9eb7af7ce856016d3c5e9d058036fe73bb5c83987bd3fc0793fbe25d633cc4f37c2bd5f1d717cd2a81661bec08f0971dc6078e17bde372b89005e7738a0ebd501b896ca3e8315270ff64df7809dd912c372df61785a5085b3553b7872e39b1b1cc0ff5a6bc")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyMetadata("IsTrimmable", "True")]
[assembly: AssemblyMetadata("CommitHash", "e29c7a50db88513a87651c366088da8b7f40b1f0")]
[assembly: AssemblyCompany(".NET Foundation and Contributors")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) .NET Foundation and Contributors.")]
[assembly: AssemblyDescription("Reactive Extensions (Rx) for .NET")]
[assembly: AssemblyProduct("System.Reactive (net6.0)")]
[assembly: AssemblyTitle("System.Reactive")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/dotnet/reactive")]
[assembly: AssemblyVersion("6.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
[GeneratedCode("Nerdbank.GitVersioning.Tasks", "3.6.128.36433")]
[ExcludeFromCodeCoverage]
internal static class ThisAssembly
{
	internal const string AssemblyConfiguration = "Release";

	internal const string AssemblyFileVersion = "6.0.0.1";

	internal const string AssemblyInformationalVersion = "6.0.0.1+e29c7a50db";

	internal const string AssemblyName = "System.Reactive";

	internal const string AssemblyTitle = "System.Reactive";

	internal const string AssemblyVersion = "6.0.0.0";

	internal static readonly DateTime GitCommitDate = new DateTime(638200702660000000L, DateTimeKind.Utc);

	internal const string GitCommitId = "e29c7a50db88513a87651c366088da8b7f40b1f0";

	internal const bool IsPrerelease = false;

	internal const bool IsPublicRelease = true;

	internal const string PublicKey = "00240000048000009400000006020000002400005253413100040000010001008f5cff058631087031f8350f30a36fa078027e5df2316b564352dc9eb7af7ce856016d3c5e9d058036fe73bb5c83987bd3fc0793fbe25d633cc4f37c2bd5f1d717cd2a81661bec08f0971dc6078e17bde372b89005e7738a0ebd501b896ca3e8315270ff64df7809dd912c372df61785a5085b3553b7872e39b1b1cc0ff5a6bc";

	internal const string PublicKeyToken = "94bc3704cddfc263";

	internal const string RootNamespace = "System.Reactive";
}
namespace System
{
	public static class ObservableExtensions
	{
		public static IDisposable Subscribe<T>(this IObservable<T> source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			return source.Subscribe(new AnonymousObserver<T>(Stubs<T>.Ignore, Stubs.Throw, Stubs.Nop));
		}

		public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			return source.Subscribe(new AnonymousObserver<T>(onNext, Stubs.Throw, Stubs.Nop));
		}

		public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onError == null)
			{
				throw new ArgumentNullException("onError");
			}
			return source.Subscribe(new AnonymousObserver<T>(onNext, onError, Stubs.Nop));
		}

		public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action onCompleted)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onCompleted == null)
			{
				throw new ArgumentNullException("onCompleted");
			}
			return source.Subscribe(new AnonymousObserver<T>(onNext, Stubs.Throw, onCompleted));
		}

		public static IDisposable Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, Action onCompleted)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onError == null)
			{
				throw new ArgumentNullException("onError");
			}
			if (onCompleted == null)
			{
				throw new ArgumentNullException("onCompleted");
			}
			return source.Subscribe(new AnonymousObserver<T>(onNext, onError, onCompleted));
		}

		public static void Subscribe<T>(this IObservable<T> source, IObserver<T> observer, CancellationToken token)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			source.Subscribe_(observer, token);
		}

		public static void Subscribe<T>(this IObservable<T> source, CancellationToken token)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			source.Subscribe_(new AnonymousObserver<T>(Stubs<T>.Ignore, Stubs.Throw, Stubs.Nop), token);
		}

		public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, CancellationToken token)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			source.Subscribe_(new AnonymousObserver<T>(onNext, Stubs.Throw, Stubs.Nop), token);
		}

		public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, CancellationToken token)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onError == null)
			{
				throw new ArgumentNullException("onError");
			}
			source.Subscribe_(new AnonymousObserver<T>(onNext, onError, Stubs.Nop), token);
		}

		public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action onCompleted, CancellationToken token)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onCompleted == null)
			{
				throw new ArgumentNullException("onCompleted");
			}
			source.Subscribe_(new AnonymousObserver<T>(onNext, Stubs.Throw, onCompleted), token);
		}

		public static void Subscribe<T>(this IObservable<T> source, Action<T> onNext, Action<Exception> onError, Action onCompleted, CancellationToken token)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onError == null)
			{
				throw new ArgumentNullException("onError");
			}
			if (onCompleted == null)
			{
				throw new ArgumentNullException("onCompleted");
			}
			source.Subscribe_(new AnonymousObserver<T>(onNext, onError, onCompleted), token);
		}

		private static void Subscribe_<T>(this IObservable<T> source, IObserver<T> observer, CancellationToken token)
		{
			if (token.CanBeCanceled)
			{
				if (!token.IsCancellationRequested)
				{
					ISafeObserver<T> safeObserver = SafeObserver<T>.Wrap(observer);
					IDisposable state2 = source.Subscribe(safeObserver);
					safeObserver.SetResource(token.Register(delegate(object? state)
					{
						((IDisposable)state).Dispose();
					}, state2));
				}
			}
			else
			{
				source.Subscribe(observer);
			}
		}

		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public static IDisposable SubscribeSafe<T>(this IObservable<T> source, IObserver<T> observer)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			if (source is ObservableBase<T>)
			{
				return source.Subscribe(observer);
			}
			if (source is IProducer<T> producer)
			{
				return producer.SubscribeRaw(observer, enableSafeguard: false);
			}
			IDisposable result = Disposable.Empty;
			try
			{
				result = source.Subscribe(observer);
			}
			catch (Exception error)
			{
				observer.OnError(error);
			}
			return result;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	public struct TaskObservableMethodBuilder<T>
	{
		internal sealed class TaskObservable : ITaskObservable<T>, IObservable<T>, ITaskObservableAwaiter<T>, INotifyCompletion
		{
			private readonly AsyncSubject<T>? _subject;

			private readonly T? _result;

			private readonly Exception? _exception;

			public bool IsCompleted => _subject?.IsCompleted ?? true;

			public TaskObservable()
			{
				_subject = new AsyncSubject<T>();
			}

			public TaskObservable(T result)
			{
				_result = result;
			}

			public TaskObservable(Exception exception)
			{
				_exception = exception;
			}

			public void SetResult(T result)
			{
				if (IsCompleted)
				{
					throw new InvalidOperationException();
				}
				_subject.OnNext(result);
				_subject.OnCompleted();
			}

			public void SetException(Exception exception)
			{
				if (IsCompleted)
				{
					throw new InvalidOperationException();
				}
				_subject.OnError(exception);
			}

			public IDisposable Subscribe(IObserver<T> observer)
			{
				if (_subject != null)
				{
					return _subject.Subscribe(observer);
				}
				if (_exception != null)
				{
					observer.OnError(_exception);
					return Disposable.Empty;
				}
				observer.OnNext(_result);
				return Disposable.Empty;
			}

			public ITaskObservableAwaiter<T> GetAwaiter()
			{
				return this;
			}

			public T GetResult()
			{
				if (_subject != null)
				{
					return _subject.GetResult();
				}
				_exception?.Throw();
				return _result;
			}

			public void OnCompleted(Action continuation)
			{
				if (_subject != null)
				{
					_subject.OnCompleted(continuation);
				}
				else
				{
					continuation();
				}
			}
		}

		private IAsyncStateMachine _stateMachine;

		private TaskObservable _inner;

		public ITaskObservable<T> Task => _inner ?? (_inner = new TaskObservable());

		public static TaskObservableMethodBuilder<T> Create()
		{
			return default(TaskObservableMethodBuilder<T>);
		}

		public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine
		{
			if (stateMachine == null)
			{
				throw new ArgumentNullException("stateMachine");
			}
			stateMachine.MoveNext();
		}

		public void SetStateMachine(IAsyncStateMachine stateMachine)
		{
			if (_stateMachine != null)
			{
				throw new InvalidOperationException();
			}
			_stateMachine = stateMachine ?? throw new ArgumentNullException("stateMachine");
		}

		public void SetResult(T result)
		{
			if (_inner == null)
			{
				_inner = new TaskObservable(result);
			}
			else
			{
				_inner.SetResult(result);
			}
		}

		public void SetException(Exception exception)
		{
			if (exception == null)
			{
				throw new ArgumentNullException("exception");
			}
			if (_inner == null)
			{
				_inner = new TaskObservable(exception);
			}
			else
			{
				_inner.SetException(exception);
			}
		}

		public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			try
			{
				if (_stateMachine == null)
				{
					_ = Task;
					_stateMachine = stateMachine;
					_stateMachine.SetStateMachine(_stateMachine);
				}
				ref TAwaiter reference = ref awaiter;
				TAwaiter val = default(TAwaiter);
				if (val == null)
				{
					val = reference;
					reference = ref val;
				}
				reference.OnCompleted(_stateMachine.MoveNext);
			}
			catch (Exception exception)
			{
				Rethrow(exception);
			}
		}

		[SecuritySafeCritical]
		public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine
		{
			try
			{
				if (_stateMachine == null)
				{
					_ = Task;
					_stateMachine = stateMachine;
					_stateMachine.SetStateMachine(_stateMachine);
				}
				ref TAwaiter reference = ref awaiter;
				TAwaiter val = default(TAwaiter);
				if (val == null)
				{
					val = reference;
					reference = ref val;
				}
				reference.UnsafeOnCompleted(_stateMachine.MoveNext);
			}
			catch (Exception exception)
			{
				Rethrow(exception);
			}
		}

		private static void Rethrow(Exception exception)
		{
			Scheduler.Default.Schedule(exception, delegate(Exception ex, Action<Exception> recurse)
			{
				ex.Throw();
			});
		}
	}
}
namespace System.Threading.Tasks
{
	internal static class TaskExtensions
	{
		public static Task ContinueWithState<TState>(this Task task, Action<Task, TState> continuationAction, TState state, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken)
		{
			return task.ContinueWith(delegate(Task t, object? tupleObject)
			{
				var (action, arg) = ((Action<Task, TState>, TState))tupleObject;
				action(t, arg);
			}, (continuationAction, state), cancellationToken, continuationOptions, TaskScheduler.Default);
		}

		public static Task ContinueWithState<TResult, TState>(this Task<TResult> task, Action<Task<TResult>, TState> continuationAction, TState state, CancellationToken cancellationToken)
		{
			return task.ContinueWith(delegate(Task<TResult> t, object? tupleObject)
			{
				var (action, arg) = ((Action<Task<TResult>, TState>, TState))tupleObject;
				action(t, arg);
			}, (continuationAction, state), cancellationToken);
		}

		public static Task ContinueWithState<TResult, TState>(this Task<TResult> task, Action<Task<TResult>, TState> continuationAction, TState state, TaskContinuationOptions continuationOptions, CancellationToken cancellationToken)
		{
			return task.ContinueWith(delegate(Task<TResult> t, object? tupleObject)
			{
				var (action, arg) = ((Action<Task<TResult>, TState>, TState))tupleObject;
				action(t, arg);
			}, (continuationAction, state), cancellationToken, continuationOptions, TaskScheduler.Default);
		}
	}
}
namespace System.Reactive
{
	public sealed class AnonymousObservable<T> : ObservableBase<T>
	{
		private readonly Func<IObserver<T>, IDisposable> _subscribe;

		public AnonymousObservable(Func<IObserver<T>, IDisposable> subscribe)
		{
			_subscribe = subscribe ?? throw new ArgumentNullException("subscribe");
		}

		protected override IDisposable SubscribeCore(IObserver<T> observer)
		{
			return _subscribe(observer) ?? Disposable.Empty;
		}
	}
	public sealed class AnonymousObserver<T> : ObserverBase<T>
	{
		private readonly Action<T> _onNext;

		private readonly Action<Exception> _onError;

		private readonly Action _onCompleted;

		public AnonymousObserver(Action<T> onNext, Action<Exception> onError, Action onCompleted)
		{
			_onNext = onNext ?? throw new ArgumentNullException("onNext");
			_onError = onError ?? throw new ArgumentNullException("onError");
			_onCompleted = onCompleted ?? throw new ArgumentNullException("onCompleted");
		}

		public AnonymousObserver(Action<T> onNext)
			: this(onNext, Stubs.Throw, Stubs.Nop)
		{
		}

		public AnonymousObserver(Action<T> onNext, Action<Exception> onError)
			: this(onNext, onError, Stubs.Nop)
		{
		}

		public AnonymousObserver(Action<T> onNext, Action onCompleted)
			: this(onNext, Stubs.Throw, onCompleted)
		{
		}

		protected override void OnNextCore(T value)
		{
			_onNext(value);
		}

		protected override void OnErrorCore(Exception error)
		{
			_onError(error);
		}

		protected override void OnCompletedCore()
		{
			_onCompleted();
		}

		internal ISafeObserver<T> MakeSafe()
		{
			return new AnonymousSafeObserver<T>(_onNext, _onError, _onCompleted);
		}
	}
	internal sealed class AnonymousSafeObserver<T> : SafeObserver<T>
	{
		private readonly Action<T> _onNext;

		private readonly Action<Exception> _onError;

		private readonly Action _onCompleted;

		private int _isStopped;

		public AnonymousSafeObserver(Action<T> onNext, Action<Exception> onError, Action onCompleted)
		{
			_onNext = onNext;
			_onError = onError;
			_onCompleted = onCompleted;
		}

		public override void OnNext(T value)
		{
			if (_isStopped != 0)
			{
				return;
			}
			bool flag = false;
			try
			{
				_onNext(value);
				flag = true;
			}
			finally
			{
				if (!flag)
				{
					Dispose();
				}
			}
		}

		public override void OnError(Exception error)
		{
			if (Interlocked.Exchange(ref _isStopped, 1) == 0)
			{
				using (this)
				{
					_onError(error);
				}
			}
		}

		public override void OnCompleted()
		{
			if (Interlocked.Exchange(ref _isStopped, 1) == 0)
			{
				using (this)
				{
					_onCompleted();
				}
			}
		}
	}
	public class EventPattern<TEventArgs> : EventPattern<object, TEventArgs>
	{
		public EventPattern(object? sender, TEventArgs e)
			: base(sender, e)
		{
		}
	}
	public class EventPattern<TSender, TEventArgs> : IEquatable<EventPattern<TSender, TEventArgs>>, IEventPattern<TSender, TEventArgs>
	{
		public TSender? Sender { get; }

		public TEventArgs EventArgs { get; }

		public EventPattern(TSender? sender, TEventArgs e)
		{
			Sender = sender;
			EventArgs = e;
		}

		public void Deconstruct(out TSender? sender, out TEventArgs e)
		{
			TSender sender2 = Sender;
			TEventArgs eventArgs = EventArgs;
			sender = sender2;
			e = eventArgs;
		}

		public bool Equals(EventPattern<TSender, TEventArgs>? other)
		{
			if ((object)other == null)
			{
				return false;
			}
			if ((object)this == other)
			{
				return true;
			}
			if (EqualityComparer<TSender>.Default.Equals(Sender, other.Sender))
			{
				return EqualityComparer<TEventArgs>.Default.Equals(EventArgs, other.EventArgs);
			}
			return false;
		}

		public override bool Equals(object? obj)
		{
			return Equals(obj as EventPattern<TSender, TEventArgs>);
		}

		public override int GetHashCode()
		{
			TSender sender = Sender;
			int num = ((sender != null) ? sender.GetHashCode() : 0);
			TEventArgs eventArgs = EventArgs;
			int num2 = ((eventArgs != null) ? eventArgs.GetHashCode() : 0);
			return (num << 5) + (num ^ num2);
		}

		public static bool operator ==(EventPattern<TSender, TEventArgs> first, EventPattern<TSender, TEventArgs> second)
		{
			return object.Equals(first, second);
		}

		public static bool operator !=(EventPattern<TSender, TEventArgs> first, EventPattern<TSender, TEventArgs> second)
		{
			return !object.Equals(first, second);
		}
	}
	internal sealed class EventPatternSource<TEventArgs> : EventPatternSourceBase<object, TEventArgs>, IEventPatternSource<TEventArgs>
	{
		event EventHandler<TEventArgs> IEventPatternSource<TEventArgs>.OnNext
		{
			add
			{
				EventHandler<TEventArgs> value2 = value;
				Add(value2, delegate(object? o, TEventArgs e)
				{
					value2(o, e);
				});
			}
			remove
			{
				Remove(value);
			}
		}

		public EventPatternSource(IObservable<EventPattern<object, TEventArgs>> source, Action<Action<object?, TEventArgs>, EventPattern<object, TEventArgs>> invokeHandler)
			: base(source, invokeHandler)
		{
		}
	}
	public abstract class EventPatternSourceBase<TSender, TEventArgs>
	{
		private sealed class Observer : ObserverBase<EventPattern<TSender, TEventArgs>>, ISafeObserver<EventPattern<TSender, TEventArgs>>, IObserver<EventPattern<TSender, TEventArgs>>, IDisposable
		{
			private bool _isDone;

			private bool _isAdded;

			private readonly Delegate _handler;

			private readonly object _gate = new object();

			private readonly Action<TSender?, TEventArgs> _invoke;

			private readonly EventPatternSourceBase<TSender, TEventArgs> _sourceBase;

			public Observer(EventPatternSourceBase<TSender, TEventArgs> sourceBase, Delegate handler, Action<TSender?, TEventArgs> invoke)
			{
				_handler = handler;
				_invoke = invoke;
				_sourceBase = sourceBase;
			}

			protected override void OnNextCore(EventPattern<TSender, TEventArgs> value)
			{
				_sourceBase._invokeHandler(_invoke, value);
			}

			protected override void OnErrorCore(Exception error)
			{
				Remove();
				error.Throw();
			}

			protected override void OnCompletedCore()
			{
				Remove();
			}

			private void Remove()
			{
				lock (_gate)
				{
					if (_isAdded)
					{
						_sourceBase.Remove(_handler);
					}
					else
					{
						_isDone = true;
					}
				}
			}

			public void SetResource(IDisposable resource)
			{
				lock (_gate)
				{
					if (!_isDone)
					{
						_sourceBase.Add(_handler, resource);
						_isAdded = true;
					}
				}
			}
		}

		private readonly IObservable<EventPattern<TSender, TEventArgs>> _source;

		private readonly Dictionary<Delegate, Stack<IDisposable>> _subscriptions;

		private readonly Action<Action<TSender?, TEventArgs>, EventPattern<TSender, TEventArgs>> _invokeHandler;

		protected EventPatternSourceBase(IObservable<EventPattern<TSender, TEventArgs>> source, Action<Action<TSender?, TEventArgs>, EventPattern<TSender, TEventArgs>> invokeHandler)
		{
			_source = source ?? throw new ArgumentNullException("source");
			_invokeHandler = invokeHandler ?? throw new ArgumentNullException("invokeHandler");
			_subscriptions = new Dictionary<Delegate, Stack<IDisposable>>();
		}

		protected void Add(Delegate handler, Action<TSender?, TEventArgs> invoke)
		{
			if ((object)handler == null)
			{
				throw new ArgumentNullException("handler");
			}
			if (invoke == null)
			{
				throw new ArgumentNullException("invoke");
			}
			Observer observer = new Observer(this, handler, invoke);
			observer.SetResource(_source.Subscribe(observer));
		}

		private void Add(Delegate handler, IDisposable disposable)
		{
			lock (_subscriptions)
			{
				if (!_subscriptions.TryGetValue(handler, out Stack<IDisposable> value))
				{
					value = (_subscriptions[handler] = new Stack<IDisposable>());
				}
				value.Push(disposable);
			}
		}

		protected void Remove(Delegate handler)
		{
			if ((object)handler == null)
			{
				throw new ArgumentNullException("handler");
			}
			IDisposable disposable = null;
			lock (_subscriptions)
			{
				if (_subscriptions.TryGetValue(handler, out Stack<IDisposable> value))
				{
					disposable = value.Pop();
					if (value.Count == 0)
					{
						_subscriptions.Remove(handler);
					}
				}
			}
			disposable?.Dispose();
		}
	}
	internal sealed class EventSource<T> : IEventSource<T>
	{
		private readonly IObservable<T> _source;

		private readonly Dictionary<Delegate, Stack<IDisposable>> _subscriptions;

		private readonly Action<Action<T>, T> _invokeHandler;

		public event Action<T> OnNext
		{
			add
			{
				Action<T> value2 = value;
				object gate = new object();
				bool isAdded = false;
				bool isDone = false;
				Action remove = delegate
				{
					lock (gate)
					{
						if (isAdded)
						{
							Remove(value2);
						}
						else
						{
							isDone = true;
						}
					}
				};
				IDisposable disposable = _source.Subscribe(delegate(T x)
				{
					_invokeHandler(value2, x);
				}, delegate(Exception ex)
				{
					remove();
					ex.Throw();
				}, remove);
				lock (gate)
				{
					if (!isDone)
					{
						Add(value2, disposable);
						isAdded = true;
					}
				}
			}
			remove
			{
				Remove(value);
			}
		}

		public EventSource(IObservable<T> source, Action<Action<T>, T> invokeHandler)
		{
			_source = source;
			_invokeHandler = invokeHandler;
			_subscriptions = new Dictionary<Delegate, Stack<IDisposable>>();
		}

		private void Add(Delegate handler, IDisposable disposable)
		{
			lock (_subscriptions)
			{
				if (!_subscriptions.TryGetValue(handler, out Stack<IDisposable> value))
				{
					value = (_subscriptions[handler] = new Stack<IDisposable>());
				}
				value.Push(disposable);
			}
		}

		private void Remove(Delegate handler)
		{
			IDisposable disposable = null;
			lock (_subscriptions)
			{
				Stack<IDisposable> value = new Stack<IDisposable>();
				if (_subscriptions.TryGetValue(handler, out value))
				{
					disposable = value.Pop();
					if (value.Count == 0)
					{
						_subscriptions.Remove(handler);
					}
				}
			}
			disposable?.Dispose();
		}
	}
	[Experimental]
	[AttributeUsage(AttributeTargets.All)]
	public sealed class ExperimentalAttribute : Attribute
	{
	}
	public interface IEventPattern<out TSender, out TEventArgs>
	{
		TSender? Sender { get; }

		TEventArgs EventArgs { get; }
	}
	public interface IEventPatternSource<TEventArgs>
	{
		event EventHandler<TEventArgs> OnNext;
	}
	public interface IEventSource<out T>
	{
		event Action<T> OnNext;
	}
	internal sealed class AnonymousEnumerable<T> : IEnumerable<T>, IEnumerable
	{
		private readonly Func<IEnumerator<T>> _getEnumerator;

		public AnonymousEnumerable(Func<IEnumerator<T>> getEnumerator)
		{
			_getEnumerator = getEnumerator;
		}

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

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _getEnumerator();
		}
	}
	internal sealed class AsyncLockObserver<T> : ObserverBase<T>
	{
		private readonly AsyncLock _gate;

		private readonly IObserver<T> _observer;

		public AsyncLockObserver(IObserver<T> observer, AsyncLock gate)
		{
			_gate = gate;
			_observer = observer;
		}

		protected override void OnNextCore(T value)
		{
			_gate.Wait((_observer, value), delegate((IObserver<T> _observer, T value) tuple)
			{
				tuple._observer.OnNext(tuple.value);
			});
		}

		protected override void OnErrorCore(Exception exception)
		{
			_gate.Wait((_observer, exception), delegate((IObserver<T> _observer, Exception exception) tuple)
			{
				tuple._observer.OnError(tuple.exception);
			});
		}

		protected override void OnCompletedCore()
		{
			_gate.Wait(_observer, delegate(IObserver<T> closureObserver)
			{
				closureObserver.OnCompleted();
			});
		}
	}
	internal sealed class AutoDetachObserver<T> : ObserverBase<T>, ISafeObserver<T>, IObserver<T>, IDisposable
	{
		private readonly IObserver<T> _observer;

		private SingleAssignmentDisposableValue _disposable;

		public AutoDetachObserver(IObserver<T> observer)
		{
			_observer = observer;
		}

		public void SetResource(IDisposable resource)
		{
			_disposable.Disposable = resource;
		}

		protected override void OnNextCore(T value)
		{
			bool flag = false;
			try
			{
				_observer.OnNext(value);
				flag = true;
			}
			finally
			{
				if (!flag)
				{
					Dispose();
				}
			}
		}

		protected override void OnErrorCore(Exception exception)
		{
			try
			{
				_observer.OnError(exception);
			}
			finally
			{
				Dispose();
			}
		}

		protected override void OnCompletedCore()
		{
			try
			{
				_observer.OnCompleted();
			}
			finally
			{
				Dispose();
			}
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			if (disposing)
			{
				_disposable.Dispose();
			}
		}
	}
	internal sealed class BinaryObserver<TLeft, TRight> : IObserver<Either<Notification<TLeft>, Notification<TRight>>>
	{
		public IObserver<TLeft> LeftObserver { get; }

		public IObserver<TRight> RightObserver { get; }

		public BinaryObserver(IObserver<TLeft> leftObserver, IObserver<TRight> rightObserver)
		{
			LeftObserver = leftObserver;
			RightObserver = rightObserver;
		}

		public BinaryObserver(Action<Notification<TLeft>> left, Action<Notification<TRight>> right)
			: this(left.ToObserver(), right.ToObserver())
		{
		}

		void IObserver<Either<Notification<TLeft>, Notification<TRight>>>.OnNext(Either<Notification<TLeft>, Notification<TRight>> value)
		{
			value.Switch(delegate(Notification<TLeft> left)
			{
				left.Accept(LeftObserver);
			}, delegate(Notification<TRight> right)
			{
				right.Accept(RightObserver);
			});
		}

		void IObserver<Either<Notification<TLeft>, Notification<TRight>>>.OnError(Exception exception)
		{
		}

		void IObserver<Either<Notification<TLeft>, Notification<TRight>>>.OnCompleted()
		{
		}
	}
	internal sealed class CheckedObserver<T> : IObserver<T>
	{
		private readonly IObserver<T> _observer;

		private int _state;

		private const int Idle = 0;

		private const int Busy = 1;

		private const int Done = 2;

		public CheckedObserver(IObserver<T> observer)
		{
			_observer = observer;
		}

		public void OnNext(T value)
		{
			CheckAccess();
			try
			{
				_observer.OnNext(value);
			}
			finally
			{
				Interlocked.Exchange(ref _state, 0);
			}
		}

		public void OnError(Exception error)
		{
			CheckAccess();
			try
			{
				_observer.OnError(error);
			}
			finally
			{
				Interlocked.Exchange(ref _state, 2);
			}
		}

		public void OnCompleted()
		{
			CheckAccess();
			try
			{
				_observer.OnCompleted();
			}
			finally
			{
				Interlocked.Exchange(ref _state, 2);
			}
		}

		private void CheckAccess()
		{
			switch (Interlocked.CompareExchange(ref _state, 1, 0))
			{
			case 1:
				throw new InvalidOperationException(Strings_Core.REENTRANCY_DETECTED);
			case 2:
				throw new InvalidOperationException(Strings_Core.OBSERVER_TERMINATED);
			}
		}
	}
	internal abstract class ConcatSink<TSource> : TailRecursiveSink<TSource>
	{
		protected ConcatSink(IObserver<TSource> observer)
			: base(observer)
		{
		}

		protected override IEnumerable<IObservable<TSource>>? Extract(IObservable<TSource> source)
		{
			return (source as IConcatenatable<TSource>)?.GetSources();
		}

		public override void OnCompleted()
		{
			Recurse();
		}
	}
	internal static class Constants_Core
	{
		private const string ObsoleteRefactoring = "This property is no longer supported due to refactoring of the API surface and elimination of platform-specific dependencies.";

		public const string ObsoleteSchedulerNewthread = "This property is no longer supported due to refactoring of the API surface and elimination of platform-specific dependencies. Please use NewThreadScheduler.Default to obtain an instance of this scheduler type.";

		public const string ObsoleteSchedulerTaskpool = "This property is no longer supported due to refactoring of the API surface and elimination of platform-specific dependencies. Please use TaskPoolScheduler.Default to obtain an instance of this scheduler type.";

		public const string ObsoleteSchedulerThreadpool = "This property is no longer supported due to refactoring of the API surface and elimination of platform-specific dependencies. Consider using Scheduler.Default to obtain the platform's most appropriate pool-based scheduler. In order to access a specific pool-based scheduler, please add a reference to the System.Reactive.PlatformServices assembly for your target platform and use the appropriate scheduler in the System.Reactive.Concurrency namespace.";

		public const string ObsoleteSchedulerequired = "This instance property is no longer supported. Use CurrentThreadScheduler.IsScheduleRequired instead.";

		internal const string AsQueryableTrimIncompatibilityMessage = "This type uses Queryable.AsQueryable, which is not compatible with trimming because expressions referencing IQueryable extension methods can get rebound to IEnumerable extension methods, and those IEnumerable methods might be trimmed.";

		internal const string EventReflectionTrimIncompatibilityMessage = "This member uses reflection to discover event members and associated delegate types.";
	}
	internal static class Constants_Linq
	{
		public const string UseAsync = "This blocking operation is no longer supported. Instead, use the async version in combination with C# and Visual Basic async/await support. In case you need a blocking operation, use Wait or convert the resulting observable sequence to a Task object and block.";

		public const string UseTaskFromAsyncPattern = "This conversion is no longer supported. Replace use of the Begin/End asynchronous method pair with a new Task-based async method, and convert the result using ToObservable. If no Task-based async method is available, use Task.Factory.FromAsync to obtain a Task object.";
	}
	internal abstract class Either<TLeft, TRight>
	{
		public sealed class Left : Either<TLeft, TRight>, IEquatable<Left>
		{
			public TLeft Value { get; }

			public Left(TLeft value)
			{
				Value = value;
			}

			public override TResult Switch<TResult>(Func<TLeft, TResult> caseLeft, Func<TRight, TResult> caseRight)
			{
				return caseLeft(Value);
			}

			public override void Switch(Action<TLeft> caseLeft, Action<TRight> caseRight)
			{
				caseLeft(Value);
			}

			public bool Equals(Left? other)
			{
				if (other == this)
				{
					return true;
				}
				if (other == null)
				{
					return false;
				}
				return EqualityComparer<TLeft>.Default.Equals(Value, other.Value);
			}

			public override bool Equals(object? obj)
			{
				return Equals(obj as Either<TLeft, TRight>.Left);
			}

			public override int GetHashCode()
			{
				TLeft value = Value;
				if (value == null)
				{
					return 0;
				}
				return value.GetHashCode();
			}

			public override string ToString()
			{
				return string.Format(CultureInfo.CurrentCulture, "Left({0})", Value);
			}
		}

		public sealed class Right : Either<TLeft, TRight>, IEquatable<Right>
		{
			public TRight Value { get; }

			public Right(TRight value)
			{
				Value = value;
			}

			public override TResult Switch<TResult>(Func<TLeft, TResult> caseLeft, Func<TRight, TResult> caseRight)
			{
				return caseRight(Value);
			}

			public override void Switch(Action<TLeft> caseLeft, Action<TRight> caseRight)
			{
				caseRight(Value);
			}

			public bool Equals(Right? other)
			{
				if (other == this)
				{
					return true;
				}
				if (other == null)
				{
					return false;
				}
				return EqualityComparer<TRight>.Default.Equals(Value, other.Value);
			}

			public override bool Equals(object? obj)
			{
				return Equals(obj as Either<TLeft, TRight>.Right);
			}

			public override int GetHashCode()
			{
				TRight value = Value;
				if (value == null)
				{
					return 0;
				}
				return value.GetHashCode();
			}

			public override string ToString()
			{
				return string.Format(CultureInfo.CurrentCulture, "Right({0})", Value);
			}
		}

		private Either()
		{
		}

		public static Either<TLeft, TRight> CreateLeft(TLeft value)
		{
			return new Left(value);
		}

		public static Either<TLeft, TRight> CreateRight(TRight value)
		{
			return new Right(value);
		}

		public abstract TResult Switch<TResult>(Func<TLeft, TResult> caseLeft, Func<TRight, TResult> caseRight);

		public abstract void Switch(Action<TLeft> caseLeft, Action<TRight> caseRight);
	}
	internal static class ExceptionHelper
	{
		public static Exception Terminated { get; } = new EndOfStreamException("On[Error|Completed]");


		public static bool TrySetException(ref Exception? field, Exception ex)
		{
			return Interlocked.CompareExchange(ref field, ex, null) == null;
		}
	}
	internal static class ExceptionHelpers
	{
		private static readonly Lazy<IExceptionServices> Services = new Lazy<IExceptionServices>(Initialize);

		[DoesNotReturn]
		public static void Throw(this Exception exception)
		{
			Services.Value.Rethrow(exception);
		}

		private static IExceptionServices Initialize()
		{
			return PlatformEnlightenmentProvider.Current.GetService<IExceptionServices>(Array.Empty<object>()) ?? new DefaultExceptionServices();
		}
	}
	internal sealed class Grouping<TKey, TElement> : Dictionary<TKey, Subject<TElement>>
	{
		public Grouping(IEqualityComparer<TKey> comparer)
			: base(comparer)
		{
		}

		public Grouping(int capacity, IEqualityComparer<TKey> comparer)
			: base(capacity, comparer)
		{
		}
	}
	internal static class HalfSerializer
	{
		public static void ForwardOnNext<T>(ISink<T> sink, T item, ref int wip, ref Exception? error)
		{
			if (Interlocked.CompareExchange(ref wip, 1, 0) == 0)
			{
				sink.ForwardOnNext(item);
				if (Interlocked.Decrement(ref wip) != 0)
				{
					Exception ex = error;
					if (ex != ExceptionHelper.Terminated)
					{
						error = ExceptionHelper.Terminated;
						sink.ForwardOnError(ex);
					}
					else
					{
						sink.ForwardOnCompleted();
					}
				}
			}
			else if (error == null)
			{
				Trace.TraceWarning("OnNext called while another OnNext call was in progress on the same Observer.");
			}
		}

		public static void ForwardOnError<T>(ISink<T> sink, Exception ex, ref int wip, ref Exception? error)
		{
			if (ExceptionHelper.TrySetException(ref error, ex) && Interlocked.Increment(ref wip) == 1)
			{
				error = ExceptionHelper.Terminated;
				sink.ForwardOnError(ex);
			}
		}

		public static void ForwardOnCompleted<T>(ISink<T> sink, ref int wip, ref Exception? error)
		{
			if (ExceptionHelper.TrySetException(ref error, ExceptionHelper.Terminated) && Interlocked.Increment(ref wip) == 1)
			{
				sink.ForwardOnCompleted();
			}
		}
	}
	internal static class Helpers
	{
		public static bool All(this bool[] values)
		{
			for (int i = 0; i < values.Length; i++)
			{
				if (!values[i])
				{
					return false;
				}
			}
			return true;
		}

		public static bool AllExcept(this bool[] values, int index)
		{
			for (int i = 0; i < values.Length; i++)
			{
				if (i != index && !values[i])
				{
					return false;
				}
			}
			return true;
		}
	}
	internal interface IConcatenatable<out TSource>
	{
		IEnumerable<IObservable<TSource>> GetSources();
	}
	internal abstract class IdentitySink<T> : Sink<T, T>
	{
		protected IdentitySink(IObserver<T> observer)
			: base(observer)
		{
		}

		public override void OnNext(T value)
		{
			ForwardOnNext(value);
		}
	}
	internal interface IEvaluatableObservable<out T>
	{
		IObservable<T> Eval();
	}
	internal sealed class ImmutableList<T>
	{
		public static readonly ImmutableList<T> Empty = new ImmutableList<T>();

		private readonly T[] _data;

		public T[] Data => _data;

		private ImmutableList()
		{
			_data = Array.Empty<T>();
		}

		public ImmutableList(T[] data)
		{
			_data = data;
		}

		public ImmutableList<T> Add(T value)
		{
			T[] array = new T[_data.Length + 1];
			Array.Copy(_data, array, _data.Length);
			array[_data.Length] = value;
			return new ImmutableList<T>(array);
		}

		public ImmutableList<T> Remove(T value)
		{
			int num = Array.IndexOf(_data, value);
			if (num < 0)
			{
				return this;
			}
			int num2 = _data.Length;
			if (num2 == 1)
			{
				return Empty;
			}
			T[] array = new T[num2 - 1];
			Array.Copy(_data, 0, array, 0, num);
			Array.Copy(_data, num + 1, array, num, num2 - num - 1);
			return new ImmutableList<T>(array);
		}
	}
	internal interface ISafeObserver<in T> : IObserver<T>, IDisposable
	{
		void SetResource(IDisposable resource);
	}
	internal sealed class Lookup<K, E> : ILookup<K, E>, IEnumerable<IGrouping<K, E>>, IEnumerable
	{
		private sealed class Grouping : IGrouping<K, E>, IEnumerable<E>, IEnumerable
		{
			private readonly KeyValuePair<K, List<E>> _keyValuePair;

			public K Key => _keyValuePair.Key;

			public Grouping(KeyValuePair<K, List<E>> keyValuePair)
			{
				_keyValuePair = keyValuePair;
			}

			public IEnumerator<E> GetEnumerator()
			{
				return _keyValuePair.Value.GetEnumerator();
			}

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

		private readonly Dictionary<K, List<E>> _dictionary;

		public int Count => _dictionary.Count;

		public IEnumerable<E> this[K key]
		{
			get
			{
				if (!_dictionary.TryGetValue(key, out var value))
				{
					return Enumerable.Empty<E>();
				}
				return Hide(value);
			}
		}

		public Lookup(IEqualityComparer<K> comparer)
		{
			_dictionary = new Dictionary<K, List<E>>(comparer);
		}

		public void Add(K key, E element)
		{
			if (!_dictionary.TryGetValue(key, out var value))
			{
				value = (_dictionary[key] = new List<E>());
			}
			value.Add(element);
		}

		public bool Contains(K key)
		{
			return _dictionary.ContainsKey(key);
		}

		private static IEnumerable<E> Hide(List<E> elements)
		{
			return elements.Skip(0);
		}

		public IEnumerator<IGrouping<K, E>> GetEnumerator()
		{
			foreach (KeyValuePair<K, List<E>> item in _dictionary)
			{
				yield return new Grouping(item);
			}
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return GetEnumerator();
		}
	}
	internal sealed class Map<TKey, TValue>
	{
		private const int DefaultConcurrencyMultiplier = 4;

		private readonly ConcurrentDictionary<TKey, TValue> _map;

		private static int DefaultConcurrencyLevel => 4 * Environment.ProcessorCount;

		public IEnumerable<TValue> Values => _map.Values.ToArray();

		public Map(int? capacity, IEqualityComparer<TKey> comparer)
		{
			if (capacity.HasValue)
			{
				_map = new ConcurrentDictionary<TKey, TValue>(DefaultConcurrencyLevel, capacity.Value, comparer);
			}
			else
			{
				_map = new ConcurrentDictionary<TKey, TValue>(comparer);
			}
		}

		public TValue GetOrAdd(TKey key, Func<TValue> valueFactory, out bool added)
		{
			added = false;
			TValue val = default(TValue);
			bool flag = false;
			TValue value;
			while (!_map.TryGetValue(key, out value))
			{
				if (!flag)
				{
					val = valueFactory();
					flag = true;
				}
				if (_map.TryAdd(key, val))
				{
					added = true;
					return val;
				}
			}
			return value;
		}

		public bool Remove(TKey key)
		{
			TValue value;
			return _map.TryRemove(key, out value);
		}
	}
	internal sealed class NopObserver<T> : IObserver<T>
	{
		public static readonly IObserver<T> Instance = new NopObserver<T>();

		public void OnCompleted()
		{
		}

		public void OnError(Exception error)
		{
		}

		public void OnNext(T value)
		{
		}
	}
	internal sealed class PriorityQueue<T> where T : IComparable<T>
	{
		private struct IndexedItem : IComparable<IndexedItem>
		{
			public T Value;

			public long Id;

			public int CompareTo(IndexedItem other)
			{
				int num = Value.CompareTo(other.Value);
				if (num == 0)
				{
					num = Id.CompareTo(other.Id);
				}
				return num;
			}
		}

		private long _count = long.MinValue;

		private IndexedItem[] _items;

		private int _size;

		public int Count => _size;

		public PriorityQueue()
			: this(16)
		{
		}

		public PriorityQueue(int capacity)
		{
			_items = new IndexedItem[capacity];
			_size = 0;
		}

		private bool IsHigherPriority(int left, int right)
		{
			return _items[left].CompareTo(_items[right]) < 0;
		}

		private int Percolate(int index)
		{
			if (index >= _size || index < 0)
			{
				return index;
			}
			int num = (index - 1) / 2;
			while (num >= 0 && num != index && IsHigherPriority(index, num))
			{
				ref IndexedItem reference = ref _items[num];
				ref IndexedItem reference2 = ref _items[index];
				IndexedItem indexedItem = _items[index];
				IndexedItem indexedItem2 = _items[num];
				reference = indexedItem;
				reference2 = indexedItem2;
				index = num;
				num = (index - 1) / 2;
			}
			return index;
		}

		private void Heapify(int index)
		{
			if (index >= _size || index < 0)
			{
				return;
			}
			while (true)
			{
				int num = 2 * index + 1;
				int num2 = 2 * index + 2;
				int num3 = index;
				if (num < _size && IsHigherPriority(num, num3))
				{
					num3 = num;
				}
				if (num2 < _size && IsHigherPriority(num2, num3))
				{
					num3 = num2;
				}
				if (num3 != index)
				{
					ref IndexedItem reference = ref _items[num3];
					ref IndexedItem reference2 = ref _items[index];
					IndexedItem indexedItem = _items[index];
					IndexedItem indexedItem2 = _items[num3];
					reference = indexedItem;
					reference2 = indexedItem2;
					index = num3;
					continue;
				}
				break;
			}
		}

		public T Peek()
		{
			if (_size == 0)
			{
				throw new InvalidOperationException(Strings_Core.HEAP_EMPTY);
			}
			return _items[0].Value;
		}

		private void RemoveAt(int index)
		{
			_items[index] = _items[--_size];
			_items[_size] = default(IndexedItem);
			if (Percolate(index) == index)
			{
				Heapify(index);
			}
			if (_size < _items.Length / 4)
			{
				IndexedItem[] items = _items;
				_items = new IndexedItem[_items.Length / 2];
				Array.Copy(items, 0, _items, 0, _size);
			}
		}

		public T Dequeue()
		{
			T result = Peek();
			RemoveAt(0);
			return result;
		}

		public void Enqueue(T item)
		{
			if (_size >= _items.Length)
			{
				IndexedItem[] items = _items;
				_items = new IndexedItem[_items.Length * 2];
				Array.Copy(items, _items, items.Length);
			}
			int num = _size++;
			_items[num] = new IndexedItem
			{
				Value = item,
				Id = ++_count
			};
			Percolate(num);
		}

		public bool Remove(T item)
		{
			for (int i = 0; i < _size; i++)
			{
				if (EqualityComparer<T>.Default.Equals(_items[i].Value, item))
				{
					RemoveAt(i);
					return true;
				}
			}
			return false;
		}
	}
	internal interface IProducer<out TSource> : IObservable<TSource>
	{
		IDisposable SubscribeRaw(IObserver<TSource> observer, bool enableSafeguard);
	}
	internal abstract class BasicProducer<TSource> : IProducer<TSource>, IObservable<TSource>
	{
		public IDisposable Subscribe(IObserver<TSource> observer)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			return SubscribeRaw(observer, enableSafeguard: true);
		}

		public IDisposable SubscribeRaw(IObserver<TSource> observer, bool enableSafeguard)
		{
			ISafeObserver<TSource> safeObserver = null;
			if (enableSafeguard)
			{
				observer = (safeObserver = SafeObserver<TSource>.Wrap(observer));
			}
			IDisposable disposable;
			if (CurrentThreadScheduler.IsScheduleRequired)
			{
				SingleAssignmentDisposable singleAssignmentDisposable = new SingleAssignmentDisposable();
				CurrentThreadScheduler.Instance.ScheduleAction((this, singleAssignmentDisposable, observer), ((BasicProducer<TSource> @this, SingleAssignmentDisposable runAssignable, IObserver<TSource> observer) tuple) => tuple.runAssignable.Disposable = tuple.@this.Run(tuple.observer));
				disposable = singleAssignmentDisposable;
			}
			else
			{
				disposable = Run(observer);
			}
			safeObserver?.SetResource(disposable);
			return disposable;
		}

		protected abstract IDisposable Run(IObserver<TSource> observer);
	}
	internal abstract class Producer<TTarget, TSink> : IProducer<TTarget>, IObservable<TTarget> where TSink : IDisposable
	{
		public IDisposable Subscribe(IObserver<TTarget> observer)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			return SubscribeRaw(observer, enableSafeguard: true);
		}

		public IDisposable SubscribeRaw(IObserver<TTarget> observer, bool enableSafeguard)
		{
			ISafeObserver<TTarget> safeObserver = null;
			if (enableSafeguard)
			{
				observer = (safeObserver = SafeObserver<TTarget>.Wrap(observer));
			}
			TSink val = CreateSink(observer);
			safeObserver?.SetResource(val);
			if (CurrentThreadScheduler.IsScheduleRequired)
			{
				CurrentThreadScheduler.Instance.ScheduleAction((this, val), delegate((Producer<TTarget, TSink> @this, TSink sink) tuple)
				{
					tuple.@this.Run(tuple.sink);
				});
			}
			else
			{
				Run(val);
			}
			return val;
		}

		protected abstract void Run(TSink sink);

		protected abstract TSink CreateSink(IObserver<TTarget> observer);
	}
	internal static class ReflectionUtils
	{
		public static TDelegate CreateDelegate<TDelegate>(object o, MethodInfo method)
		{
			return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), o);
		}

		public static Delegate CreateDelegate(Type delegateType, object o, MethodInfo method)
		{
			return method.CreateDelegate(delegateType, o);
		}

		[RequiresUnreferencedCode("This member uses reflection to discover event members and associated delegate types.")]
		public static void GetEventMethods<TSender, TEventArgs>(Type targetType, object? target, string eventName, out MethodInfo addMethod, out MethodInfo removeMethod, out Type delegateType, out bool isWinRT)
		{
			EventInfo @event;
			if (target == null)
			{
				@event = targetType.GetEvent(eventName, BindingFlags.Static | BindingFlags.Public);
				if (@event == null)
				{
					throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.COULD_NOT_FIND_STATIC_EVENT, eventName, targetType.FullName));
				}
			}
			else
			{
				@event = targetType.GetEvent(eventName, BindingFlags.Instance | BindingFlags.Public);
				if (@event == null)
				{
					throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.COULD_NOT_FIND_INSTANCE_EVENT, eventName, targetType.FullName));
				}
			}
			addMethod = @event.GetAddMethod() ?? throw new InvalidOperationException(Strings_Linq.EVENT_MISSING_ADD_METHOD);
			removeMethod = @event.GetRemoveMethod() ?? throw new InvalidOperationException(Strings_Linq.EVENT_MISSING_REMOVE_METHOD);
			ParameterInfo[] parameters = addMethod.GetParameters();
			if (parameters.Length != 1)
			{
				throw new InvalidOperationException(Strings_Linq.EVENT_ADD_METHOD_SHOULD_TAKE_ONE_PARAMETER);
			}
			ParameterInfo[] parameters2 = removeMethod.GetParameters();
			if (parameters2.Length != 1)
			{
				throw new InvalidOperationException(Strings_Linq.EVENT_REMOVE_METHOD_SHOULD_TAKE_ONE_PARAMETER);
			}
			isWinRT = false;
			if (IsWinRTEventRegistrationTokenType(addMethod.ReturnType))
			{
				isWinRT = true;
				if (IsWinRTEventRegistrationTokenType(parameters2[0].ParameterType))
				{
					throw new InvalidOperationException(Strings_Linq.EVENT_WINRT_REMOVE_METHOD_SHOULD_TAKE_ERT);
				}
			}
			delegateType = parameters[0].ParameterType;
			MethodInfo? method = delegateType.GetMethod("Invoke");
			ParameterInfo[] parameters3 = method.GetParameters();
			if (parameters3.Length != 2)
			{
				throw new InvalidOperationException(Strings_Linq.EVENT_PATTERN_REQUIRES_TWO_PARAMETERS);
			}
			if (!typeof(TSender).IsAssignableFrom(parameters3[0].ParameterType))
			{
				throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.EVENT_SENDER_NOT_ASSIGNABLE, typeof(TSender).FullName));
			}
			if (!typeof(TEventArgs).IsAssignableFrom(parameters3[1].ParameterType))
			{
				throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Linq.EVENT_ARGS_NOT_ASSIGNABLE, typeof(TEventArgs).FullName));
			}
			if (method.ReturnType != typeof(void))
			{
				throw new InvalidOperationException(Strings_Linq.EVENT_MUST_RETURN_VOID);
			}
		}

		private static bool IsWinRTEventRegistrationTokenType(Type t)
		{
			if (t.Name == "EventRegistrationToken")
			{
				if (!(t.Namespace == "System.Runtime.InteropServices.WindowsRuntime"))
				{
					return t.Namespace == "WinRT";
				}
				return true;
			}
			return false;
		}
	}
	internal abstract class SafeObserver<TSource> : ISafeObserver<TSource>, IObserver<TSource>, IDisposable
	{
		private sealed class WrappingSafeObserver : SafeObserver<TSource>
		{
			private readonly IObserver<TSource> _observer;

			public WrappingSafeObserver(IObserver<TSource> observer)
			{
				_observer = observer;
			}

			public override void OnNext(TSource value)
			{
				bool flag = false;
				try
				{
					_observer.OnNext(value);
					flag = true;
				}
				finally
				{
					if (!flag)
					{
						Dispose();
					}
				}
			}

			public override void OnError(Exception error)
			{
				using (this)
				{
					_observer.OnError(error);
				}
			}

			public override void OnCompleted()
			{
				using (this)
				{
					_observer.OnCompleted();
				}
			}
		}

		private SingleAssignmentDisposableValue _disposable;

		public static ISafeObserver<TSource> Wrap(IObserver<TSource> observer)
		{
			if (observer is AnonymousObserver<TSource> anonymousObserver)
			{
				return anonymousObserver.MakeSafe();
			}
			return new WrappingSafeObserver(observer);
		}

		public abstract void OnNext(TSource value);

		public abstract void OnError(Exception error);

		public abstract void OnCompleted();

		public void SetResource(IDisposable resource)
		{
			_disposable.Disposable = resource;
		}

		public void Dispose()
		{
			Dispose(disposing: true);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (disposing)
			{
				_disposable.Dispose();
			}
		}
	}
	internal class ScheduledObserver<T> : ObserverBase<T>, IScheduledObserver<T>, IObserver<T>, IDisposable
	{
		private sealed class SemaphoreSlimRelease : IDisposable
		{
			private volatile SemaphoreSlim? _dispatcherEvent;

			public SemaphoreSlimRelease(SemaphoreSlim dispatcherEvent)
			{
				_dispatcherEvent = dispatcherEvent;
			}

			public void Dispose()
			{
				Interlocked.Exchange(ref _dispatcherEvent, null)?.Release();
			}
		}

		private int _state;

		private const int Stopped = 0;

		private const int Running = 1;

		private const int Pending = 2;

		private const int Faulted = 9;

		private readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();

		private bool _failed;

		private Exception? _error;

		private bool _completed;

		private readonly IObserver<T> _observer;

		private readonly IScheduler _scheduler;

		private readonly ISchedulerLongRunning? _longRunning;

		private SerialDisposableValue _disposable;

		private readonly object _dispatcherInitGate = new object();

		private readonly SemaphoreSlim? _dispatcherEvent;

		private readonly IDisposable? _dispatcherEventRelease;

		private IDisposable? _dispatcherJob;

		public ScheduledObserver(IScheduler scheduler, IObserver<T> observer)
		{
			_scheduler = scheduler;
			_observer = observer;
			_longRunning = _scheduler.AsLongRunning();
			if (_longRunning != null)
			{
				_dispatcherEvent = new SemaphoreSlim(0);
				_dispatcherEventRelease = new SemaphoreSlimRelease(_dispatcherEvent);
			}
		}

		private void EnsureDispatcher()
		{
			if (_dispatcherJob != null)
			{
				return;
			}
			lock (_dispatcherInitGate)
			{
				if (_dispatcherJob == null)
				{
					_dispatcherJob = _longRunning.ScheduleLongRunning(Dispatch);
					_disposable.Disposable = StableCompositeDisposable.Create(_dispatcherJob, _dispatcherEventRelease);
				}
			}
		}

		private void Dispatch(ICancelable cancel)
		{
			do
			{
				_dispatcherEvent.Wait();
				if (cancel.IsDisposed)
				{
					return;
				}
				T result;
				while (_queue.TryDequeue(out result))
				{
					try
					{
						_observer.OnNext(result);
					}
					catch
					{
						T result2;
						while (_queue.TryDequeue(out result2))
						{
						}
						throw;
					}
					_dispatcherEvent.Wait();
					if (cancel.IsDisposed)
					{
						return;
					}
				}
				if (_failed)
				{
					_observer.OnError(_error);
					Dispose();
					return;
				}
			}
			while (!_completed);
			_observer.OnCompleted();
			Dispose();
		}

		public void EnsureActive()
		{
			EnsureActive(1);
		}

		public void EnsureActive(int n)
		{
			if (_longRunning != null)
			{
				if (n > 0)
				{
					_dispatcherEvent.Release(n);
				}
				EnsureDispatcher();
			}
			else
			{
				EnsureActiveSlow();
			}
		}

		private void EnsureActiveSlow()
		{
			bool flag = false;
			do
			{
				IL_0002:
				switch (Interlocked.CompareExchange(ref _state, 1, 0))
				{
				default:
					goto IL_0002;
				case 0:
					flag = true;
					break;
				case 9:
					return;
				case 1:
					continue;
				case 2:
					break;
				}
				break;
			}
			while (Interlocked.CompareExchange(ref _state, 2, 1) != 1);
			if (flag)
			{
				_disposable.Disposable = _scheduler.Schedule<object>(null, Run);
			}
		}

		private void Run(object? state, Action<object?> recurse)
		{
			T result;
			while (!_queue.TryDequeue(out result))
			{
				if (_failed)
				{
					if (_queue.IsEmpty)
					{
						Interlocked.Exchange(ref _state, 0);
						_observer.OnError(_error);
						Dispose();
						return;
					}
				}
				else if (_completed)
				{
					if (_queue.IsEmpty)
					{
						Interlocked.Exchange(ref _state, 0);
						_observer.OnCompleted();
						Dispose();
						return;
					}
				}
				else
				{
					int num = Interlocked.CompareExchange(ref _state, 0, 1);
					if (num == 1 || num == 9)
					{
						return;
					}
					_state = 1;
				}
			}
			Interlocked.Exchange(ref _state, 1);
			try
			{
				_observer.OnNext(result);
			}
			catch
			{
				Interlocked.Exchange(ref _state, 9);
				T result2;
				while (_queue.TryDequeue(out result2))
				{
				}
				throw;
			}
			recurse(state);
		}

		protected override void OnNextCore(T value)
		{
			_queue.Enqueue(value);
		}

		protected override void OnErrorCore(Exception exception)
		{
			_error = exception;
			_failed = true;
		}

		protected override void OnCompletedCore()
		{
			_completed = true;
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			if (disposing)
			{
				_disposable.Dispose();
			}
		}
	}
	internal sealed class ObserveOnObserver<T> : ScheduledObserver<T>
	{
		private SingleAssignmentDisposableValue _run;

		public ObserveOnObserver(IScheduler scheduler, IObserver<T> observer)
			: base(scheduler, observer)
		{
		}

		public void Run(IObservable<T> source)
		{
			_run.Disposable = source.SubscribeSafe(this);
		}

		protected override void OnNextCore(T value)
		{
			base.OnNextCore(value);
			EnsureActive();
		}

		protected override void OnErrorCore(Exception exception)
		{
			base.OnErrorCore(exception);
			EnsureActive();
		}

		protected override void OnCompletedCore()
		{
			base.OnCompletedCore();
			EnsureActive();
		}

		protected override void Dispose(bool disposing)
		{
			base.Dispose(disposing);
			if (disposing)
			{
				_run.Dispose();
			}
		}
	}
	internal interface IScheduledObserver<T> : IObserver<T>, IDisposable
	{
		void EnsureActive();

		void EnsureActive(int count);
	}
	internal sealed class ObserveOnObserverNew<T> : IdentitySink<T>
	{
		private readonly IScheduler _scheduler;

		private readonly ConcurrentQueue<T> _queue;

		private IDisposable? _task;

		private int _wip;

		private bool _done;

		private Exception? _error;

		private bool _disposed;

		private static readonly Func<IScheduler, ObserveOnObserverNew<T>, IDisposable> DrainShortRunningFunc = (IScheduler scheduler, ObserveOnObserverNew<T> self) => self.DrainShortRunning(scheduler);

		public ObserveOnObserverNew(IScheduler scheduler, IObserver<T> downstream)
			: base(downstream)
		{
			_scheduler = scheduler;
			_queue = new ConcurrentQueue<T>();
		}

		protected override void Dispose(bool disposing)
		{
			Volatile.Write(ref _disposed, value: true);
			base.Dispose(disposing);
			if (disposing)
			{
				Disposable.Dispose(ref _task);
				Clear(_queue);
			}
		}

		private static void Clear(ConcurrentQueue<T> q)
		{
			T result;
			while (q.TryDequeue(out result))
			{
			}
		}

		public override void OnCompleted()
		{
			Volatile.Write(ref _done, value: true);
			Schedule();
		}

		public override void OnError(Exception error)
		{
			_error = error;
			Volatile.Write(ref _done, value: true);
			Schedule();
		}

		public override void OnNext(T value)
		{
			_queue.Enqueue(value);
			Schedule();
		}

		private void Schedule()
		{
			if (Interlocked.Increment(ref _wip) == 1)
			{
				SingleAssignmentDisposable singleAssignmentDisposable = new SingleAssignmentDisposable();
				if (Disposable.TrySetMultiple(ref _task, singleAssignmentDisposable))
				{
					singleAssignmentDisposable.Disposable = _scheduler.Schedule(this, DrainShortRunningFunc);
				}
				if (Volatile.Read(ref _disposed))
				{
					Clear(_queue);
				}
			}
		}

		private IDisposable DrainShortRunning(IScheduler recursiveScheduler)
		{
			DrainStep(_queue);
			if (Interlocked.Decrement(ref _wip) != 0)
			{
				IDisposable value = recursiveScheduler.Schedule(this, DrainShortRunningFunc);
				Disposable.TrySetMultiple(ref _task, value);
			}
			return Disposable.Empty;
		}

		private void DrainStep(ConcurrentQueue<T> q)
		{
			if (Volatile.Read(ref _disposed))
			{
				Clear(q);
				return;
			}
			bool flag = Volatile.Read(ref _done);
			if (flag)
			{
				Exception error = _error;
				if (error != null)
				{
					Volatile.Write(ref _disposed, value: true);
					ForwardOnError(error);
					return;
				}
			}
			if (q.TryDequeue(out T result))
			{
				ForwardOnNext(result);
			}
			else if (flag)
			{
				Volatile.Write(ref _disposed, value: true);
				ForwardOnCompleted();
			}
		}
	}
	internal sealed class ObserveOnObserverLongRunning<TSource> : IdentitySink<TSource>
	{
		private readonly ISchedulerLongRunning _scheduler;

		private readonly ConcurrentQueue<TSource> _queue;

		private readonly object _suspendGuard;

		private long _wip;

		private bool _done;

		private Exception? _error;

		private bool _disposed;

		private int _runDrainOnce;

		private SingleAssignmentDisposableValue _drainTask;

		private static readonly Action<ObserveOnObserverLongRunning<TSource>, ICancelable> DrainLongRunning = delegate(ObserveOnObserverLongRunning<TSource> self, ICancelable cancelable)
		{
			self.Drain();
		};

		public ObserveOnObserverLongRunning(ISchedulerLongRunning scheduler, IObserver<TSource> observer)
			: base(observer)
		{
			_scheduler = scheduler;
			_queue = new ConcurrentQueue<TSource>();
			_suspendGuard = new object();
		}

		public override void OnCompleted()
		{
			Volatile.Write(ref _done, value: true);
			Schedule();
		}

		public override void OnError(Exception error)
		{
			_error = error;
			Volatile.Write(ref _done, value: true);
			Schedule();
		}

		public override void OnNext(TSource value)
		{
			_queue.Enqueue(value);
			Schedule();
		}

		private void Schedule()
		{
			if (Volatile.Read(ref _runDrainOnce) == 0 && Interlocked.CompareExchange(ref _runDrainOnce, 1, 0) == 0)
			{
				_drainTask.Disposable = _scheduler.ScheduleLongRunning(this, DrainLongRunning);
			}
			if (Interlocked.Increment(ref _wip) == 1)
			{
				lock (_suspendGuard)
				{
					Monitor.Pulse(_suspendGuard);
				}
			}
		}

		protected override void Dispose(bool disposing)
		{
			Volatile.Write(ref _disposed, value: true);
			lock (_suspendGuard)
			{
				Monitor.Pulse(_suspendGuard);
			}
			_drainTask.Dispose();
			base.Dispose(disposing);
		}

		private void Drain()
		{
			ConcurrentQueue<TSource> queue = _queue;
			while (true)
			{
				if (Volatile.Read(ref _disposed))
				{
					TSource result;
					while (queue.TryDequeue(out result))
					{
					}
					return;
				}
				bool num = Volatile.Read(ref _done);
				TSource result2;
				bool flag = queue.TryDequeue(out result2);
				if (num && !flag)
				{
					break;
				}
				if (flag)
				{
					ForwardOnNext(result2);
					if (Interlocked.Decrement(ref _wip) != 0L)
					{
						continue;
					}
				}
				if (Volatile.Read(ref _wip) != 0L || Volatile.Read(ref _disposed))
				{
					continue;
				}
				object suspendGuard = _suspendGuard;
				if (Monitor.TryEnter(suspendGuard))
				{
					if (Volatile.Read(ref _wip) == 0L && !Volatile.Read(ref _disposed))
					{
						Monitor.Wait(suspendGuard);
					}
					Monitor.Exit(suspendGuard);
				}
			}
			Exception error = _error;
			if (error != null)
			{
				ForwardOnError(error);
			}
			else
			{
				ForwardOnCompleted();
			}
		}
	}
	internal interface ISink<in TTarget>
	{
		void ForwardOnNext(TTarget value);

		void ForwardOnCompleted();

		void ForwardOnError(Exception error);
	}
	internal abstract class Sink<TTarget> : ISink<TTarget>, IDisposable
	{
		private SingleAssignmentDisposableValue _upstream;

		private volatile IObserver<TTarget> _observer;

		protected Sink(IObserver<TTarget> observer)
		{
			_observer = observer;
		}

		public void Dispose()
		{
			if (Interlocked.Exchange(ref _observer, NopObserver<TTarget>.Instance) != NopObserver<TTarget>.Instance)
			{
				Dispose(disposing: true);
			}
		}

		protected virtual void Dispose(bool disposing)
		{
			_upstream.Dispose();
		}

		public void ForwardOnNext(TTarget value)
		{
			_observer.OnNext(value);
		}

		public void ForwardOnCompleted()
		{
			_observer.OnCompleted();
			Dispose();
		}

		public void ForwardOnError(Exception error)
		{
			_observer.OnError(error);
			Dispose();
		}

		protected void SetUpstream(IDisposable upstream)
		{
			_upstream.Disposable = upstream;
		}

		protected void DisposeUpstream()
		{
			_upstream.Dispose();
		}
	}
	internal abstract class Sink<TSource, TTarget> : Sink<TTarget>, IObserver<TSource>
	{
		private sealed class @_ : IObserver<TTarget>
		{
			private readonly Sink<TSource, TTarget> _forward;

			public _(Sink<TSource, TTarget> forward)
			{
				_forward = forward;
			}

			public void OnNext(TTarget value)
			{
				_forward.ForwardOnNext(value);
			}

			public void OnError(Exception error)
			{
				_forward.ForwardOnError(error);
			}

			public void OnCompleted()
			{
				_forward.ForwardOnCompleted();
			}
		}

		protected Sink(IObserver<TTarget> observer)
			: base(observer)
		{
		}

		public virtual void Run(IObservable<TSource> source)
		{
			SetUpstream(source.SubscribeSafe(this));
		}

		public abstract void OnNext(TSource value);

		public virtual void OnError(Exception error)
		{
			ForwardOnError(error);
		}

		public virtual void OnCompleted()
		{
			ForwardOnCompleted();
		}

		public IObserver<TTarget> GetForwarder()
		{
			return new @_(this);
		}
	}
	internal static class Stubs<T>
	{
		public static readonly Action<T> Ignore = delegate
		{
		};

		public static readonly Func<T, T> I = (T _) => _;
	}
	internal static class Stubs
	{
		public static readonly Action Nop = delegate
		{
		};

		public static readonly Action<Exception> Throw = delegate(Exception ex)
		{
			ex.Throw();
		};
	}
	internal static class TimerStubs
	{
		public static readonly System.Threading.Timer Never = new System.Threading.Timer(delegate
		{
		});
	}
	internal sealed class SynchronizedObserver<T> : ObserverBase<T>
	{
		private readonly object _gate;

		private readonly IObserver<T> _observer;

		public SynchronizedObserver(IObserver<T> observer, object gate)
		{
			_gate = gate;
			_observer = observer;
		}

		protected override void OnNextCore(T value)
		{
			lock (_gate)
			{
				_observer.OnNext(value);
			}
		}

		protected override void OnErrorCore(Exception exception)
		{
			lock (_gate)
			{
				_observer.OnError(exception);
			}
		}

		protected override void OnCompletedCore()
		{
			lock (_gate)
			{
				_observer.OnCompleted();
			}
		}
	}
	internal abstract class TailRecursiveSink<TSource> : IdentitySink<TSource>
	{
		private readonly Stack<IEnumerator<IObservable<TSource>>> _stack = new Stack<IEnumerator<IObservable<TSource>>>();

		private bool _isDisposed;

		private int _trampoline;

		private IDisposable? _currentSubscription;

		protected TailRecursiveSink(IObserver<TSource> observer)
			: base(observer)
		{
		}

		public void Run(IEnumerable<IObservable<TSource>> sources)
		{
			if (TryGetEnumerator(sources, out IEnumerator<IObservable<TSource>> result))
			{
				_stack.Push(result);
				Drain();
			}
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				DisposeAll();
			}
			base.Dispose(disposing);
		}

		private void Drain()
		{
			if (Interlocked.Increment(ref _trampoline) != 1)
			{
				return;
			}
			do
			{
				IL_000f:
				if (Volatile.Read(ref _isDisposed))
				{
					while (_stack.Count != 0)
					{
						_stack.Pop().Dispose();
					}
					Disposable.Dispose(ref _currentSubscription);
				}
				else if (_stack.Count != 0)
				{
					IEnumerator<IObservable<TSource>> enumerator = _stack.Peek();
					IObservable<TSource> source2 = null;
					try
					{
						if (enumerator.MoveNext())
						{
							source2 = enumerator.Current;
						}
					}
					catch (Exception error)
					{
						enumerator.Dispose();
						ForwardOnError(error);
						Volatile.Write(ref _isDisposed, value: true);
						goto IL_000f;
					}
					IObservable<TSource> observable;
					try
					{
						observable = Unpack<TSource>(source2);
					}
					catch (Exception error2)
					{
						if (!Fail(error2))
						{
							Volatile.Write(ref _isDisposed, value: true);
						}
						goto IL_000f;
					}
					if (observable == null)
					{
						_stack.Pop();
						enumerator.Dispose();
						goto IL_000f;
					}
					IEnumerable<IObservable<TSource>> enumerable = Extract(observable);
					if (enumerable != null)
					{
						if (TryGetEnumerator(enumerable, out IEnumerator<IObservable<TSource>> result))
						{
							_stack.Push(result);
						}
						else
						{
							Volatile.Write(ref _isDisposed, value: true);
						}
						goto IL_000f;
					}
					IDisposable ready = ReadyToken.Ready;
					if (Disposable.TrySetSingle(ref _currentSubscription, ready) != 0)
					{
						goto IL_000f;
					}
					IDisposable disposable = observable.SubscribeSafe(this);
					IDisposable disposable2 = Interlocked.CompareExchange(ref _currentSubscription, disposable, ready);
					if (disposable2 != ready)
					{
						disposable.Dispose();
						if (disposable2 == BooleanDisposable.True)
						{
							goto IL_000f;
						}
					}
				}
				else
				{
					Volatile.Write(ref _isDisposed, value: true);
					Done();
				}
			}
			while (Interlocked.Decrement(ref _trampoline) != 0);
			static IObservable<T>? Unpack<T>(IObservable<T>? source) where T : notnull
			{
				bool flag;
				do
				{
					flag = false;
					if (source is IEvaluatableObservable<T> evaluatableObservable)
					{
						source = evaluatableObservable.Eval();
						flag = true;
					}
				}
				while (flag);
				return source;
			}
		}

		private void DisposeAll()
		{
			Volatile.Write(ref _isDisposed, value: true);
			Drain();
		}

		protected void Recurse()
		{
			if (Disposable.TrySetSerial(ref _currentSubscription, null))
			{
				Drain();
			}
		}

		protected abstract IEnumerable<IObservable<TSource>>? Extract(IObservable<TSource> source);

		private bool TryGetEnumerator(IEnumerable<IObservable<TSource>> sources, [NotNullWhen(true)] out IEnumerator<IObservable<TSource>>? result)
		{
			try
			{
				result = sources.GetEnumerator();
				return true;
			}
			catch (Exception error)
			{
				ForwardOnError(error);
				result = null;
				return false;
			}
		}

		protected virtual void Done()
		{
			ForwardOnCompleted();
		}

		protected virtual bool Fail(Exception error)
		{
			ForwardOnError(error);
			return false;
		}
	}
	internal static class ReadyToken
	{
		private sealed class ReadyDisposable : IDisposable
		{
			public void Dispose()
			{
			}
		}

		internal static readonly IDisposable Ready = new ReadyDisposable();
	}
	public interface IObserver<in TValue, out TResult>
	{
		TResult OnNext(TValue value);

		TResult OnError(Exception exception);

		TResult OnCompleted();
	}
	[Experimental]
	public class ListObservable<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable, IObservable<object>
	{
		private readonly IDisposable _subscription;

		private readonly AsyncSubject<object> _subject = new AsyncSubject<object>();

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

		public T Value
		{
			get
			{
				Wait();
				if (_results.Count == 0)
				{
					throw new InvalidOperationException(Strings_Linq.NO_ELEMENTS);
				}
				return _results[_results.Count - 1];
			}
		}

		public T this[int index]
		{
			get
			{
				Wait();
				return _results[index];
			}
			set
			{
				Wait();
				_results[index] = value;
			}
		}

		public int Count
		{
			get
			{
				Wait();
				return _results.Count;
			}
		}

		public bool IsReadOnly => false;

		public ListObservable(IObservable<T> source)
		{
			if (source == null)
			{
				throw new ArgumentNullException("source");
			}
			_subscription = source.Subscribe(_results.Add, _subject.OnError, _subject.OnCompleted);
		}

		private void Wait()
		{
			_subject.DefaultIfEmpty().Wait();
		}

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

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

		public void RemoveAt(int index)
		{
			Wait();
			_results.RemoveAt(index);
		}

		public void Add(T item)
		{
			Wait();
			_results.Add(item);
		}

		public void Clear()
		{
			Wait();
			_results.Clear();
		}

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

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

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

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

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

		public IDisposable Subscribe(IObserver<object> observer)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			return StableCompositeDisposable.Create(_subscription, _subject.Subscribe(observer));
		}
	}
	[CompilerGenerated]
	internal class NamespaceDoc
	{
	}
	public enum NotificationKind
	{
		OnNext,
		OnError,
		OnCompleted
	}
	[Serializable]
	public abstract class Notification<T> : IEquatable<Notification<T>>
	{
		[Serializable]
		[DebuggerDisplay("OnNext({Value})")]
		internal sealed class OnNextNotification : Notification<T>
		{
			public override T Value { get; }

			public override Exception? Exception => null;

			public override bool HasValue => true;

			public override NotificationKind Kind => NotificationKind.OnNext;

			public OnNextNotification(T value)
			{
				Value = value;
			}

			public override int GetHashCode()
			{
				T value = Value;
				if (value == null)
				{
					return 0;
				}
				return value.GetHashCode();
			}

			public override bool Equals(Notification<T>? other)
			{
				if ((object)this == other)
				{
					return true;
				}
				if ((object)other == null)
				{
					return false;
				}
				if (other.Kind != 0)
				{
					return false;
				}
				return EqualityComparer<T>.Default.Equals(Value, other.Value);
			}

			public override string ToString()
			{
				return string.Format(CultureInfo.CurrentCulture, "OnNext({0})", Value);
			}

			public override void Accept(IObserver<T> observer)
			{
				if (observer == null)
				{
					throw new ArgumentNullException("observer");
				}
				observer.OnNext(Value);
			}

			public override TResult Accept<TResult>(IObserver<T, TResult> observer)
			{
				if (observer == null)
				{
					throw new ArgumentNullException("observer");
				}
				return observer.OnNext(Value);
			}

			public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
			{
				if (onNext == null)
				{
					throw new ArgumentNullException("onNext");
				}
				if (onError == null)
				{
					throw new ArgumentNullException("onError");
				}
				if (onCompleted == null)
				{
					throw new ArgumentNullException("onCompleted");
				}
				onNext(Value);
			}

			public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted)
			{
				if (onNext == null)
				{
					throw new ArgumentNullException("onNext");
				}
				if (onError == null)
				{
					throw new ArgumentNullException("onError");
				}
				if (onCompleted == null)
				{
					throw new ArgumentNullException("onCompleted");
				}
				return onNext(Value);
			}
		}

		[Serializable]
		[DebuggerDisplay("OnError({Exception})")]
		internal sealed class OnErrorNotification : Notification<T>
		{
			public override T Value
			{
				get
				{
					Exception.Throw();
					return default(T);
				}
			}

			public override Exception Exception { get; }

			public override bool HasValue => false;

			public override NotificationKind Kind => NotificationKind.OnError;

			public OnErrorNotification(Exception exception)
			{
				Exception = exception;
			}

			public override int GetHashCode()
			{
				return Exception.GetHashCode();
			}

			public override bool Equals(Notification<T>? other)
			{
				if ((object)this == other)
				{
					return true;
				}
				if ((object)other == null)
				{
					return false;
				}
				if (other.Kind != NotificationKind.OnError)
				{
					return false;
				}
				return object.Equals(Exception, other.Exception);
			}

			public override string ToString()
			{
				return string.Format(CultureInfo.CurrentCulture, "OnError({0})", Exception.GetType().FullName);
			}

			public override void Accept(IObserver<T> observer)
			{
				if (observer == null)
				{
					throw new ArgumentNullException("observer");
				}
				observer.OnError(Exception);
			}

			public override TResult Accept<TResult>(IObserver<T, TResult> observer)
			{
				if (observer == null)
				{
					throw new ArgumentNullException("observer");
				}
				return observer.OnError(Exception);
			}

			public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
			{
				if (onNext == null)
				{
					throw new ArgumentNullException("onNext");
				}
				if (onError == null)
				{
					throw new ArgumentNullException("onError");
				}
				if (onCompleted == null)
				{
					throw new ArgumentNullException("onCompleted");
				}
				onError(Exception);
			}

			public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted)
			{
				if (onNext == null)
				{
					throw new ArgumentNullException("onNext");
				}
				if (onError == null)
				{
					throw new ArgumentNullException("onError");
				}
				if (onCompleted == null)
				{
					throw new ArgumentNullException("onCompleted");
				}
				return onError(Exception);
			}
		}

		[Serializable]
		[DebuggerDisplay("OnCompleted()")]
		internal sealed class OnCompletedNotification : Notification<T>
		{
			internal static readonly Notification<T> Instance = new Notification<T>.OnCompletedNotification();

			public override T Value
			{
				get
				{
					throw new InvalidOperationException(Strings_Core.COMPLETED_NO_VALUE);
				}
			}

			public override Exception? Exception => null;

			public override bool HasValue => false;

			public override NotificationKind Kind => NotificationKind.OnCompleted;

			private OnCompletedNotification()
			{
			}

			public override int GetHashCode()
			{
				return typeof(T).GetHashCode() ^ 0x213E;
			}

			public override bool Equals(Notification<T>? other)
			{
				if ((object)this == other)
				{
					return true;
				}
				if ((object)other == null)
				{
					return false;
				}
				return other.Kind == NotificationKind.OnCompleted;
			}

			public override string ToString()
			{
				return "OnCompleted()";
			}

			public override void Accept(IObserver<T> observer)
			{
				if (observer == null)
				{
					throw new ArgumentNullException("observer");
				}
				observer.OnCompleted();
			}

			public override TResult Accept<TResult>(IObserver<T, TResult> observer)
			{
				if (observer == null)
				{
					throw new ArgumentNullException("observer");
				}
				return observer.OnCompleted();
			}

			public override void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted)
			{
				if (onNext == null)
				{
					throw new ArgumentNullException("onNext");
				}
				if (onError == null)
				{
					throw new ArgumentNullException("onError");
				}
				if (onCompleted == null)
				{
					throw new ArgumentNullException("onCompleted");
				}
				onCompleted();
			}

			public override TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted)
			{
				if (onNext == null)
				{
					throw new ArgumentNullException("onNext");
				}
				if (onError == null)
				{
					throw new ArgumentNullException("onError");
				}
				if (onCompleted == null)
				{
					throw new ArgumentNullException("onCompleted");
				}
				return onCompleted();
			}
		}

		private sealed class NotificationToObservable : ObservableBase<T>
		{
			private readonly IScheduler _scheduler;

			private readonly Notification<T> _parent;

			public NotificationToObservable(IScheduler scheduler, Notification<T> parent)
			{
				_scheduler = scheduler;
				_parent = parent;
			}

			protected override IDisposable SubscribeCore(IObserver<T> observer)
			{
				return _scheduler.ScheduleAction((_parent, observer), delegate((Notification<T> _parent, IObserver<T> observer) state)
				{
					var (notification, observer2) = state;
					notification.Accept(observer2);
					if (notification.Kind == NotificationKind.OnNext)
					{
						observer2.OnCompleted();
					}
				});
			}
		}

		public abstract T Value { get; }

		public abstract bool HasValue { get; }

		public abstract Exception? Exception { get; }

		public abstract NotificationKind Kind { get; }

		protected internal Notification()
		{
		}

		public abstract bool Equals(Notification<T>? other);

		public static bool operator ==(Notification<T> left, Notification<T> right)
		{
			if ((object)left == right)
			{
				return true;
			}
			if ((object)left == null || (object)right == null)
			{
				return false;
			}
			return left.Equals(right);
		}

		public static bool operator !=(Notification<T> left, Notification<T> right)
		{
			return !(left == right);
		}

		public override bool Equals(object? obj)
		{
			return Equals(obj as Notification<T>);
		}

		public abstract void Accept(IObserver<T> observer);

		public abstract TResult Accept<TResult>(IObserver<T, TResult> observer);

		public abstract void Accept(Action<T> onNext, Action<Exception> onError, Action onCompleted);

		public abstract TResult Accept<TResult>(Func<T, TResult> onNext, Func<Exception, TResult> onError, Func<TResult> onCompleted);

		public IObservable<T> ToObservable()
		{
			return ToObservable(ImmediateScheduler.Instance);
		}

		public IObservable<T> ToObservable(IScheduler scheduler)
		{
			if (scheduler == null)
			{
				throw new ArgumentNullException("scheduler");
			}
			return new NotificationToObservable(scheduler, this);
		}
	}
	public static class Notification
	{
		public static Notification<T> CreateOnNext<T>(T value)
		{
			return new Notification<T>.OnNextNotification(value);
		}

		public static Notification<T> CreateOnError<T>(Exception error)
		{
			if (error == null)
			{
				throw new ArgumentNullException("error");
			}
			return new Notification<T>.OnErrorNotification(error);
		}

		public static Notification<T> CreateOnCompleted<T>()
		{
			return Notification<T>.OnCompletedNotification.Instance;
		}
	}
	public abstract class ObservableBase<T> : IObservable<T>
	{
		public IDisposable Subscribe(IObserver<T> observer)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			AutoDetachObserver<T> autoDetachObserver = new AutoDetachObserver<T>(observer);
			if (CurrentThreadScheduler.IsScheduleRequired)
			{
				((IScheduler)CurrentThreadScheduler.Instance).ScheduleAction(autoDetachObserver, (Action<AutoDetachObserver<T>>)ScheduledSubscribe);
			}
			else
			{
				try
				{
					autoDetachObserver.SetResource(SubscribeCore(autoDetachObserver));
				}
				catch (Exception error)
				{
					if (!autoDetachObserver.Fail(error))
					{
						throw;
					}
				}
			}
			return autoDetachObserver;
		}

		private void ScheduledSubscribe(AutoDetachObserver<T> autoDetachObserver)
		{
			try
			{
				autoDetachObserver.SetResource(SubscribeCore(autoDetachObserver));
			}
			catch (Exception error)
			{
				if (!autoDetachObserver.Fail(error))
				{
					throw;
				}
			}
		}

		protected abstract IDisposable SubscribeCore(IObserver<T> observer);
	}
	[RequiresUnreferencedCode("This type uses Queryable.AsQueryable, which is not compatible with trimming because expressions referencing IQueryable extension methods can get rebound to IEnumerable extension methods, and those IEnumerable methods might be trimmed.")]
	internal class ObservableQueryProvider : IQbservableProvider, IQueryProvider
	{
		private static MethodInfo? _staticAsQueryable;

		private static MethodInfo AsQueryable => _staticAsQueryable ?? (_staticAsQueryable = Qbservable.InfoOf((Expression<Func<object>>)(() => ((IEnumerable<object>)null).AsQueryable())).GetGenericMethodDefinition());

		public IQbservable<TResult> CreateQuery<TResult>(Expression expression)
		{
			if (expression == null)
			{
				throw new ArgumentNullException("expression");
			}
			if (!typeof(IObservable<TResult>).IsAssignableFrom(expression.Type))
			{
				throw new ArgumentException(Strings_Providers.INVALID_TREE_TYPE, "expression");
			}
			return new ObservableQuery<TResult>(expression);
		}

		IQueryable<TElement> IQueryProvider.CreateQuery<TElement>(Expression expression)
		{
			if (!(expression is MethodCallExpression methodCallExpression) || methodCallExpression.Method.DeclaringType != typeof(Qbservable) || methodCallExpression.Method.Name != "ToQueryable")
			{
				throw new ArgumentException(Strings_Providers.EXPECTED_TOQUERYABLE_METHODCALL, "expression");
			}
			Expression arg = methodCallExpression.Arguments[0];
			return Expression.Lambda<Func<IQueryable<TElement>>>(Expression.Call(AsQueryable.MakeGenericMethod(typeof(TElement)), Expression.Call(typeof(Observable).GetMethod("ToEnumerable").MakeGenericMethod(typeof(TElement)), arg)), Array.Empty<ParameterExpression>()).Compile()();
		}

		IQueryable IQueryProvider.CreateQuery(Expression expression)
		{
			throw new NotImplementedException();
		}

		TResult IQueryProvider.Execute<TResult>(Expression expression)
		{
			throw new NotImplementedException();
		}

		object IQueryProvider.Execute(Expression expression)
		{
			throw new NotImplementedException();
		}
	}
	[RequiresUnreferencedCode("This type uses Queryable.AsQueryable, which is not compatible with trimming because expressions referencing IQueryable extension methods can get rebound to IEnumerable extension methods, and those IEnumerable methods might be trimmed.")]
	internal class ObservableQuery
	{
		protected object? _source;

		protected Expression _expression;

		public object? Source => _source;

		public Expression Expression => _expression;

		public ObservableQuery(object source)
		{
			_source = source;
			_expression = System.Linq.Expressions.Expression.Constant(this);
		}

		public ObservableQuery(Expression expression)
		{
			_expression = expression;
		}
	}
	[RequiresUnreferencedCode("This type uses Queryable.AsQueryable, which is not compatible with trimming because expressions referencing IQueryable extension methods can get rebound to IEnumerable extension methods, and those IEnumerable methods might be trimmed.")]
	internal class ObservableQuery<TSource> : ObservableQuery, IQbservable<TSource>, IQbservable, IObservable<TSource>
	{
		[RequiresUnreferencedCode("This type uses Queryable.AsQueryable, which is not compatible with trimming because expressions referencing IQueryable extension methods can get rebound to IEnumerable extension methods, and those IEnumerable methods might be trimmed.")]
		private class ObservableRewriter : ExpressionVisitor
		{
			private class Lazy<T>
			{
				private readonly Func<T> _factory;

				private T? _value;

				private bool _initialized;

				public T Value
				{
					get
					{
						lock (_factory)
						{
							if (!_initialized)
							{
								_value = _factory();
								_initialized = true;
							}
						}
						return _value;
					}
				}

				public Lazy(Func<T> factory)
				{
					_factory = factory;
				}
			}

			private static readonly Lazy<ILookup<string, MethodInfo>> ObservableMethods = new Lazy<ILookup<string, MethodInfo>>(() => GetMethods(typeof(Observable)));

			protected override Expression VisitConstant(ConstantExpression node)
			{
				if (node.Value is ObservableQuery observableQuery)
				{
					object source = observableQuery.Source;
					if (source != null)
					{
						return System.Linq.Expressions.Expression.Constant(source);
					}
					return Visit(observableQuery.Expression);
				}
				return node;
			}

			protected override Expression VisitMethodCall(MethodCallExpression node)
			{
				MethodInfo method = node.Method;
				if (method.DeclaringType?.BaseType == typeof(QueryablePattern))
				{
					if (method.Name == "Then")
					{
						return System.Linq.Expressions.Expression.Call(Visit(node.Object), arguments: node.Arguments.Select((Expression arg) => Unquote(Visit(arg))).ToArray(), methodName: method.Name, typeArguments: method.GetGenericArguments());
					}
					if (method.Name == "And")
					{
						return System.Linq.Expressions.Expression.Call(Visit(node.Object), arguments: node.Arguments.Select((Expression arg) => Visit(arg)).ToArray(), methodName: method.Name, typeArguments: method.GetGenericArguments());
					}
				}
				else
				{
					IEnumerable<Expression> enumerable = node.Arguments.AsEnumerable();
					bool flag = false;
					ParameterInfo parameterInfo = method.GetParameters().FirstOrDefault();
					if (parameterInfo != null)
					{
						Type parameterType = parameterInfo.ParameterType;
						if (parameterType == typeof(IQbservableProvider))
						{
							flag = true;
							if (!(System.Linq.Expressions.Expression.Lambda<Func<IQbservableProvider>>(Visit(node.Arguments[0]), Array.Empty<ParameterExpression>()).Compile()() is ObservableQueryProvider))
							{
								return node;
							}
							enumerable = enumerable.Skip(1);
						}
						else if (typeof(IQbservable).IsAssignableFrom(parameterType))
						{
							flag = true;
						}
					}
					if (flag)
					{
						IList<Expression> arguments3 = VisitQbservableOperatorArguments(method, enumerable);
						return FindObservableMethod(method, arguments3);
					}
				}
				return base.VisitMethodCall(node);
			}

			protected override Expression VisitLambda<T>(Expression<T> node)
			{
				return node;
			}

			private IList<Expression> VisitQbservableOperatorArguments(MethodInfo method, IEnumerable<Expression> arguments)
			{
				if (method.Name == "When")
				{
					Expression expression = arguments.Last();
					if (expression.NodeType == ExpressionType.NewArrayInit)
					{
						NewArrayExpression newArrayExpression = (NewArrayExpression)expression;
						List<Expression> list = new List<Expression>();
						list.Add(System.Linq.Expressions.Expression.NewArrayInit(typeof(Plan<>).MakeGenericType(method.GetGenericArguments()[0]), newArrayExpression.Expressions.Select((Expression param) => Visit(param))));
						return list;
					}
				}
				return arguments.Select((Expression arg) => Visit(arg)).ToList();
			}

			private static MethodCallExpression FindObservableMethod(MethodInfo method, IList<Expression> arguments)
			{
				IList<Expression> arguments2 = arguments;
				Type type;
				ILookup<string, MethodInfo> lookup;
				if (method.DeclaringType == typeof(Qbservable))
				{
					type = typeof(Observable);
					lookup = ObservableMethods.Value;
				}
				else
				{
					type = method.DeclaringType;
					if (type.IsDefined(typeof(LocalQueryMethodImplementationTypeAttribute), inherit: false))
					{
						type = ((LocalQueryMethodImplementationTypeAttribute)type.GetCustomAttributes(typeof(LocalQueryMethodImplementationTypeAttribute), inherit: false)[0]).TargetType;
					}
					lookup = GetMethods(type);
				}
				Type[] typeArgs = (method.IsGenericMethod ? method.GetGenericArguments() : null);
				MethodInfo methodInfo = lookup[method.Name].FirstOrDefault((MethodInfo candidateMethod) => ArgsMatch(candidateMethod, arguments2, typeArgs)) ?? throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Strings_Providers.NO_MATCHING_METHOD_FOUND, method.Name, type.Name));
				if (typeArgs != null)
				{
					methodInfo = methodInfo.MakeGenericMethod(typeArgs);
				}
				ParameterInfo[] parameters = methodInfo.GetParameters();
				int i = 0;
				for (int num = parameters.Length; i < num; i++)
				{
					arguments2[i] = Unquote(arguments2[i]);
				}
				return System.Linq.Expressions.Expression.Call(null, methodInfo, arguments2);
			}

			private static ILookup<string, MethodInfo> GetMethods(Type type)
			{
				return type.GetTypeInfo().DeclaredMethods.Where((MethodInfo m) => m.IsStatic && m.IsPublic).ToLookup((MethodInfo m) => m.Name);
			}

			private static bool ArgsMatch(MethodInfo method, IList<Expression> arguments, Type[]? typeArgs)
			{
				ParameterInfo[] parameters = method.GetParameters();
				if (parameters.Length != arguments.Count)
				{
					return false;
				}
				if (!method.IsGenericMethod && typeArgs != null && typeArgs.Length != 0)
				{
					return false;
				}
				if (method.IsGenericMethodDefinition)
				{
					if (typeArgs == null)
					{
						return false;
					}
					if (method.GetGenericArguments().Length != typeArgs.Length)
					{
						return false;
					}
					parameters = method.MakeGenericMethod(typeArgs).GetParameters();
				}
				int i = 0;
				for (int count = arguments.Count; i < count; i++)
				{
					Type parameterType = parameters[i].ParameterType;
					Expression expression = arguments[i];
					if (!parameterType.IsAssignableFrom(expression.Type))
					{
						expression = Unquote(expression);
						if (!parameterType.IsAssignableFrom(expression.Type))
						{
							return false;
						}
					}
				}
				return true;
			}

			private static Expression Unquote(Expression expression)
			{
				while (expression.NodeType == ExpressionType.Quote)
				{
					expression = ((UnaryExpression)expression).Operand;
				}
				return expression;
			}
		}

		public Type ElementType => typeof(TSource);

		public IQbservableProvider Provider => Qbservable.Provider;

		internal ObservableQuery(IObservable<TSource> source)
			: base(source)
		{
		}

		internal ObservableQuery(Expression expression)
			: base(expression)
		{
		}

		public IDisposable Subscribe(IObserver<TSource> observer)
		{
			if (_source == null)
			{
				Expression<Func<IObservable<TSource>>> expression = System.Linq.Expressions.Expression.Lambda<Func<IObservable<TSource>>>(new ObservableRewriter().Visit(_expression), Array.Empty<ParameterExpression>());
				_source = expression.Compile()();
			}
			return ((IObservable<TSource>)_source).Subscribe(observer);
		}

		public override string? ToString()
		{
			if (_expression is ConstantExpression constantExpression && constantExpression.Value == this)
			{
				if (_source != null)
				{
					return _source.ToString();
				}
				return "null";
			}
			return _expression.ToString();
		}
	}
	public static class Observer
	{
		private class AnonymousProgress<T> : IProgress<T>
		{
			private readonly Action<T> _progress;

			public AnonymousProgress(Action<T> progress)
			{
				_progress = progress;
			}

			public void Report(T value)
			{
				_progress(value);
			}
		}

		public static IObserver<T> ToObserver<T>(this Action<Notification<T>> handler)
		{
			Action<Notification<T>> handler2 = handler;
			if (handler2 == null)
			{
				throw new ArgumentNullException("handler");
			}
			return new AnonymousObserver<T>(delegate(T x)
			{
				handler2(Notification.CreateOnNext(x));
			}, delegate(Exception exception)
			{
				handler2(Notification.CreateOnError<T>(exception));
			}, delegate
			{
				handler2(Notification.CreateOnCompleted<T>());
			});
		}

		public static Action<Notification<T>> ToNotifier<T>(this IObserver<T> observer)
		{
			IObserver<T> observer2 = observer;
			if (observer2 == null)
			{
				throw new ArgumentNullException("observer");
			}
			return delegate(Notification<T> n)
			{
				n.Accept(observer2);
			};
		}

		public static IObserver<T> Create<T>(Action<T> onNext)
		{
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			return new AnonymousObserver<T>(onNext);
		}

		public static IObserver<T> Create<T>(Action<T> onNext, Action<Exception> onError)
		{
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onError == null)
			{
				throw new ArgumentNullException("onError");
			}
			return new AnonymousObserver<T>(onNext, onError);
		}

		public static IObserver<T> Create<T>(Action<T> onNext, Action onCompleted)
		{
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onCompleted == null)
			{
				throw new ArgumentNullException("onCompleted");
			}
			return new AnonymousObserver<T>(onNext, onCompleted);
		}

		public static IObserver<T> Create<T>(Action<T> onNext, Action<Exception> onError, Action onCompleted)
		{
			if (onNext == null)
			{
				throw new ArgumentNullException("onNext");
			}
			if (onError == null)
			{
				throw new ArgumentNullException("onError");
			}
			if (onCompleted == null)
			{
				throw new ArgumentNullException("onCompleted");
			}
			return new AnonymousObserver<T>(onNext, onError, onCompleted);
		}

		public static IObserver<T> AsObserver<T>(this IObserver<T> observer)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			return new AnonymousObserver<T>(observer.OnNext, observer.OnError, observer.OnCompleted);
		}

		public static IObserver<T> Checked<T>(this IObserver<T> observer)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			return new CheckedObserver<T>(observer);
		}

		public static IObserver<T> Synchronize<T>(IObserver<T> observer)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			return new SynchronizedObserver<T>(observer, new object());
		}

		public static IObserver<T> Synchronize<T>(IObserver<T> observer, bool preventReentrancy)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			if (preventReentrancy)
			{
				return new AsyncLockObserver<T>(observer, new AsyncLock());
			}
			return new SynchronizedObserver<T>(observer, new object());
		}

		public static IObserver<T> Synchronize<T>(IObserver<T> observer, object gate)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			if (gate == null)
			{
				throw new ArgumentNullException("gate");
			}
			return new SynchronizedObserver<T>(observer, gate);
		}

		public static IObserver<T> Synchronize<T>(IObserver<T> observer, AsyncLock asyncLock)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			if (asyncLock == null)
			{
				throw new ArgumentNullException("asyncLock");
			}
			return new AsyncLockObserver<T>(observer, asyncLock);
		}

		public static IObserver<T> NotifyOn<T>(this IObserver<T> observer, IScheduler scheduler)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			if (scheduler == null)
			{
				throw new ArgumentNullException("scheduler");
			}
			return new ObserveOnObserver<T>(scheduler, observer);
		}

		public static IObserver<T> NotifyOn<T>(this IObserver<T> observer, SynchronizationContext context)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			if (context == null)
			{
				throw new ArgumentNullException("context");
			}
			return new ObserveOnObserver<T>(new SynchronizationContextScheduler(context), observer);
		}

		public static IProgress<T> ToProgress<T>(this IObserver<T> observer)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			return new AnonymousProgress<T>(observer.OnNext);
		}

		public static IProgress<T> ToProgress<T>(this IObserver<T> observer, IScheduler scheduler)
		{
			if (observer == null)
			{
				throw new ArgumentNullException("observer");
			}
			if (scheduler == null)
			{
				throw new ArgumentNullException("scheduler");
			}
			return new AnonymousProgress<T>(new ObserveOnObserver<T>(scheduler, observer).OnNext);
		}

		public static IObserver<T> ToObserver<T>(this IProgress<T> progress)
		{
			if (progress == null)
			{
				throw new ArgumentNullException("progress");
			}
			return new AnonymousObserver<T>(progress.Re